Skip to main content

Compare-Exchange

Ensure cluster-wide uniqueness and safe concurrency.

Compare-exchange is a RavenDB feature for storing atomic, cluster-wide key-value pairs where each key is a globally unique identifier in the database. Compare-exchange provides a built-in consensus mechanism ideal for safe coordination and global consistency in distributed environments, allowing you to:

  • Enforce global uniqueness (e.g., prevent duplicate usernames or emails).
  • Assign work to a single client or reserve a resource once.
  • Handle concurrency safely, without external services or custom locking logic.

Key Characteristics of a compare-exchange item:

  • Cluster-wide - Items are consistent across all nodes and managed at the cluster level.
  • Atomic - Only one client can successfully modify an item at a time, ensuring all-or-nothing updates.
  • Versioned - Each update increments the item's version, enabling safe conflict detection.
  • Flexible - Values can be simple types (strings, numbers, arrays) or complex JSON objects.
  • Internal - Handled within the cluster and not replicated to external databases.

Use cases

Implementing compare-exchange items provides a reliable, built-in consensus mechanism to address a wide variety of distributed challenges, such as -

  • Enforcing global uniqueness for user registrations, emails, or reference IDs.
  • Assigning jobs or tasks to ensure a single worker claims them exactly once.
  • Reserving limited resources like booking slots or event seats without race conditions.
  • Preventing duplicate processing to ensure an action only happens exactly once, even during retries.
  • Validating data state before executing critical, multi-step business logic.
  • Locking shared documents to prevent conflicting edits in collaborative applications.
  • Guaranteeing ACID compliance in multi-node transactions via automatic atomic guards.

Technical documentation

Refer to the technical documentation to learn how to create and manage compare-exchange items, index their values,
and understand how RavenDB automatically uses them as atomic guards to ensure cluster-wide consistency.

Create compare-exchange items

Learn how to create a compare-exchange item.

Indexing compare-exchange values

Learn how to index compare-exchange values in a static-index.

Learn more: In-depth articles

External

Complex distributed transactions with RavenDB

Execute complex distributed transactions in RavenDB by coordinating documents and compare-exchange values for strong consistency.

External

Simplifying atomic cluster wide transactions

How RavenDB 5.2 makes cluster-wide transactions simpler by auto-managing needed guards behind the scenes.

External

Create compare-exchange item Demo

Interactive demo showing how to create a compare‑exchange item.

External

Index compare-exchange item Demo

Interactive demo demonstrating indexing compare‑exchange items.

In this article