Skip to content

Advisory locks ​

IAdvisoryLock takes a PostgreSQL transaction-scoped advisory lock on a logical key, inside the transaction of the act.

When to use ​

Use it to serialize a short critical section across requests and instances: for example, two approvers deciding the same process at once. For long work, or work that outlives the transaction, it is the wrong tool.

Wiring ​

csharp
services.AddGrydAdvisoryLocks<AppDbContext>();

The registration is scoped and serves one context per host. Registering a second, different context throws InvalidOperationException; registering the same one again does nothing.

Keys ​

csharp
var key = AdvisoryLockKey.For("approval", tenantId, "process:42");
var platformKey = AdvisoryLockKey.ForPlatform("approval", "process:42");

namespace and name are not blank, have at most 200 characters and no line break; tenantId is not Guid.Empty. The 64-bit value is the first 8 bytes of the SHA-256 of "gryd-advisory-lock\n{namespace}\n{tenantId:N}\n{name}", read big-endian (platform replaces the tenant for ForPlatform).

Usage ​

csharp
await unitOfWork.ExecuteInTransactionAsync(async ct =>
{
    await advisoryLock.AcquireAsync(AdvisoryLockKey.For("approval", tenantId, $"process:{id}"), ct);
    // read, decide and write while no other transaction holds the same key
});

TryAcquireAsync returns false instead of waiting when another transaction holds the key.

Limits ​

  • PostgreSQL only; any other provider, or a call without an open transaction, throws InvalidOperationException.
  • The wait ends by the context CommandTimeout (Npgsql: 30 s by default), by lock_timeout (use SET LOCAL lock_timeout in the act for a smaller ceiling) or by the CancellationToken. In every case the transaction is aborted: roll it back.
  • With more than one key, take them in ascending order of Value; the reverse order between two acts deadlocks (40P01).
  • A discarded savepoint (INestedUnitOfWork) releases the lock.
  • Keep the section short: holding the lock in a long execution holds the connection and the transaction.

Released under the MIT License.