Skip to content

perf(v7): lock-free atomic compare-and-swap monotonicity for NewV7 - #230

Open
AdamMagued wants to merge 1 commit into
google:masterfrom
AdamMagued:lock-free-v7-monotonicity
Open

AdamMagued wants to merge 1 commit into
google:masterfrom
AdamMagued:lock-free-v7-monotonicity

Conversation

@AdamMagued

Copy link
Copy Markdown

Replace the global timeMu mutex in getV7Time() with an atomic Compare-And-Swap (atomic.CompareAndSwapInt64) state loop.

Motivation

Previously, every call to NewV7() acquired a global mutex timeMu.Lock() to serialize timestamp increments and sub-millisecond sequence numbers. Under multi-goroutine concurrent workloads, this causes severe lock contention and thread synchronization overhead, contending with UUIDv1 operations that also share timeMu.

Solution

  • Store the 64-bit monotonically advancing state ((milli << 12) + seq) in lastV7time using lock-free atomic CAS.
  • If current timestamp falls behind or equals the previous issued state (next <= last), advance next = last + 1 atomically.
  • Added TestVersion7ConcurrentMonotonicity with 16 concurrent goroutines producing 80,000 UUIDs to verify strict monotonicity under concurrent contention.
  • 100% backward compatible and passes all unit and fuzz tests.

Fixes #226

@AdamMagued
AdamMagued requested a review from a team as a code owner October 2, 2026 20:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Proposal: Lock-free CAS monotonicity and branchless hex decoding for UUIDv7 (73% faster under contention)

1 participant