Backend Development

Asynchronous Database Operations in Python: SQLAlchemy 2.0 with PostgreSQL

When building backend applications, database performance becomes increasingly important as the number of users and requests grows. A traditional database query…

D
DevByteTechnical Author
Published
23 min read4 views
Asynchronous Database Operations in Python: SQLAlchemy 2.0 with PostgreSQL

When building backend applications, database performance becomes increasingly important as the number of users and requests grows. A traditional database query might take only a few milliseconds, but when an application handles hundreds of requests simultaneously, waiting for database operations can become a significant bottleneck.

This is where asynchronous programming becomes useful.

Python supports asynchronous programming through async and await, allowing applications to perform I/O operations without blocking the execution of other tasks. When combined with PostgreSQL and SQLAlchemy 2.0, asynchronous database operations can help build responsive APIs that handle concurrent requests efficiently.

For example, imagine you're building a backend using FastAPI. Multiple users are requesting their profiles, viewing products, and placing orders simultaneously. While one request waits for PostgreSQL to return query results, the application can work on other requests instead of keeping that execution path blocked.

In this guide, we'll explore how asynchronous database operations work in Python, configure SQLAlchemy 2.0 with PostgreSQL, create database models, perform CRUD operations, manage transactions, and integrate everything with FastAPI.

We'll also discuss connection pooling, common mistakes, testing, and production best practices.

1. What Are Asynchronous Database Operations?

In a traditional synchronous application, database operations execute sequentially within the current execution flow.

Consider this example:

import time

def fetch_user():
    print("Fetching user...")
    time.sleep(3)
    return {"id": 1, "name": "Manjeet"}

user = fetch_user()
print(user)

The time.sleep(3) statement blocks the current thread for three seconds. During that time, the thread cannot continue executing other Python code.

A synchronous database query behaves similarly from the application's perspective: execution waits for the database operation to finish before continuing.

Now consider an asynchronous example:

import asyncio

async def fetch_user():
    print("Fetching user...")
    await asyncio.sleep(3)
    return {"id": 1, "name": "Manjeet"}

async def main():
    user = await fetch_user()
    print(user)

asyncio.run(main())

The important difference is await. When an asynchronous operation reaches an awaitable that cannot complete immediately, the event loop can run other eligible tasks while the operation is waiting.

A database query is a common example of I/O-bound work.

One important distinction: asynchronous programming does not automatically make an individual SQL query faster. Instead, it can improve concurrency and resource utilization when an application spends substantial time waiting for I/O.

Synchronous vs. Asynchronous Database Operations

Feature

Synchronous

Asynchronous

Query execution

Blocks the current execution path while waiting

Can yield control while waiting for I/O

Python API

Regular functions

async functions and await

Database driver

Synchronous driver

Async-compatible driver

Concurrent requests

May require more threads or workers

Can efficiently coordinate many I/O-bound tasks

Implementation

Generally simpler

Requires asynchronous session and connection management

Best use case

Simple applications and synchronous workloads

Async APIs and I/O-heavy applications

Asynchronous database operations are particularly useful for applications that already use an asynchronous framework, such as FastAPI.

However, synchronous database access remains a perfectly valid choice for many applications. The right approach depends on your workload, architecture, and operational requirements.

2. Understanding SQLAlchemy 2.0

SQLAlchemy is a popular Python SQL toolkit and Object Relational Mapper (ORM).

It provides two main ways to interact with a relational database:

  • Core: Build and execute SQL statements using SQLAlchemy's expression language.

  • ORM: Work with Python classes and objects that represent database tables and rows.

SQLAlchemy 2.0 provides an asynchronous API through components such as AsyncEngine, AsyncConnection, and AsyncSession.

These components allow you to execute database operations using Python's asynchronous programming model.

For PostgreSQL, we'll use the asyncpg driver.

Our application will use the following stack:

  • Python

  • SQLAlchemy 2.0

  • PostgreSQL

  • asyncpg

  • FastAPI

  • Pydantic

We'll start with database connectivity and then build a small user-management API.

