Skip to main content

Distributed Locks

Distributed locks are a mechanism used in distributed systems to ensure that only one node (or process, task, etc.) can execute a specific section of code or access a particular resource at a given time. This is crucial for preventing race conditions and ensuring data consistency across the system.

What is a Distributed lock?

A distributed lock is like a traditional lock used in single-process applications but is designed to work across multiple nodes/processes in a distributed system. It ensures that when one node acquires the lock, no other node can acquire the same lock until it is released.

Distributed locks in Cognibase

Cognibase offers a robust and user-friendly API for implementing distributed locks within your application, ensuring data consistency and preventing race conditions in a distributed environment.

StartCommonDataLock

  • Description: Attempts to acquire a distributed lock with a specified name.
  • Parameters:
    • string dataLockName: The unique name identifying the lock.
    • TimeSpan waitFor: The maximum time to wait for acquiring the lock.
  • Returns: bool indicating whether the lock was successfully acquired.
  • Usage:
  bool lockAcquired = _client.StartCommonDataLock("myLock", TimeSpan.FromSeconds(30));
if(lockAcquired)
{
// Lock acquired

try
{
// safe to proceed
}
finally
{
// always execute this in finally block
_client.EndCommonDataLock("singletonJobLock");
}
}
else
{
// Could not acquire lock
}

EndCommonDataLock

  • Description: Releases a previously acquired distributed lock.
  • Parameters:
    • string dataLockName: The unique name identifying the lock.
  • Usage:
_client.EndCommonDataLock("myLock");

Examples of Distributed Lock Usage

1. Data Write Operations

Imagine a scenario where multiple nodes are trying to write specific DataItem instances to Cognibase. Without a distributed lock, they might try to write the instances at the same time, leading to conflicts that needs to be managed or duplicate data. With a distributed lock, only one node can perform the write at a time, ensuring the written data are correct.

_client.StartCommonDataLock("myLock", TimeSpan.FromSeconds(30));
try
{
// Perform data write
// ...
}
finally
{
_client.EndCommonDataLock("myLock");
}

2. Singleton Job Execution

In a system where you have multiple instances of a service running, and you want to ensure that a specific job is only run by one instance at a time, you can use a distributed lock.

_client.StartCommonDataLock("myLock", TimeSpan.FromSeconds(30));
try
{
// Execute the job
// ...
}
finally
{
_client.EndCommonDataLock("myLock");
}