Overview
Transactions ensure that a series of database operations either all succeed or all fail together, maintaining data consistency and integrity. Drizzle provides a simple, type-safe transaction API.Basic Transactions
Simple Transaction
Wrap multiple operations in a transaction:Transaction Return Value
Return data from transactions:Transaction API
The transaction callback receives a transaction object (tx) that has the same API as db:
Rollback
Automatic Rollback
Transactions automatically roll back on errors:Manual Rollback
Explicitly roll back a transaction:Transaction Isolation
PostgreSQL Isolation Levels
Configure transaction isolation level:Access Mode
Set transaction to read-only:Deferrable Transactions
PostgreSQL-specific deferrable transactions:Nested Transactions
Savepoints
Use savepoints for partial rollbacks:Nested Transaction Pattern
Implement nested transaction logic:Use Cases
Bank Transfer
Atomic money transfer between accounts:Inventory Management
Update inventory and create order atomically:User Registration
Create user with related records:Error Handling
Catching Specific Errors
Retry Logic
Best Practices
- Keep transactions short: Long transactions hold locks and can cause performance issues
- Avoid external calls: Don’t make HTTP requests or other I/O inside transactions
- Handle errors: Always wrap transactions in try-catch blocks
- Use appropriate isolation: Choose the right isolation level for your use case
- Idempotency: Design operations to be safely retryable
- Read-only optimization: Use
accessMode: 'read only'for read-only transactions
Performance Tips
Batch Operations
Use batch inserts instead of multiple single inserts:Lock Only What’s Needed
Next Steps
Queries
Learn more about querying data
Migrations
Manage schema changes safely