Skip to content

About

Lab for concurrency patterns at enterprise grade

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

dblab

A minimal Python + Postgres playground: uv for dependencies, devbox for a reproducible dev environment (Python-independent Postgres included), SQLAlchemy models for users / orders / notifications, Alembic migrations, pytest, and a Jupyter notebook that exercises the same database as the tests.

Prerequisites

  • devbox — manages Postgres and uv for you, no system-wide installs needed.

uv itself is also fine to have installed globally; either way devbox provides a pinned version.

First-time setup

devbox shell            # enters the dev environment (installs uv + postgresql@16 on first run)
devbox services start postgresql
devbox run db:create    # creates dblab_dev and dblab_test databases (safe to re-run)
uv sync                 # installs Python dependencies into .venv
devbox run migrate      # applies Alembic migrations to dblab_dev

Copy .env.example to .env if you want to override the connection strings (defaults already match the devbox Postgres instance):

cp .env.example .env

Running things

devbox run test         # uv run pytest — spins migrations up/down against dblab_test
devbox run notebook     # uv run jupyter notebook notebooks/
devbox run migrate      # uv run alembic upgrade head

devbox run psql opens an interactive psql shell against dblab_dev. For a one-off SQL command instead, wrap it: devbox run -- bash -c "psql -h localhost -p 5432 -U postgres -d dblab_dev -c '...'" (devbox matches the psql script name even after --, so a bare devbox run -- psql ... silently runs the interactive script instead of your arguments).

Schema

  • users — id, email (unique), full_name, created_at
  • orders — belongs to a user; status (pending/paid/shipped/cancelled), total_amount (>= 0, enforced by a CHECK constraint), version_id (optimistic-locking counter — SQLAlchemy bumps it on every ORM update and raises StaleDataError if somebody else got there first)
  • notifications — belongs to a user and optionally an order; channel (email/sms/push), message, sent_at. Doubles as a job queue: sent_at IS NULL is the ready-set, indexed by ix_notifications_pending

Deleting a user cascades to their orders and notifications (ondelete="CASCADE" in the DB, cascade="all, delete-orphan" on the ORM relationships).

Sessions, transactions, and savepoints

src/dblab/db.py exposes:

  • engine / SessionLocal — the default engine and session factory, built from DATABASE_URL.
  • session_scope() — a context manager that injects a Session, commits on a clean exit, and rolls back on an exception.

Use session.begin_nested() inside a session_scope() block (or around a manually-managed SessionLocal() instance) to open a SAVEPOINT: if that block raises, only the savepoint is rolled back and the outer transaction/session stays usable. See tests/test_basic.py and notebooks/demo.ipynb for worked examples of commit, rollback, and begin_nested/savepoints.

The concurrency lab

docs/concurrency/ is a ten-category tour of Postgres concurrency — flush/commit/rollback, savepoints, isolation levels, row locks, deadlocks, table locks and DDL, advisory locks, write patterns, timeouts and signals, and diagnostics. Each category has a mermaid diagram, the failure it produces with its SQLSTATE, guidance on when to reach for it, and a test module that proves every claim against the real server.

Start at docs/concurrency/README.md — it has the "which pattern do I need" decision tree and the who-waits-who-retries table.

Run it progressively:

uv run pytest -m beginner                    # one session: what the calls do
uv run pytest -m "beginner or intermediate"  # + isolation levels and row locks
uv run pytest tests/concurrency              # + deadlocks, DDL, signals, queues

src/dblab/concurrency.py is the toolkit the tests and the docs share:

  • SQLState / is_retryable() / run_with_retry() — name the failures concurrency actually produces (40001, 40P01, 55P03, 57014, 25P03) and retry the ones that deserve it.
  • lock_timeout() / statement_timeout() / idle_in_transaction_timeout() — bound a wait, via SET LOCAL so nothing leaks back into the pool.
  • advisory_lock() / advisory_key() — lock a concept when there is no row.
  • held_locks() / blocking_pids() / blocking_chain() / wait_until_blocked() — read pg_locks and pg_stat_activity so a blocked session is something you can observe, not guess at.

Running the scenarios by hand

A passing test hides the interesting part. notebooks/concurrency.ipynb drives the same scenarios interactively — you watch a session block, print the lock table, and see which side Postgres picks as the deadlock victim (re-run it; the victim changes).

