๐๐ฎ๐๐ฎ๐ฏ๐ฎ๐๐ฒ ๐๐๐๐: ๐ช๐ต๐ฎ๐ ๐ถ๐ ๐๐ผ๐ป๐๐ถ๐๐๐ฒ๐ป๐ฐ๐?
You might think a database handles everything. It does not.
Consistency means your data must follow all rules before and after a transaction. If your rules say a bank balance cannot be negative, a transaction must not leave it at -$50.
Consistency happens at two levels:
- Database Level The database enforces technical rules automatically.
- Primary Keys: No duplicate IDs.
- Foreign Keys: No links to missing data.
- Constraints: Using CHECK or UNIQUE to block invalid values.
- Application Level The database does not know your business rules. It does not know your daily withdrawal limit is $30,000. You must write the code to check this.
The Danger: The Lost Update A common mistake happens when you read data, check it in your code, and then write it back.
Scenario:
- Account balance is $100.
- User A wants to withdraw $80.
- User B wants to withdraw $70.
If both users read the $100 balance at the same time, both checks pass. User A writes $20. User B writes $30. The final balance is $30. The $80 withdrawal from User A is lost. This is a failure of consistency.
How to fix it:
Use Single SQL Statements Instead of reading then writing, do it in one command. Example: UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock >= 1; This removes the time window for errors.
Optimistic Locking Use a version number. When you update, check if the version is still the same. If someone else changed it, the update fails. This works best when conflicts are rare.
Pessimistic Locking Lock the row when you read it. Others must wait until you finish. This works best for high-conflict tasks like flash sales.
Isolation Levels Adjust how much one transaction can see from another. Higher isolation levels prevent errors but slow down your system.
Summary Consistency is your responsibility. Use database constraints for technical rules and use locks or single SQL commands for business logic.