Database Transactions - ACID Properties
Introduction Yesterday, I went to a restaurant with my friends. We ordered some food, finished eating, and asked the waiter for the bill. While the waiter was preparing the bill, I started thinking about how the billing system works behind the scenes. When we place an order, the system has to do multiple things, like saving the order details, calculating the bill, and updating the payment status.…
Database Transactions and ACID Properties
A database transaction is a group of one or more database operations treated as a single unit of work. In our restaurant example, placing an order involves several operations: creating an order, saving ordered items, updating stock, and calculating the total bill. If any operation fails, we don't want incomplete data. To avoid this, we can group these operations into a single transaction.
A transaction typically involves three commands: BEGIN (starts the transaction), COMMIT (saves the changes), and ROLLBACK (undoes uncommitted changes).
Database transactions follow four important properties, known as ACID properties:
1. Atomicity: Ensures either all operations in a transaction succeed or none happen. For instance, when ordering 2 pizzas at ₹200 each, creating the order and updating stock must both occur. If the transaction fails before updating stock, the order should not be created, guaranteeing "all or nothing."
2. Consistency: Maintains database rules and constraints. Data consistency ensures the data remains correct and adheres to defined rules (e.g., foreign key constraints). Read consistency allows multiple transactions to access data without seeing inconsistent states.
3. Isolation: Controls how concurrent transactions interact. Isolation levels define the degree of separation between transactions, preventing unwanted interactions like dirty reads or phantom reads.
4. Durability: Guarantees committed transactions' changes survive crashes. Durability ensures committed changes are permanent, even after a system failure. Databases use transaction logs and recovery mechanisms to maintain durability.
In summary, ACID properties help maintain data integrity and reliability in database transactions, ensuring accurate and consistent data even in the face of failures.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to