devbox run notebook     # then open concurrency.ipynb

It runs against the real dblab_dev, tags every row it creates with the email prefix concurrency-lab-, and deletes exactly those in its first and last cells — nothing else in that database is touched. Each scenario cell re-seeds and opens its own sessions, so cells are independently re-runnable in any order.

The harness behind it is src/dblab/lab.py, importable from anywhere — a notebook, python -i, or a pdb session:

from dblab.lab import Cluster, make_lab_engine, seed_demo

engine = make_lab_engine()
seed = seed_demo(engine)
with Cluster(engine) as lab:
    alice, bob = lab.workers("alice", "bob")
    alice.execute("SELECT id FROM users WHERE id = :u FOR UPDATE", {"u": seed.user_id})
    pending = bob.start("SELECT id FROM users WHERE id = :u FOR UPDATE", {"u": seed.user_id})
    print(bob.wait_until_blocked())   # pid … waiting on Lock:transactionid blocked by […]
    print(lab.lock_report())          # the pg_locks table, one row marked WAITING
    alice.commit()
    pending.result(5)

worker.execute() waits for its statement; worker.start() returns a Future for one you expect to block — that is what lets a single cell hold two sessions in a standoff. lab.observer is a third, autocommit connection: a blocked session can't report on itself, so without it you can't see the block at all.

These tests can't use the db_session fixture (everything inside one transaction can't contend), so tests/concurrency/conftest.py just wraps dblab.lab in fixtures and adds a TRUNCATE teardown. See AGENTS.md for the rules that harness imposes.

notebooks/concurrency_advanced.ipynb covers the rest: savepoints and the lock-release asymmetry, isolation levels and write skew, the DDL outage, advisory locks and the pooling trap, and reading a three-deep lock pile-up.

The optimisation tracks

docs/tracks/ is the other half of the lab. Where docs/concurrency/ is organised by mechanism, a track is a chaptered path where each level makes the previous one measurably better — "measurably" usually means one number: round trips to the server (for MIGRATIONS it means lock duration and verified SQLSTATEs instead). Chapters are focused entry points: pick the one that matches your workload.

Track Chapters Levels Question Arc
1 · READS 4 9 What am I fetching that I don't need? 12 → 2 round trips
2 · WRITES 3 9 Why is this one row at a time? 20 → 2 round trips
3 · HYBRID 3 8 What happens between the read and the write? 3 → 2, and the race is gone
4 · SCHEMA 2 7 Which rules does the database enforce for you? duplicates → 23505
5 · MIGRATIONS 3 7 How do I change the schema without downtime? outage → fail-fast
devbox run notebook          # track_*.ipynb — one per track
uv run pytest tests/tracks   # every level's claim, asserted (+ pytest-alembic)

Each level declares an Expect that tests/tracks/ checks, so the path can't rot into folklore when SQLAlchemy changes how it batches. All levels are typed SQLAlchemy 2.0 — select(), insert(), update(), Mapped[] — so the types survive into the caller. MIGRATIONS levels run real alembic Operations against a scratch database seeded with fake data, and the repo's migration chain is validated up → down → up with pytest-alembic.

Watching the round trips

src/dblab/trace.py hooks SQLAlchemy's cursor events and renders every round trip as a span:

from dblab.trace import Tracer

with Tracer(engine) as trace:
    with trace.step("load users"):
        users = session.scalars(select(User).limit(10)).all()
    with trace.step("touch orders"):
        for user in users:
            len(user.orders)      # 10 more round trips, one per user
trace.show()                      # waterfall + per-verb summary
trace.round_trips                 # 11

It counts COMMIT too, which matters more than it sounds: commits don't go through cursor.execute, so without that hook a commit-per-row loop and a single-transaction loop both measure 10 round trips and the entire lesson disappears. BEGIN is deliberately not counted — psycopg starts the transaction implicitly with the first statement, so there's no separate trip.

Migrations

Alembic (migrations/) is wired to the same models (dblab.models.Base.metadata) and the same DATABASE_URL resolution as the app and tests (see migrations/env.py). To add a migration after changing a model:

DATABASE_URL="postgresql+psycopg://postgres@localhost:5432/dblab_dev" \
  uv run alembic revision --autogenerate -m "describe the change"
