Optimistic Locking Implementation in Rust
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 Rust as in every other language.
- ✓std::sync::atomic is the real primitive. AtomicU64, AtomicUsize and AtomicPtr expose compare_exchange(current, new, success: Ordering, failure: Ordering) -> Result<T, T>, where the Err arm hands back the value actually observed, so the optimistic loop is literally the type signature.
- ✓Reviewers expect Result rather than panics, a bounded loop, and the value from the Err arm fed straight into the next iteration instead of a second load, which would only reopen the race window.
- ✓The Rust trap: The borrow checker turns a retry loop into a design problem the other seven languages never face.
- ✓No GC and no boxing: the loop is a couple of registers and one instruction. On x86-64 every compare_exchange lowers to LOCK CMPXCHG whatever Ordering you pass, because the hardware RMW is already strongly ordered, so a Relaxed failure ordering buys compiler freedom rather than cycles.
What Optimistic Locking actually is
Optimistic Locking in Rust: what you actually reach for
Rust implementation
use std::sync::atomic::{AtomicU64, Ordering};
/// Optimistic increment: no lock is held, the write just fails if the value
/// moved, and the failure hands back what was actually there.
fn add_capped(cell: &AtomicU64, delta: u64, cap: u64) -> Result<u64, u64> {
let mut observed = cell.load(Ordering::Relaxed);
loop {
let next = observed.checked_add(delta).ok_or(observed)?;
if next > cap {
return Err(observed);
}
// *_weak may fail spuriously on LL/SC targets (AArch64), so it is only
// ever legal inside a loop. The Err arm carries the current value:
// reuse it instead of calling load() again, which reopens the window.
match cell.compare_exchange_weak(
observed,
next,
Ordering::AcqRel, // success: publishes the write
Ordering::Acquire, // failure: this is a load, never Release
) {
Ok(_) => return Ok(next),
Err(actual) => observed = actual,
}
}
}
// Row-level shape, same idea:
// sqlx::query!("UPDATE acct SET bal = bal - $1, v = v + 1 WHERE id = $2 AND v = $3",
// amt, id, v).execute(&pool).await?.rows_affected() == 1Think 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 Rust-specific trap
Performance in Rust, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Optimistic Locking?
std::sync::atomic is the real primitive. AtomicU64, AtomicUsize and AtomicPtr expose compare_exchange(current, new, success: Ordering, failure: Ordering) -> Result<T, T>, where the Err arm hands back the value actually observed, so the optimistic loop is literally the type signature. compare_exchange_weak is the loop-only variant. For rows, sqlx gives query!(...).execute(&pool).await?.rows_affected(), and Diesel's update(...).execute(conn) returns QueryResult<usize>; neither offers a JPA-style version attribute, you write the predicate yourself. Pointer reuse is handled by the crossbeam-epoch crate or by arc-swap, and reqwest::header::IF_MATCH covers the HTTP case.
What is the most common Rust mistake when implementing Optimistic Locking?
The borrow checker turns a retry loop into a design problem the other seven languages never face. Move the request body into the first attempt and it is gone; the second iteration will not compile, so you either clone per attempt or restructure so the loop owns the data and only lends it out. Most people meet this after writing the happy path and then reach for clone blindly, allocating on every retry. Second, compare_exchange_weak may fail spuriously on load-linked/store-conditional targets such as AArch64 even when the comparison would have succeeded, so using it outside a loop is simply a bug, while on x86-64 it costs nothing. Third, the failure Ordering describes a load, so Release and AcqRel are not valid values there at all.
How does Optimistic Locking actually perform in Rust?
No GC and no boxing: the loop is a couple of registers and one instruction. On x86-64 every compare_exchange lowers to LOCK CMPXCHG whatever Ordering you pass, because the hardware RMW is already strongly ordered, so a Relaxed failure ordering buys compiler freedom rather than cycles. On AArch64 the ordering picks LDXR/STXR versus the acquiring and releasing LDAXR/STLXR pair. What actually costs is contention: each failed attempt takes exclusive ownership of the cacheline and hands it straight back, so beyond a handful of threads a plain Mutex often wins. At the database, rows_affected is free and the retry is a whole round trip. 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 trialBefore paying full price for a tool, check the student deals on AI and developer tools listed 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.