惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
Forbes - Security
Forbes - Security
WordPress大学
WordPress大学
P
Proofpoint News Feed
T
Threat Research - Cisco Blogs
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
Spread Privacy
Spread Privacy
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
P
Privacy International News Feed
A
About on SuperTechFans
T
Tailwind CSS Blog
I
InfoQ
S
Securelist
云风的 BLOG
云风的 BLOG
罗磊的独立博客
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
B
Blog RSS Feed
V
Visual Studio Blog
Know Your Adversary
Know Your Adversary
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
腾讯CDC
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
AWS News Blog
AWS News Blog
博客园 - 【当耐特】
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
F
Full Disclosure
S
Secure Thoughts
博客园 - 司徒正美
J
Java Code Geeks
Y
Y Combinator Blog
Google Online Security Blog
Google Online Security Blog
GbyAI
GbyAI
N
News and Events Feed by Topic
Help Net Security
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Project Zero
Project Zero
T
Tenable Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tor Project blog
MyScale Blog
MyScale Blog
Scott Helme
Scott Helme
小众软件
小众软件
K
Kaspersky official blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
# Unit of Work: Managing Database Transactions Like a Pro with Python
Diego Fernando Castillo Mamani · 2026-06-24 · via DEV Community

Diego Fernando Castillo Mamani

Introduction

Every serious backend developer eventually faces the same problem: you need to make multiple changes to a database as part of a single business operation, and you need all of them to succeed or none of them to go through. Partial updates are worse than no updates at all - they leave your data in an inconsistent state that can be nearly impossible to debug in production.
This is not a new problem. Enterprise developers have been solving it for decades, and Martin Fowler documented the canonical solution in his 2002 book Patterns of Enterprise Application Architecture: the Unit of Work pattern.
In this article we are going to go deep on what Unit of Work is, why it exists, how it works internally, and how to build a clean, production-quality implementation from scratch in Python using only the standard library. By the end you will have a working implementation you can adapt to any project, and a solid understanding of how popular frameworks like SQLAlchemy and Django ORM implement this pattern under the hood.
The full source code is available on GitHub:
👉 github.com/diegocastillo12/unit-of-work-python

  • - ## Background: What is the Unit of Work Pattern? The Unit of Work pattern is part of Martin Fowler's catalog of Patterns of Enterprise Application Architecture (PoEAA), a collection of battle-tested solutions for common problems in enterprise software design. Fowler defines it as follows: > "A Unit of Work maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Let's unpack that definition carefully. "Maintains a list of objects affected by a business transaction" - this means the Unit of Work acts as a tracker. When your business logic creates a new object, modifies an existing one, or marks one for deletion, it does not immediately write to the database. Instead, it registers the change with the Unit of Work, which keeps an in-memory list of everything that needs to happen. "Coordinates the writing out of changes" - when the business transaction is complete and everything looks correct, the Unit of Work flushes all the accumulated changes to the database in a single coordinated operation. This is the commit() call. "Resolution of concurrency problems" - by batching all writes into a single transaction, the Unit of Work also helps manage concurrent access. Either all changes go through together or none do, which prevents other processes from seeing partial states. The pattern is closely related to two others from the same catalog: the Identity Map (which ensures that each database record is loaded only once per transaction, preventing duplicate in-memory objects) and the Repository (which abstracts the data access layer and uses the Unit of Work to coordinate persistence). Together these three patterns form the backbone of most modern ORM implementations.
  • - ## The Problem it Solves: A Concrete Example To understand why Unit of Work matters, let's look at what happens without it. Imagine you are building an e-commerce platform. When a customer places an order, your system needs to:
  • Create a new order record in the orders table
  • Deduct the purchased quantity from the inventory table
  • Record the total price for billing Without Unit of Work, a naive implementation might look like this:
def process_order_naive(conn, item_id, quantity):
 cursor = conn.cursor()
# Step 1: insert the order
 cursor.execute("INSERT INTO orders (item_id, quantity) VALUES (?, ?)", (item_id, quantity))
 conn.commit() # committed immediately
# Step 2: update inventory
 cursor.execute("UPDATE inventory SET stock = stock - ? WHERE id = ?", (quantity, item_id))
 conn.commit() # committed immediately
# Step 3: record billing
 cursor.execute("INSERT INTO billing (item_id, quantity) VALUES (?, ?)", (item_id, quantity))
 conn.commit() # committed immediately

