Optimistic Locking Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Optimistic Locking runs in O(1) time and O(1) space, in Python as in every other language.
- ✓There is no compare-and-set primitive in the standard library; threading offers no such call and the atomic-looking operations are CPython bytecode accidents, not guarantees.
- ✓Reviewers want the retry loop outside the session rather than inside it, and a brand new Session per attempt.
- ✓The Python trap: SQLAlchemy only bumps version_id_col when its unit of work notices a dirty attribute. Mutate a JSON or PickleType column in place, data["k"] = 1, and unless the column type was wrapped with sqlalchemy.ext.mutable.MutableDict.as_mutable the change is invisible: no UPDATE is emitted, the version never moves, and the write is lost with no exception raised anywhere.
- ✓The version predicate costs nothing at the database, since it rides the same primary-key index lookup the read already used.
What Optimistic Locking actually is
Optimistic Locking in Python: what you actually reach for
Python implementation
import random, time
from sqlalchemy import Integer, create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.orm.exc import StaleDataError
class Base(DeclarativeBase):
pass
class Account(Base):
__tablename__ = "account"
id: Mapped[int] = mapped_column(primary_key=True)
balance: Mapped[int] = mapped_column(Integer)
version: Mapped[int] = mapped_column(Integer, nullable=False)
# every ORM UPDATE now carries "AND version = :old" and bumps the column
__mapper_args__ = {"version_id_col": version}
engine = create_engine("postgresql+psycopg://localhost/bank")
def withdraw(acct_id: int, amount: int, attempts: int = 5) -> None:
for i in range(attempts):
session = Session(engine) # fresh Session每 attempt: the identity
try: # map would keep re-sending a stale row
acct = session.get(Account, acct_id)
if acct.balance < amount:
raise ValueError("insufficient funds")
acct.balance -= amount
session.commit() # UPDATE ... WHERE id=%s AND version=%s
return
except StaleDataError: # rowcount was 0: another writer won
session.rollback()
time.sleep(random.uniform(0, 0.005 * 2 ** i))
finally:
session.close()
raise RuntimeError("optimistic retry budget exhausted")Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Optimistic Locking?
There is no compare-and-set primitive in the standard library; threading offers no such call and the atomic-looking operations are CPython bytecode accidents, not guarantees. At the row level SQLAlchemy 2.x gives you the real thing declaratively: __mapper_args__ = {"version_id_col": version} makes every ORM UPDATE carry AND version = :old, bumps the column, and raises sqlalchemy.orm.exc.StaleDataError when the row count is zero. Django has no equivalent, so you write Model.objects.filter(pk=pk, version=v).update(version=F("version") + 1, ...) using django.db.models.F and check the returned int. For HTTP, httpx or requests set If-Match and you branch on status 412.
What is the most common Python mistake when implementing Optimistic Locking?
SQLAlchemy only bumps version_id_col when its unit of work notices a dirty attribute. Mutate a JSON or PickleType column in place, data["k"] = 1, and unless the column type was wrapped with sqlalchemy.ext.mutable.MutableDict.as_mutable the change is invisible: no UPDATE is emitted, the version never moves, and the write is lost with no exception raised anywhere. The second trap is reusing the Session after StaleDataError. The identity map still holds the stale instance carrying the stale version, so the retry re-sends the same losing predicate forever. Roll back, then expire_all or discard the Session entirely and build a new one.
How does Optimistic Locking actually perform in Python?
The version predicate costs nothing at the database, since it rides the same primary-key index lookup the read already used. The cost is Python-side: every retry is a full round trip plus a unit-of-work flush that runs tens of microseconds of interpreter work per object before the socket is touched, which is why hot paths drop to Core's update construct or raw SQL. The GIL is irrelevant here because each attempt blocks on I/O and releases it. Under asyncio a retry is nearly free, and that is precisely why it must be bounded: a thousand coroutines hammering one row will livelock without jittered backoff. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.