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.
Learn more: In-depth articles
Related blog posts

ExternalDistributed compare-exchange operations with RavenDB
How RavenDB uses compare-exchange to safely coordinate shared tasks across a distributed cluster.

ExternalCluster wide ACID transactions
Introducing RavenDB 4.1’s cluster-wide ACID transactions to ensure atomic, consistent changes across nodes.