Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Optimistic Locking Implementation in Python

14 min readintermediate
Website QA and SEO audits

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 never takes a lock. You read a record together with a version token (an integer, a timestamp, a SQL Server rowversion, an HTTP ETag), mutate a private copy, then write back with the token in the predicate: UPDATE ... SET v = v + 1 WHERE id = ? AND v = ?. If the affected-row count comes back zero, somebody else wrote first, so you discard your work and retry from a fresh read. The whole design is a bet that conflicts are rare, and the cost of losing the bet is a wasted round trip rather than a stalled thread. That is the opposite trade from mutual exclusion, which pays coordination cost on every access so conflicts become impossible. Two hazards are permanent. The retry loop must be bounded and jittered or contention becomes livelock. And a token that can be reused makes equality a lie: the value went A, then B, then back to A, your check passes, and a change you never observed is silently overwritten. The eight languages diverge because the token lives somewhere different in each. Some hand you a declarative version column in the ORM, some make you count rows off the driver yourself, and in shared memory the primitive is a hardware compare-and-swap whose exact signature, memory ordering rules and spurious-failure behaviour are genuinely different per language.

Optimistic Locking in Python: what you actually reach for

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.

Python implementation

Reviewers want the retry loop outside the session rather than inside it, and a brand new Session per attempt. A bare except around commit gets rejected; catch StaleDataError specifically. The conditional UPDATE must be a single statement, because a SELECT followed by an unconditional UPDATE is exactly the bug you are trying to fix. Let SQLAlchemy own the counter through version_id_col or version_id_generator instead of hand-bumping it. Backoff uses random.uniform jitter, and tenacity is the accepted third-party retry decorator over a hand-rolled while True.
python
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 Free

The Python-specific 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 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.

Performance in Python, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Optimistic Locking between languages.

Real-World Applications

Optimistic Locking is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Optimistic Locking helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Optimistic Locking appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Optimistic Locking over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Optimistic Locking to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.