Nâng CaoFastAPI iconFastAPI

Transaction boundary trong FastAPI service nên đặt ở đâu?

Transaction boundary nên đặt quanh use-case cần atomic, thường ở service/application layer, không rải commit trong từng repository nhỏ. Repository chỉ thao tác dữ liệu; service quyết định commit/rollback cho toàn workflow.

Ví dụ ý tưởng:

python
async with session.begin():
    order = await orders.create(session, payload)
    await inventory.reserve(session, order.items)

Nếu mỗi repository tự commit, workflow nhiều bước sẽ khó rollback khi bước sau lỗi, dễ tạo dữ liệu nửa vời.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI