Back

Data Integrity

Data Safety

Making sure two people can't buy the exact same seat at the same time. It's like a digital "occupied" sign for data.

1 Race condition

Two people buy the last seat at the same time

There's one ticket left. Two users click Buy at the exact same millisecond. Both reads say "1 available." Both writes go through. Now you've sold a ticket that doesn't exist. The fix is to check and decrement in one locked step.

Buggy: inventory drops to -1.
Fixed: atomic check. Second user gets "SOLD OUT".

Hit Bug to oversell. Hit Atomic to lock the database while you check.

2 Optimistic locking

Check the version number before saving

Every row has a version number. You read it when you open the record. When you save, the database checks that the number hasn't changed. If someone else saved first, your write is rejected and you have to refresh.

Two users edit the same record. Watch the second save fail because the version moved on.

3 Deadlock

Two processes wait for each other forever

Process A needs lock 1, then lock 2. Process B needs lock 2, then lock 1. Each grabs its first lock and waits for the second. They wait forever. The fix is to always grab locks in the same order.

Watch each process grab a lock the other needs. Neither moves. The clock stops.

Let's Lock It Down