3. Setting Up the Project

First, create a project directory:

mkdir async-postgres-app
cd async-postgres-app

Create a virtual environment:

python3 -m venv venv

Activate it on macOS or Linux:

source venv/bin/activate

On Windows:

venv\Scripts\activate

Now install the required dependencies:

pip install "SQLAlchemy>=2.0,<3.0" asyncpg fastapi uvicorn pydantic

We'll also install python-dotenv to load environment variables from a local .env file:

pip install python-dotenv

Our initial project structure will look like this:

async-postgres-app/
│
├── app/
│   ├── __init__.py
│   ├── database.py
│   ├── models.py
│   ├── schemas.py
│   └── main.py
│
├── .env
├── .gitignore
└── requirements.txt

Create the app directory and its Python files.

You can also save your installed dependencies:

pip freeze > requirements.txt

For a more controlled production dependency workflow, pin and lock the versions you have tested rather than relying on an unrestricted pip freeze from an arbitrary development environment.

4. Running PostgreSQL Locally

If PostgreSQL is already installed, you can use your existing database.

Alternatively, Docker provides a convenient way to start a local PostgreSQL instance.

Create a compose.yaml file in your project directory:

services:
  postgres:
    image: postgres:17
    container_name: async-postgres
    restart: unless-stopped

    environment:
      POSTGRES_DB: async_app
      POSTGRES_USER: app_user
      POSTGRES_PASSWORD: local_dev_password

    ports:
      - "127.0.0.1:5432:5432"

    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Start PostgreSQL:

docker compose up -d

Check whether the container is running:

docker compose ps

You can also check the PostgreSQL logs:

docker compose logs postgres

This configuration is intended for local development. Use a strong secret-management approach for production, and avoid committing database passwords to version control.

Configure Environment Variables

Create a .env file:

DATABASE_URL=postgresql+asyncpg://app_user:local_dev_password@127.0.0.1:5432/async_app

The connection string contains several important parts:

postgresql+asyncpg://
    app_user:
    local_dev_password@
    127.0.0.1:
    5432/
    async_app

Here's what each component means:

Component

Purpose

postgresql+asyncpg

Selects PostgreSQL with the asynchronous asyncpg driver

app_user

Database username

local_dev_password

Database password

127.0.0.1

Database host

5432

PostgreSQL's default port

async_app

Database name

The +asyncpg part is important. It tells SQLAlchemy to use an asynchronous PostgreSQL driver.

A URL such as postgresql://... may select a synchronous driver depending on the installed drivers and configuration. For this tutorial, explicitly specify postgresql+asyncpg://....

Add the following to .gitignore:

venv/
__pycache__/
.env
.pytest_cache/

Never commit your real database credentials to a public repository.

5. Creating an Asynchronous Database Engine

Now let's configure SQLAlchemy.

Create app/database.py:

import os

from dotenv import load_dotenv
from sqlalchemy.ext.asyncio import (
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)

load_dotenv()

DATABASE_URL = os.getenv("DATABASE_URL")

if not DATABASE_URL:
    raise RuntimeError("DATABASE_URL is not configured")

engine = create_async_engine(
    DATABASE_URL,
    echo=False,
    pool_size=10,
    max_overflow=20,
    pool_timeout=30,
    pool_pre_ping=True,
)

AsyncSessionLocal = async_sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
)

Let's understand the important parts.

create_async_engine()

engine = create_async_engine(
    DATABASE_URL,
    echo=False,
    pool_size=10,
    max_overflow=20,
)

The asynchronous engine manages database connectivity and the connection pool.

Instead of creating a new physical database connection for every request, SQLAlchemy can reuse connections from the pool.

The configuration above sets:

  • pool_size=10: Maintain up to ten persistent connections in the pool.

  • max_overflow=20: Permit up to twenty additional connections beyond the pool size when needed.

  • pool_timeout=30: Wait up to thirty seconds to obtain a connection before raising a timeout error.

  • pool_pre_ping=True: Check whether a pooled connection is usable before handing it out.