uv run alembic upgrade head

Postgres native ENUM columns (order_status, notification_channel) need their DROP TYPE added by hand to any autogenerated downgrade() — op.drop_table() alone leaves the type behind. See the initial migration for the pattern.

Tests

tests/conftest.py runs alembic upgrade head against dblab_test once per test session, then wraps each test in an outer transaction with join_transaction_mode="create_savepoint" so tests can freely call commit()/rollback()/begin_nested() while the database still resets between tests. The session fixture downgrades back to base at teardown.

Project layout

src/dblab/            models.py, db.py, concurrency.py, lab.py, trace.py
src/dblab/tracks/     the five track registries (reads..migrations)
migrations/           Alembic environment + versions
tests/                pytest suite (conftest.py sets up/tears down the schema)
tests/concurrency/    the concurrency lab — one module per category
tests/tracks/         asserts every level's round-trip claim
docs/concurrency/     10 categories: diagrams, when-to-use-what, failure modes
docs/tracks/          5 chaptered optimisation tracks (generated)
notebooks/            demo · concurrency · concurrency_advanced · track_{reads,writes,hybrid}
devbox.json           Postgres + uv, plus db:create/migrate/test/notebook/psql scripts

Deployed site (JupyterLite on GitHub Pages)

Every push to main builds a JupyterLite site (.github/workflows/deploy.yml) and publishes it at https://mohit-levers.github.io/concurrency-lab/ — notebooks and docs are readable in the browser, and Python cells run in-browser via Pyodide. One-time repo setup: Settings → Pages → Source: GitHub Actions.

Database modes (DBLAB_MODE)

Browsers cannot open TCP sockets, so psycopg cannot connect to Postgres from the Pages site — no env var changes that. Instead, under Pyodide the lab runs on a per-visitor SQLite sandbox: a dblab_browser.db on the kernel's own in-memory filesystem. Every visitor gets their own database — nothing shared, nothing to configure, no server to run — because the Pyodide filesystem is per-kernel. The dblab wheel is shipped into the site (wheels/ + PipliteAddon.piplite_urls in jupyter_lite_config.json), and the first cell of every notebook installs it into the kernel (piplite.install("dblab", deps=False) — psycopg/alembic have no wasm builds and are not needed there; SQLite comes from Pyodide's stdlib).

DBLAB_MODE where behaviour
direct (default outside Pyodide) your machine SQLAlchemy engine on DATABASE_URL (.env)
browser (auto under Pyodide) GitHub Pages per-visitor SQLite sandbox — schema auto-created, each site visitor isolated

What runs in the sandbox: the demo notebook and the READS / WRITES / HYBRID / SCHEMA tracks — those lessons are round trips and ORM behaviour, which are dialect-independent (an occasional cell that probes the Postgres catalog — EXPLAIN plans, pg_*, enable_seqscan — will error there). What still needs a local clone: the concurrency lab (Cluster refuses under browser mode with a clear error — row locks, pg_locks, pg_blocking_pids and isolation levels have no SQLite equivalent) and the MIGRATIONS track (DDL lock queues, CREATE INDEX CONCURRENTLY).

SQLite over DuckDB (which also ships for Pyodide): zero extra download — it's stdlib — and the surviving lessons don't care about the engine. Add DuckDB if analytic-SQL chapters ever appear.

Pointing a notebook at any database (fully dynamic)

The engine is built lazily from DATABASE_URL at the first query — and rebuilt if the value changes mid-notebook — so an optional first cell is all it takes:

import os
os.environ["DATABASE_URL"] = "postgresql+psycopg://user:pass@host:5432/db"
# os.environ["DBLAB_MODE"] = "direct"   # also re-read per notebook

Precedence is always: notebook/shell env > .env (dotenv never overrides an existing value) > built-in localhost default. No re-import needed; changing the URL disposes the old engine and reconnects on the next query.

Local preview of the site: uv build -o wheels && pip install -r requirements-lite.txt && jupyter lite serve (CI does the same wheel build with pip wheel --no-deps -w wheels .).

For AI coding agents

See AGENTS.md for conventions to follow when working in this repo.

About

Lab for concurrency patterns at enterprise grade

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages