ORM and Lost Updates

Two requests update the same profile at almost the same time.

Both read:

name = "Alex"

One writes "Alex Kumar".

The other writes "Alex Smith".

If the second request uses stale data, it can overwrite the first update.

This is a lost update.

Why It Happens

A typical ORM flow is:

SELECT → modify object → UPDATE

Two requests can read the same old value before either writes.

The later update may overwrite the earlier one.

A transaction does not automatically eliminate this problem. The result depends on the database, isolation level, locking behavior, and SQL being executed.

How to Prevent It

Common approaches include:

  • Optimistic locking — detect that the data changed before saving.

  • Pessimistic locking — lock the row during the transaction.

  • Atomic updates — let the database perform operations such as counter = counter + 1.

The right choice depends on contention, latency, and how conflicts should be handled.

Common Mistake

A single-request test usually looks correct.

The problem appears when multiple requests update the same row concurrently.

Key Takeaway

ORMs simplify database access, but they do not automatically solve concurrent update problems.

Common Questions / FAQ

Does an ORM prevent lost updates?

No. Concurrency behavior depends on the database and the application's concurrency-control strategy.

Is a transaction enough?

Not necessarily. Isolation and locking behavior matter.

When is optimistic locking useful?

When conflicts are possible and the application can detect and handle stale updates.

What about counters?

An atomic database update is often preferable to reading, incrementing, and writing the value from application code.

What’s your technical perspective on preventing lost updates? Share it in the comments.

Previous Post Next Post