With this configuration, the pool can generally have up to thirty simultaneous connections per engine. This is not necessarily the right number for every application.

You should size the pool based on database capacity, application concurrency, the number of application processes, and the expected duration of database operations.

For example, four application processes with a pool capacity of thirty connections each could potentially create up to 120 connections, assuming every process uses this configuration.

That can overwhelm a PostgreSQL server if its connection budget is limited.

async_sessionmaker()

AsyncSessionLocal = async_sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
)

An AsyncSession represents a unit of work with the database. It tracks ORM objects and manages the transaction and connection resources associated with database operations.

The session factory creates new sessions when needed.

We use expire_on_commit=False so ORM attributes do not automatically expire after a successful commit. This makes it easier to access loaded attributes after committing without triggering implicit database refreshes.

It does not mean every attribute is loaded or that an expired or unloaded attribute can always be accessed without I/O.

Important rule: create a separate AsyncSession for each independent concurrent task. Do not share one session across multiple asyncio.gather() tasks.

6. Creating a Database Model

Now let's create a user table.

Create app/models.py:

from datetime import datetime

from sqlalchemy import DateTime, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Base(DeclarativeBase):
    pass


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(
        primary_key=True,
        index=True,
    )

    name: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
    )

    email: Mapped[str] = mapped_column(
        String(255),
        unique=True,
        index=True,
        nullable=False,
    )

    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        nullable=False,
    )

This model defines a PostgreSQL table named users.

Each user has:

  • An automatically generated primary key.

  • A required name.

  • A unique email address.

  • A timestamp generated by the database.

SQLAlchemy 2.0's Mapped and mapped_column() syntax provides type-aware model definitions.

For example:

email: Mapped[str] = mapped_column(
    String(255),
    unique=True,
    nullable=False,
)

This tells SQLAlchemy that email is a required string column with a uniqueness constraint.

The database constraint is important because checking whether an email already exists in application code is not enough to guarantee uniqueness. Two concurrent requests could both pass the check before either inserts its row.

The unique constraint provides the final guarantee at the database level.

7. Initializing the Database

For a small local example, we can create the table using SQLAlchemy's metadata.

Add the following function to app/database.py:

from app.models import Base

Then add:

async def create_tables():
    async with engine.begin() as connection:
        await connection.run_sync(Base.metadata.create_all)

The import should appear at the module level, after the existing imports.

The run_sync() method is used because Base.metadata.create_all() is a synchronous SQLAlchemy metadata operation that must run through the asynchronous connection's supported synchronous bridge.

Notice that we do not call this:

Base.metadata.create_all(engine)

That is not the appropriate way to initialize schema through an AsyncEngine.

For this tutorial, create_tables() is convenient. In a production application, use database migrations, typically with Alembic, to manage schema changes in a controlled and repeatable way.

We'll initialize the database through FastAPI's lifespan handler later.

8. Managing Asynchronous Database Sessions

One of the most important parts of asynchronous database programming is session lifecycle management.

A session should be created when a unit of work begins and closed when that work finishes.

Let's create a dependency that provides a session to each API request.

Add this function to app/database.py:

from collections.abc import AsyncGenerator


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        yield session

The async with statement ensures that the session is closed when the dependency finishes.

This is important because sessions may hold references to checked-out database connections and other resources.

We can now use this dependency in FastAPI routes:

from typing import Annotated

from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db

DbSession = Annotated[
    AsyncSession,
    Depends(get_db),
]

We'll use DbSession in our API examples.

Why Not Create a Global Session?

Avoid this pattern:

# Avoid this pattern.
session = AsyncSessionLocal()

A global session can accidentally be shared between requests, resulting in transaction interference, unsafe concurrent access, and difficult-to-debug failures.

The engine and session factory are normally application-level objects. Individual sessions should be created for individual units of work.

9. Performing SELECT Queries Asynchronously

Let's retrieve users from PostgreSQL.

SQLAlchemy 2.0 uses select() to build queries.

Create a function like this:

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models import User


async def get_users(session: AsyncSession):
    result = await session.execute(
        select(User).order_by(User.id)
    )

    return result.scalars().all()

Let's break down the query:

select(User)

This builds a statement that selects user records.

await session.execute(...)

This asynchronously executes the statement against the database.

result.scalars().all()

This extracts the ORM User objects from the result and returns all the rows.

You can retrieve a single user by ID:

async def get_user_by_id(
    session: AsyncSession,
    user_id: int,
):
    result = await session.execute(
        select(User).where(User.id == user_id)
    )

    return result.scalar_one_or_none()

The method scalar_one_or_none() returns the matching object or None. It raises an error if the query unexpectedly produces multiple rows.

For a query that may return many records, avoid loading the entire table into memory. Apply filters, limits, or pagination where appropriate.

For example:

async def get_recent_users(
    session: AsyncSession,
    limit: int = 20,
):
    result = await session.execute(
        select(User)
        .order_by(User.id.desc())
        .limit(limit)
    )

    return result.scalars().all()

In a real API, validate pagination parameters and choose an ordering that provides predictable results.

10. Inserting Data with AsyncSession

Now let's insert a new user.

async def create_user(
    session: AsyncSession,
    name: str,
    email: str,
):
    user = User(
        name=name,
        email=email,
    )

    session.add(user)

    await session.commit()
    await session.refresh(user)

    return user

There are three important operations here.

Step 1: Add the Object

session.add(user)

This adds the ORM object to the session. The insert may be deferred until a flush or commit occurs.

Step 2: Commit the Transaction

await session.commit()

This commits the current transaction. Pending changes are flushed before the transaction is committed.

Step 3: Refresh the Object

await session.refresh(user)

This reloads the object from the database, allowing database-generated values to be retrieved.

Because our session factory uses expire_on_commit=False, a refresh is not always required. However, it can be useful when you need to explicitly retrieve values generated or modified by the database.

A Better Approach for Transaction Safety

In larger applications, consider using transaction context managers to make the boundaries of a unit of work clearer.

For example:

async def create_user(
    session: AsyncSession,
    name: str,
    email: str,
):
    async with session.begin():
        user = User(
            name=name,
            email=email,
        )

        session.add(user)
        await session.flush()

        await session.refresh(user)

    return user

The session.begin() context manager commits the transaction if the block completes successfully and rolls it back if an exception occurs.

flush() sends pending changes to the database without committing the transaction.

This allows the database to generate the new ID before the transaction is committed.

Do not combine this pattern with an unrelated transaction that is already active on the same session. Establish clear transaction ownership so you know which layer is responsible for committing or rolling back.

11. Updating and Deleting Records

Updating and deleting records follows the same asynchronous pattern.

Updating a User

async def update_user(
    session: AsyncSession,
    user_id: int,
    name: str,
):
    user = await session.get(User, user_id)

    if user is None:
        return None

    user.name = name

    await session.commit()
    await session.refresh(user)

    return user

The session.get() method retrieves an object by its primary key.

When an ORM-managed object's attributes change, SQLAlchemy tracks those changes. The update is sent to the database during a flush, which normally occurs before the commit.

Deleting a User

async def delete_user(
    session: AsyncSession,
    user_id: int,
):
    user = await session.get(User, user_id)

    if user is None:
        return False

    await session.delete(user)
    await session.commit()

    return True

Notice that await is required for session.delete() with AsyncSession.

This differs from the traditional synchronous ORM session API.

The session's delete operation marks the object for deletion, and the actual SQL statement is issued when the session flushes the pending changes.

For production code, make sure your API handles missing records, database errors, and transaction rollback consistently.

12. Integrating SQLAlchemy 2.0 with FastAPI

Now let's bring everything together into a working API.

We'll use Pydantic schemas to validate incoming data and control the response format.

Create app/schemas.py:

from datetime import datetime

from pydantic import BaseModel, ConfigDict, EmailStr


class UserCreate(BaseModel):
    name: str
    email: EmailStr


class UserUpdate(BaseModel):
    name: str