This looks reasonable but has a critical flaw. If step 2 fails - say, due to a network error, a constraint violation, or a bug - the order already exists in the database but the stock was never decremented. You now have:

  • An order that references a product
  • Inventory that still shows the original stock level
  • No billing record Your database is now inconsistent. A customer placed an order and your system thinks the stock is still available. The next customer might be able to order the same item even though it is already sold. Debugging this in production at 2am is not a good time. The root cause is simple: each operation was committed independently. There was no coordination. With Unit of Work, all three operations are registered in memory and only committed together as a single atomic transaction. If any step fails, all three are rolled back automatically. The database either reflects the complete order or it reflects nothing - there is no in-between state.
  • - ## Core Concepts in Detail Before diving into code, let's understand the four core operations that define a Unit of Work: ### register_new(obj) Called when a new domain object is created that does not yet exist in the database. The Unit of Work adds it to an internal new_objects list. On commit, these become INSERT statements. ### register_dirty(obj) Called when an existing domain object has been modified. "Dirty" is a classic database term meaning "modified but not yet persisted". The Unit of Work adds it to a dirty_objects list. On commit, these become UPDATE statements. ### register_deleted(obj) Called when a domain object needs to be removed from the database. The Unit of Work adds it to a deleted_objects list. On commit, these become DELETE statements. ### commit() The moment of truth. When called, the Unit of Work iterates over all three lists and generates the corresponding SQL statements, executes them inside a single database transaction, and calls connection.commit(). If anything fails at any point, it calls connection.rollback() and raises the exception so the caller knows something went wrong. The beauty of this design is that your business logic never writes to the database directly. It only works with in-memory Python objects and registers intent. The Unit of Work handles all the SQL coordination.
  • - ## Implementation: Step by Step Now let's build the full implementation. We are using Python's built-in sqlite3 library and dataclasses - no external dependencies required. ### Step 1: Define the Domain Models
import sqlite3
from dataclasses import dataclass
from typing import List, Any, Optional
@dataclass
class InventoryItem:
 id: int
 name: str
 price: float
 stock: int
@dataclass
class Order:
 id: Optional[int]
 item_id: int
 quantity: int
 total_price: float

We use Python dataclasses for simplicity. In a real project these would be your domain entities - classes that represent core business concepts in your system, completely ignorant of how they are persisted.
Notice that Order.id is Optional[int] - when we create a new order it does not have a database ID yet. The database will assign one on insert.

Step 2: Build the Unit of Work Class

class UnitOfWork:
 """
 Implements the Unit of Work design pattern.
 Maintains a list of objects affected by a business transaction
 and coordinates the writing out of changes and the resolution
 of concurrency problems.
Reference: Fowler, M. (2002). Patterns of Enterprise Application
 Architecture. Addison-Wesley.
 https://martinfowler.com/eaaCatalog/unitOfWork.html
 """
def __init__(self, connection: sqlite3.Connection):
 self.connection = connection
 self.new_objects: List[Any] = []
 self.dirty_objects: List[Any] = []
 self.deleted_objects: List[Any] = []
def __enter__(self):
 return self
def __exit__(self, exc_type, exc_val, exc_tb):
 if exc_type is not None:
 self.rollback()
 else:
 self.commit()
 self._clear()
def _clear(self):
 self.new_objects.clear()
 self.dirty_objects.clear()
 self.deleted_objects.clear()
def register_new(self, obj: Any):
 if obj not in self.new_objects:
 self.new_objects.append(obj)
def register_dirty(self, obj: Any):
 if obj not in self.dirty_objects:
 self.dirty_objects.append(obj)
def register_deleted(self, obj: Any):
 if obj not in self.deleted_objects:
 self.deleted_objects.append(obj)
def commit(self):
 cursor = self.connection.cursor()
 try:
 # Process new objects - INSERT
 for obj in self.new_objects:
 if isinstance(obj, Order):
 cursor.execute(
 "INSERT INTO orders (item_id, quantity, total_price) "
 "VALUES (?, ?, ?)",
 (obj.item_id, obj.quantity, obj.total_price)
 )
 elif isinstance(obj, InventoryItem):
 cursor.execute(
 "INSERT INTO inventory (id, name, price, stock) "
 "VALUES (?, ?, ?, ?)",
 (obj.id, obj.name, obj.price, obj.stock)
 )
# Process dirty objects - UPDATE
 for obj in self.dirty_objects:
 if isinstance(obj, InventoryItem):
 cursor.execute(
 "UPDATE inventory SET name=?, price=?, stock=? WHERE id=?",
 (obj.name, obj.price, obj.stock, obj.id)
 )
 elif isinstance(obj, Order):
 cursor.execute(
 "UPDATE orders SET item_id=?, quantity=?, total_price=? WHERE id=?",
 (obj.item_id, obj.quantity, obj.total_price, obj.id)
 )
# Process deleted objects - DELETE
 for obj in self.deleted_objects:
 if isinstance(obj, InventoryItem):
 cursor.execute(
 "DELETE FROM inventory WHERE id=?", (obj.id,)
 )
 elif isinstance(obj, Order):
 cursor.execute(
 "DELETE FROM orders WHERE id=?", (obj.id,)
 )
self.connection.commit()
 print("[UoW] Transaction committed successfully.")
except Exception as e:
 self.rollback()
 raise e
def rollback(self):
 self.connection.rollback()
 print("[UoW] Transaction rolled back.")

A few things worth highlighting here:
Context manager support - implementing __enter__ and __exit__ allows the with statement. If an exception is raised anywhere inside the with block, Python automatically calls __exit__ with the exception information, which triggers rollback(). If everything succeeds, it calls commit(). This means the caller does not need any try/except logic - the Unit of Work handles it.
Duplicate guard - both register_new and register_dirty check if obj not in list before appending. This prevents the same object from being processed twice if your business logic accidentally registers it more than once.
Clear on exit - _clear() is called in __exit__ regardless of success or failure. This ensures the Unit of Work is clean and ready for reuse after the transaction completes.

