Data access and security · mid
SQLAlchemy sessions, connection pools and async use
A Session is a unit of work with an identity map. The engine owns a connection pool per process, so the total connections across pods and workers must fit the database limit. In async code lazy loading fails, so load what you need on purpose.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- The Session tracks new, changed and deleted objects and writes them in one flush, in the right order. The identity map gives one Python object per primary key per session.
- Autoflush sends pending changes before a query and at commit. flush() sends SQL but does not commit. expire_on_commit=True (default) marks objects stale after commit; use False in async code to avoid hidden I/O.
- One session per request (a FastAPI yield dependency or Flask-SQLAlchemy's scoped session). The engine and pool are shared by the app. A session is not thread-safe. 2.0 style: select(User).where(...), session.scalars(...), typed Mapped[...] models.
- Default QueuePool: pool_size=5, max_overflow=10, pool_timeout=30, so up to 15 per process. 6 pods x 4 workers x 15 = 360, over a PostgreSQL limit of 200. Budget: processes x (pool_size + max_overflow) below max_connections minus a reserve.
- A pool larger than what PostgreSQL can run at once only adds waiting. pool_pre_ping=True checks a connection before use; pool_recycle replaces old connections for proxies that drop idle ones. Autoscaling multiplies connections: cap it.
- PgBouncer in transaction mode shares few server connections among many app connections, but breaks session features (session SET, advisory locks across transactions, LISTEN). asyncpg prepared statements need care behind it. With PgBouncer, use NullPool or a very small pool.
- Django: CONN_MAX_AGE keeps one connection per thread; the PostgreSQL pool option in OPTIONS (Django 5.1 and later) needs CONN_MAX_AGE = 0.
- MissingGreenlet in async: lazy loading runs SQL on attribute access, which cannot be awaited. Fix with eager loading (selectinload), await obj.awaitable_attrs.items (AsyncAttrs), or lazy="raise" in tests. An AsyncSession is not safe for concurrent tasks: do not gather on one session. Install sqlalchemy[asyncio].
The red pen
Common traps: mistake → fix
Mistake: A pool per process is a small thing
Fix: pods x workers x pool size can exceed the database limit.
Mistake: A bigger pool makes the database faster
Fix: it only queues work inside the database.
Mistake: gather on one AsyncSession runs queries in parallel
Fix: it fails; use one session per task.
Mistake: Async makes one query faster
Fix: it helps many waiting requests, not one query.
Easy to hard
Questions interviewers ask, easy to hard
- How does a SQLAlchemy Session work? What is the identity map?
- When does it flush?
- We have 6 pods with 4 workers each and a limit of 200 connections. How do you size the pools?
- When do you add PgBouncer, and what breaks?
- Why does an async endpoint raise MissingGreenlet?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.