class UserResponse(BaseModel):
    id: int
    name: str
    email: EmailStr
    created_at: datetime

    model_config = ConfigDict(from_attributes=True)

Because we're using EmailStr, install the optional email-validation dependency:

pip install email-validator

from_attributes=True allows Pydantic to construct a response from an ORM object's attributes.

Now create app/main.py:

from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, status
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import (
    engine,
    get_db,
    create_tables,
)
from app.models import User
from app.schemas import UserCreate, UserResponse, UserUpdate


@asynccontextmanager
async def lifespan(app: FastAPI):
    await create_tables()

    try:
        yield
    finally:
        await engine.dispose()


app = FastAPI(lifespan=lifespan)

DbSession = Annotated[
    AsyncSession,
    Depends(get_db),
]


@app.post(
    "/users",
    response_model=UserResponse,
    status_code=status.HTTP_201_CREATED,
)
async def create_user(
    payload: UserCreate,
    session: DbSession,
):
    user = User(
        name=payload.name,
        email=str(payload.email),
    )

    try:
        async with session.begin():
            session.add(user)
            await session.flush()
            await session.refresh(user)

    except IntegrityError as exc:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="A user with this email may already exist.",
        ) from exc

    return user


@app.get(
    "/users",
    response_model=list[UserResponse],
)
async def list_users(
    session: DbSession,
):
    result = await session.execute(
        select(User).order_by(User.id)
    )

    return result.scalars().all()


@app.get(
    "/users/{user_id}",
    response_model=UserResponse,
)
async def get_user(
    user_id: int,
    session: DbSession,
):
    user = await session.get(User, user_id)

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found",
        )

    return user


@app.patch(
    "/users/{user_id}",
    response_model=UserResponse,
)
async def update_user(
    user_id: int,
    payload: UserUpdate,
    session: DbSession,
):
    user = await session.get(User, user_id)

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found",
        )

    user.name = payload.name

    await session.commit()
    await session.refresh(user)

    return user


@app.delete("/users/{user_id}")
async def delete_user(
    user_id: int,
    session: DbSession,
):
    user = await session.get(User, user_id)

    if user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found",
        )

    await session.delete(user)
    await session.commit()

    return {"message": "User deleted successfully"}

Understanding the Lifespan Handler

The lifespan handler manages application startup and shutdown.

@asynccontextmanager
async def lifespan(app: FastAPI):
    await create_tables()

    try:
        yield
    finally:
        await engine.dispose()

At startup, the application initializes the tables for this tutorial.

At shutdown, it disposes of the engine's connection pool.

For a production deployment, run migrations as a separate deployment step instead of calling create_all() during every application's startup. If multiple workers start simultaneously, coordinating schema changes through migrations is safer.

Also, the example catches IntegrityError during user creation and returns HTTP 409. In a production system, inspect database constraint information where appropriate so that only the expected duplicate-email violation is translated into this response. Other integrity errors may indicate a different problem.

Start the Application

Run:

uvicorn app.main:app --reload

Open FastAPI's interactive API documentation at:

http://127.0.0.1:8000/docs

You can now test the endpoints directly from the browser.

For example, create a user with this request body:

{
  "name": "Manjeet",
  "email": "manjeet@example.com"
}

The API should return the created user with its generated ID and timestamp.

The actual ID and timestamp will depend on the database.

13. Handling Transactions and Database Errors

Transactions are essential when an operation involves multiple related database changes.

Imagine you're developing an e-commerce application. When a customer places an order, the backend might need to:

  1. Create an order record.

  2. Insert order items.

  3. Reduce inventory.

  4. Record payment-related information.

If an operation fails halfway through, leaving some changes committed and others missing can corrupt the application's business state.

Use a single transaction for changes that must succeed or fail together.

For example:

async def create_order(
    session: AsyncSession,
    order_data: dict,
):
    async with session.begin():
        order = Order(
            customer_id=order_data["customer_id"],
        )

        session.add(order)
        await session.flush()

        for item_data in order_data["items"]:
            item = OrderItem(
                order_id=order.id,
                product_id=item_data["product_id"],
                quantity=item_data["quantity"],
            )

            session.add(item)

    return order