Step 3: Set Up the Database

def setup_db() -> sqlite3.Connection:
 """
 Initializes an in-memory SQLite database with schema and seed data.
 In a real application this would point to a persistent database.
 """
 conn = sqlite3.connect(":memory:")
 cursor = conn.cursor()
cursor.execute("""
 CREATE TABLE inventory (
 id INTEGER PRIMARY KEY,
 name TEXT NOT NULL,
 price REAL NOT NULL,
 stock INTEGER NOT NULL
 )
 """)
cursor.execute("""
 CREATE TABLE orders (
 id INTEGER PRIMARY KEY AUTOINCREMENT,
 item_id INTEGER NOT NULL,
 quantity INTEGER NOT NULL,
 total_price REAL NOT NULL,
 FOREIGN KEY (item_id) REFERENCES inventory(id)
 )
 """)
# Seed with two products
 cursor.execute(
 "INSERT INTO inventory (id, name, price, stock) VALUES (1, 'Laptop', 1200.0, 10)"
 )
 cursor.execute(
 "INSERT INTO inventory (id, name, price, stock) VALUES (2, 'Smartphone', 800.0, 5)"
 )
conn.commit()
 return conn

We use :memory: for simplicity - this creates a temporary SQLite database that lives only in RAM. For a real application you would replace this with a connection string to your actual database.

Step 4: Business Logic Using Unit of Work

def process_order(conn: sqlite3.Connection, item_id: int, quantity: int):
 """
 Processes a purchase order using the Unit of Work pattern.
 All database changes are coordinated through the UoW - none
 of them touch the database directly until commit() is called.
 """
 cursor = conn.cursor()
 cursor.execute(
 "SELECT id, name, price, stock FROM inventory WHERE id=?", (item_id,)
 )
 row = cursor.fetchone()
if not row:
 raise ValueError(f"Product with ID {item_id} not found.")
# Load the domain object into memory
 item = InventoryItem(id=row[0], name=row[1], price=row[2], stock=row[3])
print(
 f"\n[Process] Attempting to purchase {quantity}x "
 f"'{item.name}' (Available stock: {item.stock})"
 )
# The entire business transaction runs inside the UoW context
 with UnitOfWork(conn) as uow:
# Validate business rules BEFORE registering any changes
 if item.stock < quantity:
 raise ValueError(
 f"Insufficient stock for '{item.name}'. "
 f"Requested: {quantity}, Available: {item.stock}"
 )
# Modify the in-memory object and register it as dirty
 item.stock -= quantity
 uow.register_dirty(item)
# Create the new order object and register it as new
 total_price = item.price * quantity
 order = Order(
 id=None,
 item_id=item_id,
 quantity=quantity,
 total_price=total_price
 )
 uow.register_new(order)
# At this point nothing has been written to the database yet.
 # When the 'with' block exits successfully, __exit__ calls commit()
 # and both changes (stock update + order insert) go through together.

This is the key design point. Inside the with block, we:

  1. Load the current state from the database
  2. Validate the business rule (enough stock available)
  3. Modify the in-memory objects
  4. Register the changes with the Unit of Work Nothing touches the database until the with block exits cleanly. If the stock check fails and raises a ValueError, the __exit__ method sees the exception and calls rollback() instead of commit(). The database remains untouched. ### Step 5: Utility and Main Execution
def print_db_state(conn: sqlite3.Connection):
 cursor = conn.cursor()
 print("\n - - DATABASE CURRENT STATE - -")
 print("Inventory Table:")
 cursor.execute("SELECT * FROM inventory")
 for row in cursor.fetchall():
 print(f" ID: {row[0]} | Name: {row[1]:<12} | Price: ${row[2]:.2f} | Stock: {row[3]}")
print("Orders Table:")
 cursor.execute("SELECT * FROM orders")
 orders = cursor.fetchall()
 if not orders:
 print(" (empty)")
 for row in orders:
 print(f" ID: {row[0]} | Item ID: {row[1]} | Quantity: {row[2]} | Total: ${row[3]:.2f}")
 print(" - - - - - - - - - - - - - - - ")
if __name__ == "__main__":
 conn = setup_db()
print("=== Initial Database State ===")
 print_db_state(conn)
print("\n=== Test Case 1: Successful Order (3 Laptops) ===")
 try:
 process_order(conn, item_id=1, quantity=3)
 print("Result: Order processed successfully.")
 except Exception as e:
 print(f"Result: Failed - {e}")
 print_db_state(conn)
print("\n=== Test Case 2: Failed Order (6 Smartphones, only 5 in stock) ===")
 try:
 process_order(conn, item_id=2, quantity=6)
 print("Result: Order processed successfully.")
 except Exception as e:
 print(f"Result: Failed as expected - {e}")
 print_db_state(conn)

  • - ## Expected Output Running python unit_of_work.py produces: