Skip to content

Lesson 7 of 9 · 25m

Correctness Reasoning: Invariants and Linearizability

How to reason about concurrent code without simulating every schedule: protect invariants, define atomic points, and make linearizability an explicit contract.

You cannot test every interleaving, and you cannot hold the whole scheduler in your head. Senior engineers survive concurrency by shrinking the reasoning problem: name the invariant, identify the operations that can violate it, and define what one operation is allowed to observe from another. Correctness becomes a property of the design rather than a hope about timing.

Invariants are the unit of correctness

An invariant is a statement that is true whenever the object is in a consistent state. Examples:

  • balance equals the sum of all posted ledger entries
  • size equals the number of linked nodes in the queue
  • a job is either queued or running, never both
  • if closed is true, no producer may append again Concurrent code may temporarily break an invariant inside a critical section, but no other thread may observe that broken state. This is why locks protect critical sections, not variables: the section is the boundary inside which inconsistency is private.
mu.Lock()
account.Balance += delta
account.Version++
mu.Unlock()

Either observers see neither write or both writes. The invariant is preserved publicly even though it is broken privately between the two statements.

Linearizability means operations appear atomic

Linearizability is the standard correctness condition for concurrent objects: every operation appears to take effect instantaneously at some point between its invocation and response, and the resulting order matches real time.

thread A: enqueue(x)  |-------------|
thread B: enqueue(y)       |-----|
thread C: dequeue()             |-------| -> x

If A completed before C began, C must not return as though A never happened. There is some legal order of operations that explains every response. If no such order exists, the implementation is not linearizable.

The practical benefit is composition. If each object is linearizable, you can reason about operations as if they have atomic points, even when the implementation uses fine-grained locking or CAS.

Pick the atomic point deliberately

Sometimes the atomic point is a successful CAS. Sometimes it is the moment a lock is acquired. In more complex protocols it may depend on helping or future observation. The implementation detail matters less than the design question: where does the operation become visible to the abstract state?

A compare-and-exchange loop is a useful example:

Node* old_head = head.load();
while (!head.compare_exchange_weak(old_head, new_head)) {
    new_head->next = old_head;
}

The linearization point for a successful push is the successful CAS. Every failed iteration never happened at the abstract level. That is why retries do not violate correctness.

Weaker contracts are valid when they are explicit

Not every system needs linearizability. Metrics counters can be approximate. Caches can be eventually consistent. Presence systems can tolerate seconds of staleness. The mistake is not choosing a weaker model; the mistake is not saying so.

Write the contract in operational language:

  • reads may lag writes by up to five seconds
  • counts are approximate under contention
  • duplicate delivery is possible; consumers must be idempotent
  • after close returns success, later writes are rejected Those statements are testable. "Thread-safe" is not.

Field notes

  • If a reviewer cannot find the invariant, they cannot review the concurrency correctly. Put it in comments or design docs.
  • Multi-object invariants need one synchronization domain or immutable snapshots; linearizability does not automatically compose across multi-object transactions.
  • An operation that returns before durability does not linearize at durability time. Be precise about which state machine you mean.
  • Correctness proofs do not need formal notation. A one-page argument with states, transitions, and atomic points catches most design bugs.

Was this lesson helpful?

Sign in to rate