
Imagine you're building an e-commerce application with FastAPI and PostgreSQL. A customer places an order, the application creates an order record, and the system reduces the available stock for each product.
Everything looks simple until something goes wrong.
The order gets created successfully, but updating the product inventory fails. Now your database says the customer has placed an order, but the inventory hasn't been updated. Another customer might purchase the same product using the remaining stock, even though the first order should have reserved it.
This is the kind of problem database transactions are designed to prevent.
When building APIs, it's easy to focus on endpoints, request validation, authentication, and response formats. But once an application starts handling payments, inventory, subscriptions, bookings, or financial records, database consistency becomes just as important as the API itself.
In this article, we'll explore how database transactions work in FastAPI, how to handle rollbacks, how concurrent requests can cause unexpected results, and how to protect data integrity using SQLAlchemy and PostgreSQL.
We'll also look at practical techniques you can use when building production APIs.
What Is a Database Transaction?
A database transaction is a group of database operations that should be treated as one logical unit.
Consider an application that transfers money between two accounts.
Suppose a customer wants to transfer ₹1,000 from Account A to Account B.
The application needs to perform two operations:
Subtract ₹1,000 from Account A.
Add ₹1,000 to Account B.
Both operations must succeed together.
If the application subtracts the money from Account A but fails before adding it to Account B, the database becomes inconsistent.
A transaction allows the application to commit both changes together or roll them back if something fails.
Conceptually, the process looks like this:
BEGIN TRANSACTION
|
v
Subtract ₹1,000 from Account A
|
v
Add ₹1,000 to Account B
|
v
Did every operation succeed?
|
+---+---+
| |
Yes No
| |
v v
COMMIT ROLLBACK
| |
v v
Changes Undo the
saved transactionIn PostgreSQL, a transaction typically starts when the application executes its first statement within a transaction or explicitly begins one. It ends with either COMMIT or ROLLBACK.
With SQLAlchemy, you can manage these operations through a database session.
For example:
from sqlalchemy.orm import Session
def transfer_money(
db: Session,
sender_id: int,
receiver_id: int,
amount: int,
):
try:
# Fetch accounts and validate balances here.
# Perform both balance updates here.
db.commit()
except Exception:
db.rollback()
raiseThis example demonstrates the basic structure, but a real money-transfer operation also needs balance validation, concurrency control, and database constraints.
Let's build up those concepts step by step.
1. Setting Up FastAPI with PostgreSQL and SQLAlchemy
Before discussing transactions in detail, let's establish a basic database setup.
We'll use:
FastAPI for the API layer.
PostgreSQL for persistent storage.
SQLAlchemy 2.x for database operations.
Psycopg for connecting Python to PostgreSQL.
Pydantic for request validation.
Install the required packages:
pip install fastapi "uvicorn[standard]" sqlalchemy "psycopg[binary]" pydantic-settingsCreate a .env file:
DATABASE_URL=postgresql+psycopg://postgres:password@localhost:5432/shop_dbReplace the credentials with your local PostgreSQL configuration. Don't commit real credentials to Git.
Now create database.py:
from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
class Settings(BaseSettings):
database_url: str
model_config = SettingsConfigDict(
env_file=".env",
extra="ignore",
)
settings = Settings()
engine = create_engine(
settings.database_url,
pool_pre_ping=True,
)
SessionLocal = sessionmaker(
bind=engine,
autoflush=False,
expire_on_commit=False,
)
class Base(DeclarativeBase):
pass
def get_db():
with SessionLocal() as db:
yield dbHere, create_engine() configures the database connection pool, while SessionLocal creates SQLAlchemy sessions.
The get_db() function provides a session to FastAPI endpoints.
Notice that this dependency doesn't automatically commit transactions. That's intentional. We'll make transaction boundaries explicit so it's clear which operations belong together.
For a production application, use database migrations, configure connection pooling according to your workload, and manage credentials through a secure configuration system.
2. Understanding ACID Properties
Database transactions are commonly described using four properties known as ACID.
Understanding them helps explain why transactions matter beyond simply calling commit().
Atomicity
Atomicity means a transaction succeeds as a whole or its changes are rolled back.
For example, creating an order and reducing inventory should happen together when both operations belong to the same database transaction.
If inventory validation fails, the order shouldn't be committed as though everything succeeded.
Consistency
Consistency means a transaction must preserve the rules enforced by your database and application.
For example, a product's stock shouldn't become negative if your business rules prohibit negative inventory.
You can enforce this rule with a database constraint:
ALTER TABLE products
ADD CONSTRAINT products_stock_nonnegative
CHECK (stock >= 0);This constraint protects the database even if a developer accidentally writes incorrect application code.
Isolation
Isolation controls how concurrent transactions interact with one another.
Suppose two customers attempt to purchase the final unit of a product simultaneously.
Without suitable concurrency control, both requests might read the same stock value and attempt to purchase that unit.
Isolation levels, row locks, conditional updates, and constraints help prevent such problems.
Durability
Durability means that once a transaction has been committed successfully, its changes are expected to survive failures according to the database's durability guarantees and configuration.
PostgreSQL provides transactional durability, although the precise guarantees also depend on settings such as WAL configuration and synchronous replication.
For most application developers, the practical takeaway is straightforward: validate your data, group related writes into transactions, and let the database enforce critical invariants.
3. Managing Transactions in FastAPI
One common source of confusion is deciding where a transaction should begin and end.
Should you commit inside the database dependency? Should every repository function commit independently? Or should the API endpoint manage everything?
There isn't one correct design for every application, but the transaction boundary should be easy to identify.
For a simple API, a useful approach is to let the endpoint or service layer own the transaction.
The database dependency creates and closes the session, while the service performs the business operation and commits the changes.
For example:
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from database import get_db
app = FastAPI()
@app.post("/users")
def create_user(
db: Session = Depends(get_db),
):
try:
# Add the user and perform any related writes.
db.commit()
return {"message": "User created successfully"}
except Exception:
db.rollback()
raise HTTPException(
status_code=500,
detail="Unable to create user",
)This shows the basic pattern, but production code should validate the request, handle expected database errors separately, and avoid returning generic success messages before all required operations have completed.
Also, don't expose raw database exceptions to clients. Log appropriate diagnostic details on the server and return a safe error response.
A Cleaner Approach with session.begin()
SQLAlchemy provides a transaction context manager that handles commit and rollback automatically.
Consider this example:
def create_user(db: Session, email: str):
with db.begin():
# Add the user.
# Add related records.
# Perform other required database operations.
passIf the block finishes successfully, SQLAlchemy commits the transaction.
If an exception occurs, SQLAlchemy rolls it back and propagates the exception.
This is often easier to maintain than manually repeating try, commit(), and rollback() throughout your application.
However, there's an important detail: db.begin() cannot start a new outer transaction if the session already has an active transaction.
SQLAlchemy sessions may begin transactions automatically when database operations are performed.
For that reason, decide which layer owns the transaction and avoid mixing incompatible transaction-management patterns.
For example, if a service function receives a session that already has an active transaction, it shouldn't blindly call db.begin() again.
One practical design is to let the service layer own the transaction:
def create_order_service(
db: Session,
customer_id: int,
):
with db.begin():
# Validate the customer.
# Create the order.
# Update inventory.
# Create order items.
passThe route passes the session to the service, but doesn't independently commit the same operation.
This separation becomes especially useful when your application contains several related database writes.
4. Handling Rollbacks When Something Fails
Let's consider a real-world example.
A customer places an order. The application must:
Create the order.
Add order items.
Reduce product inventory.
Save the final order status.
If any required database operation fails, none of those changes should be committed.
Here's a simplified model setup.
Create models.py:
from sqlalchemy import (
CheckConstraint,
ForeignKey,
Integer,
String,
)
from sqlalchemy.orm import Mapped, mapped_column
from database import Base
class Product(Base):
__tablename__ = "products"
__table_args__ = (
CheckConstraint(
"stock >= 0",
name="products_stock_nonnegative",
),
)
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(
String(200),
nullable=False,
)
stock: Mapped[int] = mapped_column(
Integer,
nullable=False,
)
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(
Integer,
nullable=False,
)
status: Mapped[str] = mapped_column(
String(30),
default="pending",
nullable=False,
)
class OrderItem(Base):
__tablename__ = "order_items"
id: Mapped[int] = mapped_column(primary_key=True)
order_id: Mapped[int] = mapped_column(
ForeignKey("orders.id"),
nullable=False,
)
product_id: Mapped[int] = mapped_column(
ForeignKey("products.id"),
nullable=False,
)
quantity: Mapped[int] = mapped_column(
Integer,
nullable=False,
)In a complete application, you'll also want positive-quantity constraints, appropriate indexes, customer foreign keys, and any required price or currency fields.
Now consider a service that creates an order.
from sqlalchemy.orm import Session
from models import Order, OrderItem, Product
def create_order(
db: Session,
customer_id: int,
product_id: int,
quantity: int,
):
if quantity <= 0:
raise ValueError("Quantity must be greater than zero")
with db.begin():
product = db.get(Product, product_id)
if not product:
raise ValueError("Product not found")
if product.stock < quantity:
raise ValueError("Insufficient stock")
order = Order(
customer_id=customer_id,
status="confirmed",
)
db.add(order)
db.flush()
order_item = OrderItem(
order_id=order.id,
product_id=product.id,
quantity=quantity,
)
db.add(order_item)
product.stock -= quantity
return {
"order_id": order.id,
"status": order.status,
}The important line here is:
db.flush()A flush sends pending SQL statements to the database without committing the transaction.
In this example, it allows PostgreSQL to generate the order ID before we create the related order item.
If the order item insertion or inventory update fails, the transaction context manager rolls back the database changes.
The order and its item therefore won't be partially committed.
Why flush() Is Different from commit()
These methods serve different purposes.
flush() sends pending changes to the database within the current transaction.
commit() makes the transaction's changes permanent.
For example:
db.add(order)
db.flush()
print(order.id)
db.commit()After flush(), the order may have an assigned database-generated ID, but the transaction hasn't been committed yet.
Other transactions generally won't see the uncommitted row, and a rollback can still undo the insertion.
This distinction becomes important when working with foreign keys, generated IDs, and multiple related records.
One more important point: The order example above checks stock before updating it. That check alone isn't safe against concurrent requests. We'll fix that in the next section.
5. Understanding Race Conditions in Database Operations
A race condition occurs when the outcome of an operation depends on the timing of concurrent requests.
Suppose an online store has one unit of a product left.
Two customers place an order at almost the same time.
Without suitable protection, both requests could follow this sequence:
Request A Request B
--------- ---------
Read stock = 1
Read stock = 1
Check stock is sufficient
Check stock is sufficient
Reduce stock by 1
Reduce stock by 1
Create order
Create orderDepending on how the update is implemented, both orders might succeed even though only one unit was available.
This isn't a problem that can be solved by frontend validation or by checking stock in Python alone.
The database must coordinate the concurrent operations.
There are several ways to approach this problem.
Approach 1: Use a Conditional SQL Update
One effective solution is to update the stock only when sufficient inventory remains.
from sqlalchemy import update
from sqlalchemy.orm import Session
from models import Product
def reserve_stock(
db: Session,
product_id: int,
quantity: int,
) -> bool:
if quantity <= 0:
raise ValueError("Quantity must be greater than zero")
statement = (
update(Product)
.where(
Product.id == product_id,
Product.stock >= quantity,
)
.values(
stock=Product.stock - quantity,
)
)
result = db.execute(statement)
return result.rowcount == 1The key part is:
.where(
Product.id == product_id,
Product.stock >= quantity,
)The database evaluates the condition as part of the update.
If two transactions attempt to reserve the final unit, PostgreSQL coordinates the conflicting row updates. After one transaction succeeds, the other must evaluate the updated row and won't successfully reserve stock that is no longer available.
The function returns True when one row was updated and False when the reservation couldn't be completed.
Use it inside the same transaction as the order creation:
def create_order_safely(
db: Session,
customer_id: int,
product_id: int,
quantity: int,
):
if quantity <= 0:
raise ValueError("Quantity must be greater than zero")
with db.begin():
reserved = reserve_stock(
db,
product_id,
quantity,
)
if not reserved:
raise ValueError(
"Product not found or insufficient stock"
)
order = Order(
customer_id=customer_id,
status="confirmed",
)
db.add(order)
db.flush()
db.add(
OrderItem(
order_id=order.id,
product_id=product_id,
quantity=quantity,
)
)
return {"order_id": order.id}Here, reserve_stock() executes within the transaction opened by create_order_safely().
If creating the order or order item fails, the stock reduction is rolled back as well.
In a real API, you might distinguish a missing product from insufficient stock by performing an additional lookup or using a more detailed database operation. The simpler error above intentionally avoids that distinction.
This pattern is useful for inventory, seat reservations, quota consumption, and other operations where a value must not exceed an available limit.
Approach 2: Use SELECT FOR UPDATE
Sometimes you need to read a record, perform several calculations, and then update it.
In those cases, a row-level lock may be a better fit.
PostgreSQL supports SELECT ... FOR UPDATE, which locks the selected rows against conflicting updates until the transaction ends.
With SQLAlchemy:
from sqlalchemy import select
from sqlalchemy.orm import Session
from models import Product
def reserve_stock_with_lock(
db: Session,
product_id: int,
quantity: int,
):
if quantity <= 0:
raise ValueError("Quantity must be greater than zero")
with db.begin():
statement = (
select(Product)
.where(Product.id == product_id)
.with_for_update()
)
product = db.scalar(statement)
if not product:
raise ValueError("Product not found")
if product.stock < quantity:
raise ValueError("Insufficient stock")
product.stock -= quantity
return {
"product_id": product.id,
"remaining_stock": product.stock,
}The transaction locks the product row before checking the stock.
If another transaction tries to lock the same row, it must wait until the first transaction completes. The second transaction can then read the current value rather than relying on a stale value from before the lock.
This approach is useful when the business operation requires more complex decisions than a single conditional update can express.
However, locks should be held for as little time as possible. Don't call an external payment API or wait for user input while holding a database row lock.
Important: Don't combine the two transaction-owning examples above by calling reserve_stock_with_lock() inside another function that has already opened db.begin(). That function manages its own transaction. In a larger service, refactor the locked database operations into a helper that assumes the caller already owns the transaction.
6. Choosing the Right Isolation Level
PostgreSQL supports several transaction isolation levels. The isolation level determines what a transaction can observe while other transactions modify the database.
Read Committed
READ COMMITTED is PostgreSQL's default isolation level.
Each statement sees data committed before that statement began, with special handling for statements that encounter concurrently updated rows.
This works well for many standard API operations.
However, separate statements in the same transaction can observe different committed states. A value read in one statement isn't necessarily unchanged by the next statement.
Repeatable Read
REPEATABLE READ provides a stable snapshot for the transaction.
Repeated reads generally see the same committed database snapshot, although concurrent writes can cause serialization-related failures when the transaction attempts to modify rows that changed after its snapshot was established.
This can help with workflows that require a consistent view of several records.
Serializable
SERIALIZABLE provides the strongest standard isolation level in PostgreSQL.
It aims to make concurrent transactions behave as though they ran one after another in some serial order.
However, transactions may fail with serialization errors when PostgreSQL detects a conflict that would violate this guarantee.
Your application must be prepared to retry eligible transactions.
For example, with SQLAlchemy, you can configure the engine's isolation level:
from sqlalchemy import create_engine
engine = create_engine(
DATABASE_URL,
isolation_level="SERIALIZABLE",
)This configuration applies to connections obtained from that engine. Don't switch your entire application to SERIALIZABLE without evaluating the performance implications and retry requirements.
For many applications, READ COMMITTED combined with conditional updates, appropriate constraints, and row-level locks is sufficient.
Choose the isolation level based on the actual business invariant you're trying to protect rather than assuming the strongest option is always the best.
7. Handling Transaction Failures and Retries
Concurrency control introduces another responsibility: dealing with transactions that fail because of conflicts.
For example, PostgreSQL might abort a transaction under SERIALIZABLE isolation with SQLSTATE 40001, indicating a serialization failure.
Deadlocks can also occur when transactions acquire locks in conflicting orders. PostgreSQL commonly reports these with SQLSTATE 40P01.
These errors don't necessarily mean the application is broken. They can be an expected consequence of concurrent activity.
The important part is knowing when and how to retry.
Here's a simplified retry pattern:
import random
import time
from sqlalchemy.exc import DBAPIError
RETRYABLE_SQLSTATES = {
"40001", # Serialization failure
"40P01", # Deadlock detected
}
def get_sqlstate(error: DBAPIError):
original = error.orig
sqlstate = getattr(original, "sqlstate", None)
if sqlstate is None:
sqlstate = getattr(original, "pgcode", None)
return sqlstate
def run_with_retry(operation, max_attempts=3):
for attempt in range(max_attempts):
try:
return operation()
except DBAPIError as error:
sqlstate = get_sqlstate(error)
if (
sqlstate not in RETRYABLE_SQLSTATES
or attempt == max_attempts - 1
):
raise
delay = 0.05 * (2 ** attempt)
time.sleep(delay + random.uniform(0, 0.03))This helper illustrates the general idea, but there are several things to keep in mind.
First, the operation must create a fresh transaction attempt each time. A failed SQLAlchemy transaction cannot simply continue as though nothing happened.
Second, the database session must be in a clean state before the next attempt. One straightforward design is for each attempt to use a fresh session.
Third, retries should be limited to errors that are genuinely transient and safe to retry.
For example, retrying a serialization failure is often reasonable. Retrying a validation error or a duplicate-email error usually isn't.
Don't Repeat External Side Effects During Retries
Consider an order operation that does the following:
Creates an order in PostgreSQL.
Charges a payment through an external payment provider.
Updates the order status.
Commits the transaction.
If the database transaction fails after the payment succeeds, retrying the entire operation could charge the customer again.
Database rollbacks cannot undo external API calls.
For workflows involving payments, email delivery, or third-party services, consider idempotency keys, durable workflow states, and the transactional outbox pattern.
For example, the database transaction can create both the order and an outbox event. A separate worker reads the event and performs the external action.
This avoids pretending that PostgreSQL and an external payment service share one atomic transaction.
8. Maintaining Data Integrity with Database Constraints
Application validation is useful, but it shouldn't be the only line of defense.
Imagine two API requests attempt to register the same email address simultaneously.
Both requests check whether the email exists. Both find no matching user. Both attempt to insert a new user.
A check-then-insert pattern alone cannot reliably prevent duplicates.
A database uniqueness constraint can:
from sqlalchemy import String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from database import Base
class User(Base):
__tablename__ = "users"
__table_args__ = (
UniqueConstraint(
"email",
name="uq_users_email",
),
)
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(
String(255),
nullable=False,
)PostgreSQL enforces the constraint even when concurrent requests attempt to insert the same email.
You should still validate the request and provide a useful error response, but the database is responsible for guaranteeing uniqueness.
Other useful constraints include:
Foreign keys to prevent references to nonexistent records.
Check constraints to enforce rules such as positive quantities or nonnegative balances.
Unique constraints to prevent duplicate business records.
Not-null constraints to ensure required fields are present.
For example:
ALTER TABLE order_items
ADD CONSTRAINT order_items_quantity_positive
CHECK (quantity > 0);These rules protect your data regardless of whether a write comes from a FastAPI endpoint, a background worker, a script, or another application.
9. Handling Database Errors Without Exposing Internal Details
Database errors should be handled deliberately.
For example, a duplicate email is a predictable business error, while an unexpected connection failure is an infrastructure problem.
Your API shouldn't return a raw PostgreSQL exception to the client.
A simplified example:
from fastapi import HTTPException
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from models import User
def register_user(db: Session, email: str):
try:
with db.begin():
user = User(email=email)
db.add(user)
db.flush()
user_id = user.id
except IntegrityError as error:
# Production code should inspect the specific
# constraint before mapping this to a 409 response.
raise HTTPException(
status_code=409,
detail="Unable to create user with these details",
) from error
return {"id": user_id}This example uses a broad IntegrityError handler for simplicity. In a real application, not every integrity error means that the email already exists. A foreign-key violation or another constraint failure may indicate a different problem.
Inspect the specific database constraint or SQLSTATE before translating an error into a business response.
Also, be careful about returning detailed messages that reveal whether a particular email address belongs to an existing account. Your response policy should account for privacy and account-enumeration risks.
10. Testing Transactions and Concurrent Requests
Database transaction behavior should be tested against PostgreSQL, especially when your production application uses PostgreSQL.
SQLite can be useful for some unit tests, but its locking behavior and SQL features differ from PostgreSQL. A test suite that passes on SQLite doesn't automatically prove that your PostgreSQL concurrency logic is correct.
Test Rollbacks
A rollback test should verify that a failed operation doesn't leave partially committed records.
For example, you can arrange for an order creation operation to fail after inserting the order but before completing the inventory update.
After the transaction rolls back, verify that:
No order was committed.
No order items were committed.
Product stock remains unchanged.
The test must use a transaction setup that accurately reflects the production code's commit and rollback behavior.
Test Concurrent Inventory Updates
For an inventory test, create a product with one unit of stock and run two separate requests concurrently.
Both requests attempt to purchase that unit.
The expected result is:
One request succeeds.
The other request reports insufficient inventory.
The final stock is zero.
Only one order is committed.
Use separate database sessions for concurrent requests. Sharing one SQLAlchemy session between concurrent tasks or threads is not safe.
Test Constraints
Test that PostgreSQL rejects invalid data even if it bypasses the normal API validation.
For example, inserting a negative stock value should fail if the products_stock_nonnegative constraint exists.
These tests help verify that your database protects important business rules independently of the API layer.
11. Practical Transaction Best Practices for Production
When your FastAPI application begins handling real customers and increasing traffic, a few habits make a substantial difference.
Keep transactions short. Don't perform network calls, send emails, or run slow computations while holding database locks.
Use one clear transaction boundary per business operation. If creating an order requires several writes, those writes should normally belong to one transaction.
Use database constraints. Don't rely exclusively on Python checks for uniqueness, foreign-key relationships, or other critical invariants.
Use conditional updates or row locks for concurrent changes. Inventory, quotas, and balances often require stronger protection than a normal read followed by a write.
Handle retries carefully. Retry only appropriate transient failures, and ensure each attempt starts with a clean transaction.
Use idempotency for important operations. If a client retries an order request because the response timed out, the application should have a strategy for preventing duplicate orders.
Avoid unnecessary commits. Committing after every individual database operation can leave partially completed business workflows.
Monitor transaction duration and lock contention. Long-running transactions can cause blocked queries, increased resource usage, and operational problems.
Use migrations. Keep schema changes controlled and review them before deployment.
Test with PostgreSQL. Pay special attention to concurrency, constraints, rollback behavior, and isolation levels.
These practices are particularly important for e-commerce applications, booking systems, financial workflows, subscription platforms, and other applications where inconsistent data can have real consequences.
Conclusion
Database transactions are one of those topics that become much more important as soon as an application starts handling real business operations.
With FastAPI and PostgreSQL, managing transactions correctly means more than calling commit() after an insert. You need to understand where transactions begin and end, how rollbacks work, how concurrent requests interact, and which business rules should be enforced by the database.
For straightforward operations, SQLAlchemy's transaction context managers provide a clean way to group related writes. For concurrent updates, conditional SQL statements and row-level locks help prevent race conditions. For stronger consistency requirements, PostgreSQL isolation levels and carefully designed retry logic can provide additional protection.
The most important lesson is to make your business rules explicit and enforce them at the right level.
If two customers can't purchase the same final unit of stock, the database should guarantee that outcome. If an order and its items must be created together, they should share a transaction. If duplicate records aren't allowed, a database constraint should enforce that rule.
Once you build these principles into your FastAPI backend, your application becomes much more reliable as traffic increases and multiple users begin performing operations at the same time.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


