← Concepts

阅读中文版本

Seqlocks

A seqlock lets readers retry when a concurrent writer is detected, delivering fast lock-free reads for data that is written rarely.

concurrency

Definition

A sequence lock is a synchronisation primitive that pairs a counter with shared data, letting readers detect a concurrent write and retry rather than take a lock.

Context and scope

It suits structures that are updated infrequently but read from hot paths, such as time sources or configuration snapshots.

Common misconceptions

  • a seqlock gives readers a consistent but potentially old value on retry
  • seqlocks are safe for pointers to freed memory

Anti-patterns

  • exposing mutable pointers through a seqlock without lifetime protection
  • using a seqlock where writers are as frequent as readers

Related concepts

Related examples

Authoritative source

https://en.wikipedia.org/wiki/Seqlock

Definition

A sequence lock is a synchronisation primitive that pairs a counter with shared data, letting readers detect a concurrent write and retry rather than take a lock.

It suits structures that are updated infrequently but read from hot paths, such as time sources or configuration snapshots. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.

When to use it

A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.

How it works

Writers increment the counter before and after modifying the data, and readers sample the counter before and after reading and retry when it changed or was odd.

Readers never block writers, which is the appeal, but they can starve under heavy write pressure because each retry restarts from the beginning.

Trade-offs and alternatives

The pattern assumes readers only need a consistent snapshot and do not dereference memory a writer might reclaim, so it must not be used for owning pointers. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.

Common misconceptions

A persistent misconception is that a seqlock gives readers a consistent but potentially old value on retry. Another is that seqlocks are safe for pointers to freed memory. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.

Anti-patterns to avoid

Two recurring anti-patterns are to exposing mutable pointers through a seqlock without lifetime protection and to using a seqlock where writers are as frequent as readers. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Lock Fairness and Starvation, Coroutines, Software Transactional Memory.