Here, Order and OrderItem represent hypothetical ORM models that must be defined separately.

The example illustrates transaction management rather than a complete order-processing implementation.

If an exception occurs inside the transaction block, SQLAlchemy rolls back the transaction. Otherwise, it commits when the block completes successfully.

For inventory and payments, you must also consider concurrency control, database constraints, idempotency, and integration with external payment providers. A database transaction alone cannot make an external payment operation atomic with a PostgreSQL transaction.

Handling Database Exceptions

SQLAlchemy provides exceptions such as:

  • IntegrityError: A database integrity constraint was violated.

  • OperationalError: An operational database error occurred.

  • DBAPIError: A general database-driver-related exception.

  • TimeoutError: A SQLAlchemy connection-pool timeout occurred.

Handle known errors at the appropriate application boundary.

For example:

from sqlalchemy.exc import SQLAlchemyError


async def perform_database_operation(
    session: AsyncSession,
):
    try:
        result = await session.execute(
            select(User)
        )

        return result.scalars().all()

    except SQLAlchemyError:
        # Log the exception through your application's logger.
        raise

This example demonstrates where to handle SQLAlchemy exceptions, but simply re-raising them does not provide a useful HTTP response by itself.

In a real application, use structured logging, map known errors to appropriate responses, and avoid returning internal database details to clients.

If a flush or commit fails, the session's transaction may need to be rolled back before it can be reused. Transaction context managers help manage that lifecycle.

14. Running Concurrent Database Queries

One of the main benefits of asynchronous database access is the ability to coordinate independent I/O-bound operations.

Suppose an API needs to fetch a list of users and count the total number of users. These queries can run concurrently when they are independent.

However, each concurrent operation should use its own session.

import asyncio

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import AsyncSessionLocal
from app.models import User


async def fetch_users():
    async with AsyncSessionLocal() as session:
        result = await session.execute(
            select(User).order_by(User.id).limit(20)
        )

        return result.scalars().all()


async def count_users():
    async with AsyncSessionLocal() as session:
        result = await session.execute(
            select(func.count()).select_from(User)
        )

        return result.scalar_one()


async def get_dashboard_data():
    users, total_users = await asyncio.gather(
        fetch_users(),
        count_users(),
    )

    return {
        "users": users,
        "total_users": total_users,
    }

The two queries are independent, so asyncio.gather() can coordinate their execution.

While one query waits for PostgreSQL, the event loop may make progress on the other query.

There are two important considerations.

First, concurrency does not guarantee a performance improvement. The result depends on query duration, database capacity, network latency, connection-pool availability, and the number of concurrent operations.

Second, the queries may observe different database states. Because they execute in separate sessions and transactions, a concurrent insert or delete could occur between them. If a consistent snapshot is required, consider an appropriate transaction design and PostgreSQL isolation level.

For some applications, a single SQL query that returns both the requested rows and a count may be more efficient. Measure your actual workload before deciding.

15. Connection Pooling and Performance Optimization

Connection pooling is a key part of database performance.

Opening a new database connection for every request adds overhead. A connection pool allows the application to reuse established connections.

SQLAlchemy's asynchronous engine provides connection pooling for supported configurations.

Consider the following configuration:

engine = create_async_engine(
    DATABASE_URL,
    pool_size=10,
    max_overflow=20,
    pool_timeout=30,
    pool_recycle=1800,
    pool_pre_ping=True,
)

Each option serves a different purpose.

Setting

What it does

pool_size

Sets the number of persistent pooled connections

max_overflow

Allows temporary connections beyond the configured pool size

pool_timeout

Controls how long the application waits for a connection

pool_recycle

Recycles connections older than the configured age when they are checked out

pool_pre_ping

Checks connection usability before checkout

pool_recycle is useful in environments where connections can become stale after a period of time. It does not automatically solve every network or database connection problem.

Avoid Long-Running Transactions

