USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll BooksBackend Book
HomeBackend BookData and State
PreviousRelational Modeling, Constraints, and IndexesNextAlembic Migrations Without Downtime Surprises
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

12 sections

Progress0%
1 / 12

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

SQLAlchemy, Repositories, and Units of Work

SQLAlchemy maps Python operations to SQL and manages a session identity map; it does not remove the need to understand transactions or queries. Repositories express application-specific persistence, while a unit of work owns one transaction. Routes should not scatter commits, and domain code should not depend on ORM sessions.

What will you be able to do?

  • configure an async SQLAlchemy engine and bounded pool;
  • map a ticket table and execute explicit statements;
  • own commit and rollback in one unit of work;
  • detect N+1 queries and accidental lazy I/O.

How do you configure the persistence adapter?

Install the driver and ORM:

bash
uv add sqlalchemy alembic 'psycopg[binary]'

Create src/supportdesk_ai/adapters/db.py:

python
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine engine = create_async_engine( settings.database_url, pool_size=5, max_overflow=5, pool_pre_ping=True, ) session_factory = async_sessionmaker(engine, expire_on_commit=False)

Pool sizes across every worker must remain below database connection capacity with headroom for migrations and operations.

An application-specific repository uses explicit tenant scope:

python
from sqlalchemy import select class SqlTicketRepository: def __init__(self, session: AsyncSession) -> None: self.session = session async def get(self, organization_id: UUID, ticket_id: UUID) -> TicketRow | None: statement = select(TicketRow).where( TicketRow.organization_id == organization_id, TicketRow.id == ticket_id, ) return await self.session.scalar(statement)

The application service decides when the use case succeeds; the unit of work commits once. On exception it rolls back. Repository methods do not commit independently, because multiple related changes may need atomicity.

How do you avoid ORM surprises?

  • Load required relationships explicitly.
  • Count emitted queries in tests for critical endpoints.
  • Select only fields needed for large lists.
  • Never serialize an ORM row as the public API by accident.
  • Set statement timeouts and slow-query monitoring at appropriate layers.

Why does this matter in AI-native systems?

An AI action may create an ai_run, enqueue an outbox event, and update ticket state atomically. The model call itself should normally occur outside a long database transaction; record intent, perform external work, then persist the outcome idempotently.

Common mistakes

  • One global session shared across concurrent requests.
  • Committing inside repository methods.
  • Lazy-loading while serializing creates N+1 queries or async errors.
  • Catching an integrity error without rolling back leaves the session unusable.
  • Pool capacity multiplied by workers overwhelms PostgreSQL.

AI Pair-Programmer Prompt

text
Review this SQLAlchemy 2.x data path. Trace session and transaction ownership, tenant predicates, emitted SQL, relationship loading, commit/rollback, integrity errors, pool math across workers, and domain/ORM separation. Propose tests that count queries and prove rollback.

Exercise

Implement create-and-comment as one transaction. Force the comment insert to fail and prove the ticket is not committed. Count SQL statements for listing 25 tickets with authors.

Acceptance criteria: rollback is atomic, tenant scope is in every query, and the list query count does not grow with result size.

Knowledge check

  1. Who should own the transaction?
  2. Why avoid a model call inside an open database transaction?
  3. What is the N+1 problem?

Answers

  1. The use case's unit of work.
  2. Remote latency holds locks/connections and failure semantics do not align with the database.
  3. Loading one collection triggers one initial query plus another query for each item.

Completion checklist

  • Session scope is per unit of work.
  • Repositories never hide commits.
  • Critical query counts are tested.

Primary references

  • SQLAlchemy unified tutorial
  • SQLAlchemy asyncio