Reeve.EntityFrameworkCore.AdvisoryLocks
1.0.0
dotnet add package Reeve.EntityFrameworkCore.AdvisoryLocks --version 1.0.0
NuGet\Install-Package Reeve.EntityFrameworkCore.AdvisoryLocks -Version 1.0.0
<PackageReference Include="Reeve.EntityFrameworkCore.AdvisoryLocks" Version="1.0.0" />
<PackageVersion Include="Reeve.EntityFrameworkCore.AdvisoryLocks" Version="1.0.0" />
<PackageReference Include="Reeve.EntityFrameworkCore.AdvisoryLocks" />
paket add Reeve.EntityFrameworkCore.AdvisoryLocks --version 1.0.0
#r "nuget: Reeve.EntityFrameworkCore.AdvisoryLocks, 1.0.0"
#:package Reeve.EntityFrameworkCore.AdvisoryLocks@1.0.0
#addin nuget:?package=Reeve.EntityFrameworkCore.AdvisoryLocks&version=1.0.0
#tool nuget:?package=Reeve.EntityFrameworkCore.AdvisoryLocks&version=1.0.0
Reeve.EntityFrameworkCore.AdvisoryLocks
Typed PostgreSQL advisory locks for Entity Framework Core and Npgsql: the one place that spells pg_advisory_*, with typed keys.
- Transaction-scoped locks on the current transaction of an EF context (
DatabaseFacade) or of anNpgsqlTransaction: blocking,try, andtrywith a timeout, exclusive or shared. The transaction ends the lock; there is nothing to release. - A separate session lock type (
AdvisorySessionLock) for leader election and start-up steps, where a lock has to outlive a transaction. - A typed key (
AdvisoryLockKey) and a namespace registry (AdvisoryLockNamespace), so an application and the libraries it uses, sharing one database, cannot take each other's locks by accident.
dotnet add package Reeve.EntityFrameworkCore.AdvisoryLocks
It needs .NET 11 (net11.0), Npgsql and Microsoft.EntityFrameworkCore.Relational 11, and a PostgreSQL 11 or newer (hashtextextended); the tests run on PostgreSQL 18.
public sealed class OrderWorker(DbContext db)
{
private static readonly AdvisoryLockNamespace Orders = AdvisoryLockNamespace.Register("acme.orders", 2001);
public async Task ProcessAsync(long orderId, CancellationToken ct)
{
await using var transaction = await db.Database.BeginTransactionAsync(ct);
if (!await db.Database.TryAdvisoryXactLockAsync(AdvisoryLockKey.Of(Orders, orderId), TimeSpan.FromSeconds(2), cancellationToken: ct))
{
return; // another transaction is working on this order
}
// ... the order is ours until the transaction ends ...
await transaction.CommitAsync(ct);
}
}
Keys
PostgreSQL has one 64-bit advisory-lock space per database, plus a separate space for two-int4 keys. Every user of the database shares it.
public static class OrderKeys
{
// Registered once per process. The id is part of the lock identity: never change it.
private static readonly AdvisoryLockNamespace Orders = AdvisoryLockNamespace.Register("acme.orders", 2001);
// hashtextextended(name, 2001), computed by the server
public static AdvisoryLockKey ByNumber(string orderNumber) => AdvisoryLockKey.Of(Orders, orderNumber);
// (2001 << 48) | id; ids are 0 .. 2^48-1
public static AdvisoryLockKey ById(long id) => AdvisoryLockKey.Of(Orders, id);
}
Register is idempotent for the same name and id and throws for a name or an id that belongs to another registration. The registry is a static of
the package, so a clash surfaces at the first use of the type that registers (a static initialiser runs lazily), within one process and one
AssemblyLoadContext; register in an explicit start-up step if you want it to fail at start-up. Namespace id 0 is reserved: it is the seed of
FromHashedText. The application chooses its ids; a library that takes locks should expose its namespace name and id as an option.
Numeric keys of two namespaces are never equal, but a namespaced key can equal a FromRaw key whose top 16 bits are a registered namespace id, so
register the prefix of any raw keys you use. Name keys are 64-bit hashes: two different names collide with the probability of any 64-bit hash, and
a collision only makes two locks share, it never lets two holders in.
Keys fixed elsewhere
A key that has to match one fixed elsewhere (a literal, a hash the caller computes, a stored function, another language or an older release) renders exactly as given, so replicas of one deployment contend on the same lock whichever code they run:
| Factory | Renders | For a hand-written |
|---|---|---|
AdvisoryLockKey.FromRaw(long) |
pg_advisory_xact_lock(@key) |
bigint literal, constant or client-side hash |
AdvisoryLockKey.FromHashedText(string) |
hashtextextended(@text, 0) |
hashtextextended({0}, 0) |
AdvisoryLockKey.FromIntPair(int, int) |
pg_advisory_xact_lock(@first, @second) |
the two-int4 form |
Otherwise use Of. Seed 0 of FromHashedText is the reserved namespace 0, so the hashed and the namespaced text keys are the same function with
different seeds.
Transaction-scoped locks
await using var transaction = await db.Database.BeginTransactionAsync(ct);
await db.Database.AdvisoryXactLockAsync(key, cancellationToken: ct); // waits for a conflicting holder
if (!await db.Database.TryAdvisoryXactLockAsync(key, cancellationToken: ct)) { ... } // never waits
if (!await db.Database.TryAdvisoryXactLockAsync(key, TimeSpan.FromSeconds(2), cancellationToken: ct)) { ... }
await db.Database.AdvisoryXactLockAsync(key, AdvisoryLockMode.Shared, cancellationToken: ct); // shared locks admit each other
await transaction.CommitAsync(ct); // the locks end here
The same three methods extend NpgsqlTransaction. Without an active transaction they throw InvalidOperationException: a transaction lock taken
outside a transaction would last for one statement and protect nothing.
The timed form takes the lock inside a savepoint, with its own lock_timeout and statement_timeout = 0 set locally for the wait; it reads the
caller's two settings first and puts them back, on a won wait and on a lost one.
How a timed try ends
Every way the lock statement of TryAdvisoryXactLockAsync(key, timeout) can end has one outcome:
| The lock statement ends by | Outcome |
|---|---|
| the lock is acquired | true |
its own lock_timeout |
false; rolled back to the savepoint, the transaction usable |
the server's statement_timeout |
cannot end it: the wait suspends statement_timeout, and the try's own timeout bounds the wait |
| the client's command timeout | cannot end it first: the package sets it to the timeout plus a margin, above lock_timeout; a longer commandTimeout argument does not lower it |
a commandTimeout argument not longer than timeout |
ArgumentOutOfRangeException before anything runs; the call contradicts itself |
the CancellationToken |
OperationCanceledException; rolled back to the savepoint, the transaction usable |
| a deadlock or any other server error | the PostgresException rethrown; rolled back to the savepoint, the transaction usable (earlier locks of the transaction stay) |
a lost connection, or transaction_timeout (PostgreSQL 17 and newer, which ends the session) |
the exception rethrown; there is nothing to restore |
The waits that have no timeout of their own (AdvisoryXactLockAsync, AdvisorySessionLock.LockAsync) end by whatever ends any statement: the
command timeout, the server's statement_timeout, a cancellation, a deadlock. The transaction a wait ran in is then aborted.
Command timeouts
A lock statement waits inside one command, and the client's command timeout cuts that wait off:
| Call | Command timeout |
|---|---|
timed try (TryAdvisoryXactLockAsync(key, timeout)) |
timeout plus a margin, or the commandTimeout argument when that is longer (it must be longer than timeout; infinite means none): always above lock_timeout, so the server answers first |
a try that does not wait (TryAdvisoryXactLockAsync(key), a timed try with a zero timeout) |
the ambient value (a timed try with zero timeout also takes commandTimeout) |
AdvisorySessionLock.TryLockAsync, UnlockAsync |
the commandTimeout argument, else the ambient value |
a wait (AdvisoryXactLockAsync, AdvisorySessionLock.LockAsync) |
the commandTimeout argument, else the ambient value |
commandTimeout is an optional TimeSpan? of the overloads that take it: null keeps the ambient value (the context's or the connection's
Command Timeout; for a timed try, the package's own), Timeout.InfiniteTimeSpan removes the limit, and any other value must be positive.
Session locks
await using var connection = new NpgsqlConnection(unpooledConnectionString);
await connection.OpenAsync(ct);
if (await AdvisorySessionLock.TryLockAsync(connection, key, cancellationToken: ct))
{
// ... start-up step ...
await AdvisorySessionLock.UnlockAsync(connection, key, cancellationToken: ct);
}
A session lock belongs to a connection, not to a transaction, and survives a rollback. It ends at UnlockAsync or when the server drops the session.
Taken twice, it needs two unlocks. IsHeldAsync asks the server whether this session holds the key.
Keep these for the places that have to hold a lock across transactions. Anything that fits in a transaction should use the transaction forms: a
pooled connection that goes back to the pool, a multiplexed connection or a transaction-pooling proxy hands the next statement to another session,
which silently loses the lock. Closing a pooled connection returns it to the pool and does not end the session, so its locks stay held: use an
unpooled connection. After a lock call that was cancelled or failed the hold is unknown; close the connection. The DatabaseFacade overloads
require the context's connection to be open already (Database.OpenConnectionAsync), because EF closes a connection it opened itself after each operation.
Tracing
The package has a standard System.Diagnostics.ActivitySource, named like the assembly (AdvisoryLockTelemetry.ActivitySourceName,
Reeve.EntityFrameworkCore.AdvisoryLocks), whose version is the package version. It makes one activity, advisory_lock.acquire, per
acquisition attempt, on every path: transaction waits, tries and timed tries, session waits and tries, exclusive and shared, EF and Npgsql. A timed
try is one activity however many statements it runs. The activity starts before the lock statement is sent, with the key, mode, scope and
timeout already set, so a listener sees which lock is about to be asked for (Npgsql's own span has no statement text or parameters at that point)
and can hold the call in ActivityStarted until it lets the statement go.
A release is not an acquisition: AdvisorySessionLock.UnlockAsync and IsHeldAsync take nothing and wait for nothing, and emit no activity.
A call refused before it runs (an argument out of range, no transaction, a closed connection) emits none either. Nobody listening costs one
check: no activity and no tags are made.
| Tag | Type | When | Value |
|---|---|---|---|
advisory_lock.key.form |
string | start | raw, namespaced_id, hashed_text, namespaced_text, int_pair (the factory that made the key) |
advisory_lock.key.namespace |
string | start, namespaced forms | the registered namespace name |
advisory_lock.key.namespace_id |
int | start, namespaced forms | the registered namespace id |
advisory_lock.key.id |
long | start, raw and namespaced_id |
the bigint of raw; the id within the namespace of namespaced_id |
advisory_lock.key.text |
string | start, text forms | the text that is hashed |
advisory_lock.key.first, advisory_lock.key.second |
int | start, int_pair |
the two int4 |
advisory_lock.mode |
string | start | exclusive, shared |
advisory_lock.scope |
string | start | transaction, session |
advisory_lock.try |
bool | start | true for every try form, a timed try and one with a zero timeout included |
advisory_lock.timeout_ms |
long | start, timed tries only | the wait, in milliseconds (0 for a zero timeout); absent otherwise |
advisory_lock.outcome |
string | stop | see below |
error.type |
string | stop, on timed_out and error |
the exception type |
The key tags carry the key's text and ids as given: leave the source unsubscribed, or drop the tags, where a name is confidential.
| Outcome | The attempt ended by | Activity status |
|---|---|---|
acquired |
the lock taken (a try answered true) |
unset |
refused |
a try answered false: held right now, or still held when a timed try's lock_timeout ran out |
unset |
timed_out |
a timeout threw: a wait cut off by the caller's lock_timeout or statement_timeout (SQLSTATE 55P03 or 57014) or by the client's command timeout; 57014 also covers a cancel request from another session (pg_cancel_backend), which cannot be told apart |
error |
cancelled |
the CancellationToken |
unset |
error |
any other exception, a deadlock and a lost connection included | error |
using var listener = new ActivityListener
{
ShouldListenTo = source => source.Name == AdvisoryLockTelemetry.ActivitySourceName,
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded,
ActivityStarted = activity => Console.WriteLine($"asking for {activity.GetTagItem("advisory_lock.key.form")} ({activity.GetTagItem("advisory_lock.mode")})"),
ActivityStopped = activity => Console.WriteLine($"{activity.GetTagItem("advisory_lock.outcome")} after {activity.Duration}"),
};
ActivitySource.AddActivityListener(listener);
With OpenTelemetry, tracing.AddSource(AdvisoryLockTelemetry.ActivitySourceName).
Building and testing
dotnet build Reeve.AdvisoryLocks.slnx
dotnet test tests/Reeve.EntityFrameworkCore.AdvisoryLocks.Tests # no database
dotnet test tests/Reeve.EntityFrameworkCore.AdvisoryLocks.IntegrationTests # needs Docker: a PostgreSQL 18 over Testcontainers
python3 tools/source-rules.py # repository rules; --self-test plants a violation of each
CI runs both test projects on every pull request and every push to main.
Documentation
- Architecture: the rules the library relies on and keeps.
- Using it in an application: namespaces, timeouts, connections, tracing, upgrading.
- FAQ: aborted transactions, lost connections, timeouts.
- Contributing and the changelog.
Licence
MIT, see LICENSE.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.EntityFrameworkCore.Relational (>= 11.0.0)
- Npgsql (>= 11.0.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Reeve.EntityFrameworkCore.AdvisoryLocks:
| Package | Downloads |
|---|---|
|
Reeve.Workloads.EntityFrameworkCore.PostgreSql
PostgreSQL support for Reeve.Workloads: the library's own migrations, the persistence conventions — jsonb for the JSON columns and the active-row filters on the partial unique indexes — and an advisory-lock leader election for the workload engine. The migrations and the conventions need no wiring at all; AddEntityFrameworkStores finds them both when the context runs on Npgsql, and a host writes none of its own. The election is one call, AddPostgreSqlLeaderElection(), because a registration runs before any context can report a provider. |
|
|
ReeveWorkflow.Npgsql
The PostgreSQL half of a workflow cluster: the one-permit run lock over advisory locks, and the leader gate derived from it. One session per process, no schema, no migration. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0 | 63 | 11/25/2026 |