Lesson 15 of 59Data and storage
PostgreSQL for Developers
Run Postgres in Docker, design tables with the right types and keys, read query plans, and understand transactions and connection pools.
Your API now has routes, dependencies, settings, errors and auth, but its data still lives in memory. This unit gives it a real database. Almost every Python backend you join will store its data in PostgreSQL. The ORM hides a lot of it, but the database is still where your slow queries, deadlocks, duplicate rows and "too many connections" outages come from. Developers who can open psql, read a query plan and explain what a transaction protects them from fix those problems in minutes instead of days. This lesson gives you that working knowledge before the next lesson puts SQLAlchemy on top. It assumes the SQL & Databases course; where a topic gets only a paragraph here, that course has the full lesson.
Why Postgres
PostgreSQL (usually just "Postgres") is a free, open-source relational database with decades of development behind it. Teams pick it as the default for a few reasons:
- Correctness first. Constraints, foreign keys and transactions are strict and well tested. It refuses bad data instead of quietly storing it.
- Rich types. Real timestamps with time zones, UUIDs, arrays, ranges and
jsonbfor semi-structured data, so you rarely need a second database early on. - Everywhere. Every cloud offers managed Postgres (Amazon RDS, Google Cloud SQL, Azure, Neon, Supabase), and every Python tool supports it.
SQLite is great for tests and small tools, and MySQL is a fine choice too. But when nobody has a strong reason to pick something else, Postgres is the answer.
Running it locally with Docker
You do not install Postgres on your laptop any more. You run it in a container, the same version as production, and throw it away when you like:
docker run --name pg -d \ -e POSTGRES_USER=app -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=app \ -p 5432:5432 -v pgdata:/var/lib/postgresql/data \ postgres:17The -e variables create a user and a database on first start. -p 5432:5432 exposes the default port, and the named volume pgdata keeps your data when the container is removed. Pin the major version to whatever production runs. Your app then connects with a URL like postgresql://app:secret@localhost:5432/app. Most teams put this in a compose.yaml so docker compose up starts the database next to the API.
psql, the tool you will use every week
psql is Postgres's command-line client. Open it inside the container:
docker exec -it pg psql -U app -d appLines starting with a backslash are psql commands, not SQL. These few cover most days:
| Command | What it does |
|---|---|
\l | List databases |
\dt | List tables |
\d todos | Describe a table: columns, types, indexes, foreign keys |
\x | Toggle expanded output, one column per line, for wide rows |
\timing | Print how long each query took |
\q | Quit |
Everything else is plain SQL ending with a semicolon.
Tables, types and keys
Here is a schema for users and their todos, written the way a careful Postgres developer would:
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE todos (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users (id) ON DELETE CASCADE,
title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
done boolean NOT NULL DEFAULT false,
price numeric(10, 2),
due_at timestamptz
);A few choices worth copying:
bigint ... GENERATED ALWAYS AS IDENTITYis the modern auto-incrementing id.bigintmeans you never run out at two billion rows. Some teams useuuidids instead, which are safe to generate anywhere and do not reveal how many rows you have.textfor strings. In Postgres,textandvarchar(n)perform the same; use aCHECKwhen you need a length limit.timestamptz, never plaintimestamp. It stores an exact moment in UTC and converts on the way out. Plaintimestamphas no time zone, and that becomes a bug the first time a user travels.numericfor money. Floats cannot store 0.10 exactly.NOT NULLby default. Every nullable column is a question your code has to answer forever.
The primary key identifies each row. The foreign key REFERENCES users (id) makes Postgres reject a todo for a user who does not exist, and ON DELETE CASCADE deletes a user's todos with them. UNIQUE and CHECK push rules into the database, where no buggy endpoint or race condition can skip them.
Indexes and EXPLAIN
This is the short version of How Indexes Work and Reading EXPLAIN and EXPLAIN ANALYZE from the SQL & Databases course. Without an index, finding WHERE user_id = 42 means reading every row: a sequential scan. An index is a separate, sorted structure (a B-tree by default) that lets Postgres jump to matching rows, like the index at the back of a book. Postgres indexes primary keys and UNIQUE columns automatically. It does not index foreign keys for you, so add those yourself:
CREATE INDEX ix_todos_user_id ON todos (user_id);
CREATE INDEX ix_todos_user_done ON todos (user_id, done); -- a composite indexTo see what Postgres plans to do, put EXPLAIN in front of a query. EXPLAIN ANALYZE actually runs it and shows real timings:
EXPLAIN ANALYZE SELECT * FROM todos WHERE user_id = 42 AND done = false;Index Scan using ix_todos_user_done on todos (cost=0.43..8.61 rows=3 width=72)
(actual time=0.031..0.035 rows=3 loops=1)
Index Cond: ((user_id = 42) AND (done = false))
Execution Time: 0.061 msYou do not need to understand every number. Look for three things: Seq Scan on a big table (missing index?), estimated rows wildly different from actual rows (stale statistics, run ANALYZE), and which step takes the time. A composite index on (user_id, done) serves queries that filter on user_id alone or on both, but not on done alone: the leftmost column has to be used.
Indexes are not free. Each one slows every insert and update a little and takes disk space, so add them for real queries you can see in EXPLAIN, not "just in case". On a busy production table, use CREATE INDEX CONCURRENTLY so you do not block writes while it builds.
(user_id, created_at). Which query can use it efficiently?Transactions and isolation
Transactions and ACID and Isolation Levels and Anomalies cover this in depth; here is what you need day to day. A transaction wraps several statements so they all happen or none do. Postgres guarantees ACID: changes are Atomic, keep the database Consistent with its constraints, are Isolated from other transactions, and are Durable once committed.
You can try atomicity right here with SQLite, which follows the same rules:
Press Run (⌘ Enter) to see what happens.The second transfer credited Ada first, then failed the CHECK on Sam's balance. The rollback undid the credit too, so no money appeared from nowhere.
Isolation is about what concurrent transactions see of each other. Postgres's default level is Read Committed: each statement sees data committed before it started. That is fine for most web requests, but it allows the classic lost update:
Two people buy the last items at the same moment. A reads stock = 5.
The stricter levels are Repeatable Read (the whole transaction sees one snapshot) and Serializable (Postgres guarantees the result matches some one-at-a-time order). Both can abort a transaction with a serialization error when they detect a conflict, so your code must be ready to retry. Most teams stay on Read Committed and use atomic updates, row locks and unique constraints where it matters. Keep transactions short: an open transaction holds locks, and a request that waits on an external API inside one blocks everyone who needs those rows.
JSONB in one paragraph
A jsonb column stores JSON in a parsed binary form you can query: settings->>'theme' returns a field as text, and WHERE tags @> '["urgent"]' checks containment, which a GIN index can speed up. It is ideal for data whose shape varies, like webhook payloads or per-customer settings. It is a poor replacement for real columns: you lose types, NOT NULL, foreign keys and simple migrations. Use columns for what you query and validate, and jsonb for the long tail.
Connection pooling
Opening a Postgres connection is expensive. Postgres starts a separate server process for each one, with its own memory, and the handshake (plus TLS) takes several milliseconds. The server also has a hard limit, max_connections, which is often 100 by default and not much higher on small managed plans.
So web apps keep a pool: a set of open connections that requests borrow and return. SQLAlchemy's engine does this for you, with a small default pool per process plus some overflow. The trap is multiplication: every worker process has its own pool.
Each worker process has its own pool. 2 servers × 4 workers × (5 pooled + 10 overflow) is up to 120 connections, already past a limit of 100.
Practical rules: do the multiplication before you scale out, keep pools small (a few connections per worker is usually plenty), set pool_pre_ping=True so dead connections are replaced, and add a pooler before you add servers. If you see FATAL: sorry, too many clients already, this diagram is why.
Match each tool to the problem it solves.
Three servers each run 4 workers. Each worker's pool allows 5 connections plus 5 overflow. What is the maximum number of Postgres connections?
print(3 * 4 * (5 + 5))
- psql
- Postgres's command-line client. Backslash commands like
\dtand\d tableinspect the schema. - timestamptz
- A timestamp stored as an exact UTC instant. The right default for any point in time.
- EXPLAIN ANALYZE
- Runs a query and shows the plan Postgres chose, with real row counts and timings.
- isolation level
- How much concurrent transactions see of each other. Postgres defaults to Read Committed.
- lost update
- Two transactions read the same value and both write, so one change silently disappears.
- jsonb
- A queryable binary JSON column type, indexable with GIN. Good for varying shapes, not a replacement for columns.
- connection pool
- A set of open database connections that requests borrow and return, avoiding the cost of reconnecting.