Optimistic Locking — ELI5
Imagine you and your roommate share a shopping list on the fridge. You both grab your phones, take a photo of the list, and head to different stores.
You add “milk” to your copy. Your roommate crosses off “eggs” on their copy. When you both come back and try to update the list on the fridge, there’s a problem — your roommate’s version doesn’t have “milk” because they copied the list before you added it.
Pessimistic locking would be like putting a padlock on the list — only one person can touch it at a time. Safe, but annoying. Nobody else can even look at it while you’re shopping.
Optimistic locking takes a different approach. It lets everyone work freely, but checks for conflicts at the end. It’s like putting a version number on the list: “Version 3.” Before updating the fridge list, you check: “Is it still Version 3?” If yes, great — update it to Version 4. If someone else already changed it to Version 4, your update is rejected and you need to look at the new version and try again.
Most of the time, people aren’t editing the same thing at the same moment. Optimistic locking bets on that. It doesn’t slow anyone down with locks, and the rare collision is handled by just retrying.
Your phone’s contacts, Google Docs, and even online shopping carts use this idea. Two people rarely edit the exact same record at the exact same time. And when they do, it’s better to say “hey, someone else changed this — take another look” than to block everyone from accessing the data.
One thing to remember: Optimistic locking lets everyone work without waiting, then checks for conflicts only when saving. If someone else changed the data first, you retry instead of overwriting their changes.
See Also
- Python Aioredis Understand Aioredis through a practical analogy so your Python decisions become faster and clearer.
- Python Alembic Understand Alembic through a practical analogy so your Python decisions become faster and clearer.
- Python Asyncpg Database asyncpg is the fastest way for Python to talk to PostgreSQL without making your program sit around waiting.
- Python Asyncpg Understand Asyncpg through a practical analogy so your Python decisions become faster and clearer.
- Python Cassandra Python Understand Cassandra Python through a practical analogy so your Python decisions become faster and clearer.