DEV Community

Cover image for Why I Over-Engineered a ULID Library for .NET
GigAHerZ
GigAHerZ

Posted on • Originally published at byteaether.github.io

Why I Over-Engineered a ULID Library for .NET

Unique identifiers are often treated as an afterthought, but for senior engineers and architects, they represent a critical choice in system design. "Good enough" identifiers are a ticking time bomb of index fragmentation and degraded performance.

Why ULID over UUIDv7?

While UUIDv7 is a step forward, its specification makes monotonicity optional. During high-concurrency bursts, many generators sacrifice order to stay fast. ByteAether.Ulid refuses this compromise. By mandating strict lexicographical sortability, it ensures your database indexes remain optimized and sequential.

Solving the Overflow Problem

A common failure point in ULID implementations is the 80-bit random component overflow. High-volume systems can easily exhaust the random space within a single millisecond, causing standard libraries to throw an OverflowException.

ByteAether.Ulid handles this by automatically incrementing the timestamp component. This ensures unique, sorted IDs continue to generate even under extreme load, providing a level of resilience that standard implementations lack.

Performance via CAS Strategy

In high-throughput environments, traditional locking mechanisms introduce significant overhead and latency. ByteAether.Ulid utilizes a lock-free compare-and-exchange (CAS) strategy to manage state.

By avoiding heavy OS-level locks and using hardware-level atomics to achieve the same synchronization, we eliminate the latency typical of normal locking mechanisms. This allows threads to resolve state changes with minimal friction, maximizing CPU efficiency while maintaining strict thread safety.

Strategic Features

  • Anti-Enumeration: Configurable random increments prevent attackers from guessing sequential IDs.
  • Temporal Queries: Use Ulid.MinAt() and Ulid.MaxAt() to perform range queries on your primary key without needing a CreatedAt column.
  • Zero Allocations: Optimized for standard generation paths to reduce GC pressure.

I have documented the full engineering rationale and performance benchmarks in a detailed post on my blog. If you are interested in the nuances of distributed system design, I invite you to read the full version.

Top comments (0)