← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Compare-And-Swap (CAS)

concurrency Advanced
debt(d9/e5/b5/t7)
d9 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'silent in production until users hit it' (d9). The detection_hints field states automated=no, and the code_pattern is purely a textual hint (WATCH|multi()|exec()). There is no tool listed that catches misuse — not checking the return value, spin-looping without backoff, or ignoring the ABA problem will all silently fail or degrade performance only under contention in production.

e5 Effort Remediation debt — work required to fix once spotted

Closest to 'touches multiple files / significant refactor in one component' (e5). The quick_fix mentions switching to Redis WATCH/MULTI/EXEC or DB UPDATE WHERE version=N, and always handling the failure case with retry/error logic. This isn't a single-line swap; it requires restructuring the retry logic, adding version columns or WATCH blocks, and auditing all call sites that rely on the CAS result — spanning meaningful rework within a component.

b5 Burden Structural debt — long-term weight of choosing wrong

Closest to 'persistent productivity tax' (b5). CAS applies across web, cli, and queue-worker contexts per applies_to. Any concurrent code path that uses optimistic locking must carry the cognitive and structural weight of retry loops, failure handling, and contention-awareness. It doesn't define the system's shape entirely, but it imposes an ongoing tax on every developer working on concurrent sections of the codebase.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'serious trap (contradicts how a similar concept works elsewhere)' (t7). The canonical misconception is that 'CAS is always superior to locking' — a competent developer familiar with lock-based concurrency will assume CAS is strictly better and use it everywhere, not realising that spin-looping under high contention wastes CPU and that locking is often more efficient in those scenarios. The ABA problem and silent failure on unchecked return values compound the trap further.

About DEBT scoring →

TL;DR

CAS atomically compares a memory location to an expected value and only swaps it if equal — the foundation of lock-free algorithms and optimistic concurrency control.

Explanation

CAS(location, expected, new): if *location == expected, set *location = new and return true; else return false. Hardware instruction on all modern CPUs (CMPXCHG on x86). Used in: lock-free data structures, optimistic locking (DB version check), Redis atomic operations (WATCH/MULTI/EXEC). ABA problem: value changes A→B→A — CAS sees A, thinks nothing changed, but it did. Solution: version-stamped CAS (include version in the compare). In PHP/databases: UPDATE ... WHERE version = N is a CAS operation. Redis WATCH monitors keys for changes before EXEC.

Common Misconception

CAS is always superior to locking — CAS retry loops under high contention spin and waste CPU. For high-contention scenarios, locking is often more efficient.

Why It Matters

CAS is the primitive underlying optimistic locking, Redis transactions, and lock-free algorithms — understanding it explains how high-performance concurrent systems avoid locks.

Common Mistakes

  • Ignoring the ABA problem in version-based CAS.
  • Spin-looping on failed CAS without backoff — wastes CPU under contention.
  • Not checking return value of CAS — silent failure.

Code Examples

✗ Vulnerable
// Redis CAS without WATCH — not atomic:
$val = $redis->get('counter');
if ($val < 10) $redis->set('counter', $val + 1); // Race between get and set
✓ Fixed
// Redis WATCH = CAS:
$redis->watch('counter');
$val = $redis->get('counter');
if ($val < 10) {
    $redis->multi();
    $redis->set('counter', $val + 1);
    if ($redis->exec() === null) {
        // Transaction failed — another client changed 'counter' — retry
    }
}
$redis->unwatch();

Added 23 Mar 2026
Views 29
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 1 ping W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S
No pings yet today
No pings yesterday
Perplexity 9 Amazonbot 5 Unknown AI 2 Ahrefs 2 ChatGPT 1 Google 1 Meta AI 1
crawler 20 pre-tracking 1
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: High
⚡ Quick Fix
Use Redis WATCH/MULTI/EXEC for CAS-style atomic sequences. Use DB UPDATE WHERE version = N for row-level CAS. Always handle the failure case (retry or error).
📦 Applies To
web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
WATCH|multi\(\)|exec\(\)
Auto-detectable: ✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: High Context: Function Tests: Update
CWE-362

✓ schema.org compliant