A transaction that remains open while the application performs unrelated work can hold a database connection unnecessarily.

For example, avoid making a slow external HTTP request while holding a database transaction open unless the workflow genuinely requires that design.

A better approach is to keep database transactions as short as practical and separate unrelated network operations from database work.

Select Only the Data You Need

If an API only needs a user's ID and name, retrieving every column may be unnecessary.

You can select individual columns:

result = await session.execute(
    select(User.id, User.name)
)

users = result.all()

This returns rows containing the selected columns rather than complete ORM entities.

Selecting fewer columns can reduce data transfer and memory usage, especially for large tables.

Use Pagination

Avoid returning thousands of records in one response.

For example:

result = await session.execute(
    select(User)
    .order_by(User.id)
    .limit(50)
    .offset(0)
)

users = result.scalars().all()

For larger tables or deep pagination, keyset pagination based on a stable indexed column may perform better than large offsets.

Add Indexes Where They Help

Indexes can improve query performance for common lookup and filtering operations.

Our model includes an index on email, which is useful for lookups by email address.

However, indexes also add storage overhead and can slow down writes. Add them based on actual query patterns and execution plans rather than indexing every column automatically.

16. Common Mistakes When Using Async SQLAlchemy

Even when the code appears correct, certain mistakes can reduce performance or create unexpected failures.

Mistake 1: Using a Synchronous Driver with an Async Engine

This configuration is appropriate for our tutorial:

DATABASE_URL = (
    "postgresql+asyncpg://"
    "app_user:password@localhost:5432/async_app"
)

Using an incompatible synchronous driver with create_async_engine() will not provide the expected asynchronous database integration.

Choose a supported asynchronous dialect and driver.

Mistake 2: Forgetting await

Incorrect:

result = session.execute(select(User))

Correct:

result = await session.execute(
    select(User)
)

Asynchronous session operations must be awaited when their API returns awaitables.

Forgetting await may leave you with a coroutine rather than the actual query result.

Mistake 3: Sharing One Session Across Concurrent Tasks

Avoid:

async with AsyncSessionLocal() as session:
    await asyncio.gather(
        operation_one(session),
        operation_two(session),
    )

Both tasks would use the same session concurrently, which SQLAlchemy does not support.

Create a separate session for each independent task.

Mistake 4: Blocking the Event Loop

Avoid calling blocking operations such as time.sleep() or making synchronous network requests directly inside an asynchronous request handler.

Use asynchronous alternatives when available.

For example:

import asyncio

await asyncio.sleep(1)

This allows the event loop to schedule other tasks during the wait.

Mistake 5: Treating Async as a Replacement for Good SQL

An asynchronous database call does not fix an inefficient query.

If PostgreSQL performs a sequential scan over millions of rows when a suitable index could help, switching to async and await will not automatically fix that database bottleneck.

Use EXPLAIN ANALYZE, inspect query plans, and measure performance.

Mistake 6: Leaving Sessions or Connections Open

Always manage session and connection lifecycles.

For example:

async with AsyncSessionLocal() as session:
    result = await session.execute(
        select(User)
    )

    users = result.scalars().all()

The context manager closes the session when the block finishes.

At application shutdown, dispose of the engine when its lifecycle is owned by that application instance.

17. Testing Asynchronous Database Code

Testing database operations helps catch errors involving transactions, constraints, and session management.

For simple repository tests, you can use pytest and pytest-asyncio.

Install them:

pip install pytest pytest-asyncio

A basic test for fetching users could look like this:

import pytest
from sqlalchemy.ext.asyncio import AsyncSession

from app.models import User


@pytest.mark.asyncio
async def test_create_user(session: AsyncSession):
    user = User(
        name="Test User",
        email="test@example.com",
    )

    session.add(user)
    await session.flush()

    assert user.id is not None
    assert user.name == "Test User"

This example assumes that your test configuration provides a valid session fixture connected to a test database.

The fixture should create the required schema and isolate test data so that tests do not affect your development or production database.

Depending on the SQLAlchemy and pytest-asyncio versions, you may need to configure the test event-loop and fixture scopes appropriately.

For reliable integration tests, use PostgreSQL rather than assuming that SQLite will reproduce all PostgreSQL behavior. Differences in types, constraints, SQL syntax, concurrency, and transaction behavior can affect test results.

You should also test cases such as:

  • Creating a user with a duplicate email.

  • Retrieving a nonexistent user.

  • Rolling back a failed transaction.

  • Handling database connection failures.

  • Verifying that sessions are closed correctly.

  • Confirming that concurrent requests do not share sessions.

18. When Should You Use Async SQLAlchemy?

Asynchronous database operations are useful when the application benefits from coordinating many I/O-bound operations.

Consider async SQLAlchemy when:

  • You are building an API with FastAPI or another asynchronous framework.

  • Your application handles many concurrent database requests.

  • Requests perform several independent I/O operations.

  • You need to coordinate database queries with asynchronous HTTP clients or other network services.

  • You want to use PostgreSQL through an asynchronous Python driver.

A synchronous approach may be preferable when:

  • Your application has relatively low concurrency.

  • Your existing architecture is entirely synchronous.

  • Most of your workload is CPU-bound.

  • The additional complexity of async programming does not provide measurable benefits.

Remember that asynchronous database access does not make CPU-intensive Python operations run in parallel. CPU-heavy tasks may require multiprocessing, worker queues, or other execution strategies.

Also, PostgreSQL still has finite connection and query-processing capacity. An asynchronous application can issue many concurrent operations, but that does not mean the database can efficiently execute an unlimited number of queries.

The goal is not to make everything asynchronous. The goal is to use asynchronous operations where they provide a meaningful benefit.

19. Production Best Practices

Before deploying an asynchronous SQLAlchemy application, review these practical recommendations.

Use environment variables for secrets. Keep database credentials outside your source code and use an appropriate secret-management system in production.

Use Alembic for schema migrations. Manage database schema changes explicitly rather than relying on create_all() during application startup.

Set realistic connection-pool limits. Account for all application workers and replicas, and keep the total within PostgreSQL's connection budget.

Keep transactions short. Avoid holding connections and transactions while performing unrelated or slow operations.

Handle integrity errors properly. Database constraints remain essential for data correctness, especially when concurrent requests are involved.

Use a separate session for each concurrent task. An AsyncSession is mutable state and must not be shared by concurrent tasks.

Monitor slow queries. Use PostgreSQL query plans and database monitoring tools to find bottlenecks before optimizing application code.

Implement timeouts and cancellation carefully. An application timeout does not necessarily mean that every operation has been cancelled cleanly at the database level. Understand the behavior of your driver, transaction handling, and infrastructure.

Test under realistic concurrency. Measure connection usage, latency, error rates, and throughput using a workload representative of your actual application.

Avoid unnecessary concurrency. Running too many database queries simultaneously can increase connection-pool contention and put additional pressure on PostgreSQL.

Conclusion

Asynchronous database operations are a valuable tool for building scalable Python backend applications.

With SQLAlchemy 2.0, PostgreSQL, and the asyncpg driver, you can execute database queries using async and await, manage transactions through AsyncSession, and integrate database access into a FastAPI application.

In this tutorial, we covered:

  • The difference between synchronous and asynchronous database access.

  • Installing and configuring SQLAlchemy 2.0 with PostgreSQL.

  • Creating an asynchronous engine and session factory.

  • Defining ORM models and managing database sessions.

  • Performing asynchronous CRUD operations.

  • Integrating SQLAlchemy with FastAPI.

  • Handling transactions and database errors.

  • Running independent queries concurrently.

  • Optimizing connection pools and query performance.

  • Testing asynchronous database code and preparing for production.

The most important takeaway is that asynchronous programming improves how an application manages I/O waiting, but good database design, efficient SQL queries, correct transaction boundaries, and proper connection management remain essential.

If you're already working with FastAPI or building AI-powered Python applications, learning asynchronous SQLAlchemy will help you develop backend services that coordinate database access and other I/O operations more effectively.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