API reference — Coordination
Nuvora.Nexus.Relay.Coordination.ValKey
ValKey-backed distributed coordination for Nuvora Nexus Relay: distributed locks, fenced leases, node registry and wake bridge (works with any Redis-compatible server)
dotnet add package Nuvora.Nexus.Relay.Coordination.ValKey
Nuvora.Nexus.Relay.Coordination.ValKey
ValKeyCoordinationConnection
public sealed class ValKeyCoordinationConnection : IAsyncDisposable
Owns the one multiplexed ValKey connection shared by the coordination primitives (StackExchange.Redis is designed around a single shared multiplexer per endpoint). Connects lazily on first use with abortConnect=false, so a ValKey outage at startup surfaces as failed acquisitions (which electors and lock consumers already treat as “not acquired, retry”) rather than failing host startup.
Constructors
ValKeyCoordinationConnection(IOptions<ValKeyCoordinationOptions> options)
Methods
ValueTask DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
ValueTask<IConnectionMultiplexer> GetConnectionAsync(CancellationToken cancellationToken = default(CancellationToken))
ValueTask<IDatabase> GetDatabaseAsync(CancellationToken cancellationToken = default(CancellationToken))
The default database of the shared connection, connecting on first call.
ValKeyCoordinationOptions
public sealed class ValKeyCoordinationOptions
Options for the ValKey-backed coordination primitives (distributed lock, lease store, node registry, wake bridge). One shared connection serves all of them.
Properties
TimeSpan LockRetryInterval { get; set; }
Polling interval while a blocking lock acquisition waits for the holder to release.
TimeSpan LockTtl { get; set; }
Time-to-live a held distributed lock is granted per renewal. Unlike a PostgreSQL advisory lock (released by the server when the holder’s connection drops), a ValKey lock key must expire for a crashed holder’s lock to free up; live holders renew at a third of this interval, so the TTL only bounds how long a crash blocks other acquirers.
string ConnectionString { get; set; }
StackExchange.Redis connection string (e.g. localhost:6379).
string KeyPrefix { get; set; }
Key prefix namespacing all coordination keys per service/environment.
ValKeyDistributedLock
public sealed class ValKeyDistributedLock : IDistributedLock, IAsyncDisposable
IDistributedLock backed by ValKey (SET NX PX with an owner token, released by a compare-and-delete script). Register it scoped.
Session-scoped locks (ValKeyDistributedLock.TryAcquireAsync) are held until the returned handle is disposed. A background renewal extends the key TTL at a third of ValKeyCoordinationOptions.LockTtl, so the TTL only bounds how long a crashed holder blocks other acquirers — the ValKey analogue of a dropped connection releasing a PostgreSQL advisory lock. If a ValKey outage outlives the TTL the key can expire while the holder still runs (the same window a PostgreSQL session lock has when its connection drops); the loss is logged, but a handle cannot revoke work already in flight — writes that must survive that window should carry a fencing token from the lease store rather than rely on the lock alone.
Transaction-scoped locks are approximated as scope-bound locks: ValKey has no view of the host’s database transaction, so the lock is instead released when the DI scope that acquired it is disposed — which the Relay command pipeline does after the unit of work commits or rolls back. Mutual exclusion therefore covers the whole transaction (release is never early, only slightly late), and a crashed holder is covered by the TTL. Re-acquiring a held resource in the same scope is reentrant, matching PostgreSQL advisory-lock semantics.
Constructors
ValKeyDistributedLock(IOptions<ValKeyCoordinationOptions> options, ValKeyCoordinationConnection connection, ILogger<ValKeyDistributedLock> logger)
Methods
Task AcquireForCurrentTransactionAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))
Blocks until the transaction-scoped lock is acquired.
Task<IDistributedLockHandle?> TryAcquireAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))
Tries to take the session-scoped lock without waiting. Returns a handle to hold (and dispose to release), or null if another holder owns it.
Task<bool> TryAcquireForCurrentTransactionAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))
Tries to take the transaction-scoped lock without waiting; false if held elsewhere.
ValueTask DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
ValKeyLeaseStore
public sealed class ValKeyLeaseStore : ILeaseStore
ValKey-backed ILeaseStore. Each lease is a persistent hash ({prefix}lease:{role} with owner/token/expiresAt fields) mutated by one atomic Lua script, which serializes concurrent acquirers exactly like the PostgreSQL implementation’s advisory lock + row update — same acquire/renew/takeover rules, same monotonic fencing tokens.
The key deliberately has no ValKey TTL: expiry is a stored timestamp compared inside the script. Letting the key itself expire would erase the fencing token and restart it at 1, breaking the monotonicity fencing depends on. Time comes from the server clock (TIME inside the script), so leases are immune to clock skew between competing client nodes; the returned LeaseResult.ExpiresAt is the server-computed deadline.
Constructors
ValKeyLeaseStore(IOptions<ValKeyCoordinationOptions> options, ValKeyCoordinationConnection connection)
Methods
Task ReleaseAsync(string role, string ownerId, CancellationToken cancellationToken = default(CancellationToken))
Releases the lease if ownerId holds it (best-effort; expiry covers crashes).
Task<LeaseResult> TryAcquireOrRenewAsync(string role, string ownerId, TimeSpan ttl, CancellationToken cancellationToken = default(CancellationToken))
Acquires the lease for ownerId if it is free or expired, or renews it if ownerId already holds it. Returns LeaseResult.NotAcquired if a different, non-expired owner holds it.
ValKeyNodeRegistry
public sealed class ValKeyNodeRegistry : INodeRegistry
ValKey-backed INodeRegistry. Heartbeats land in one sorted set ({prefix}nodes) scored by the server-clock last-seen time, so node liveness is immune to clock skew between the nodes themselves; a node is live while its last heartbeat is within the liveness TTL. Long-dead entries are pruned opportunistically on each heartbeat.
Constructors
ValKeyNodeRegistry(IOptions<ValKeyCoordinationOptions> options, ValKeyCoordinationConnection connection, TimeSpan livenessTtl)
Methods
Task HeartbeatAsync(string nodeId, CancellationToken cancellationToken = default(CancellationToken))
Records that nodeId is alive as of now.
Task RemoveAsync(string nodeId, CancellationToken cancellationToken = default(CancellationToken))
Removes nodeId from the registry (e.g. on graceful shutdown).
Task<IReadOnlyList<string>> GetLiveNodesAsync(CancellationToken cancellationToken = default(CancellationToken))
Returns the node ids whose most recent heartbeat is within the liveness window.
ValKeyWakeHub
public sealed class ValKeyWakeHub : IRelayWakeHub
IRelayWakeHub that fans local wakes out to every instance via ValKey pub/sub — the ValKey analogue of PostgreSQL’s NOTIFY. A local ValKeyWakeHub.Wake releases this process’s waiters immediately and publishes (fire-and-forget) on {prefix}wake:{channel}; the companion ValKeyWakeListener delivers remote publishes back into the local hub. Like the PostgreSQL wakes, this is strictly an optimization: pub/sub is lossy across reconnects, so pollers keep their polling interval as the safety net.
Constructors
ValKeyWakeHub(IOptions<ValKeyCoordinationOptions> options, ValKeyCoordinationConnection connection, ILogger<ValKeyWakeHub> logger)
Methods
IDisposable RegisterListener(string channel)
Registers a live listener for the channel; dispose the handle when the listener stops.
Task<bool> WaitAsync(string channel, TimeSpan maxWait, CancellationToken cancellationToken = default(CancellationToken))
Waits until the channel is signaled or maxWait elapses, whichever comes first. Returns true when woken by a signal, false on timeout.
bool HasListener(string channel)
Whether an external notification listener is currently feeding this channel. Pollers use this to relax their fallback interval when wakes are available and keep the tight interval when polling is the only signal.
void Wake(string channel)
Signals the channel, releasing all current waiters (no-op when none are waiting).
ValKeyWakeListener
public sealed class ValKeyWakeListener : BackgroundService
Hosted service that subscribes to the ValKey wake pattern ({prefix}wake:*) and forwards each publish to the local ValKeyWakeHub, so the outbox processor, scheduler and projection host wake within milliseconds of activity on any instance instead of waiting out a polling interval. StackExchange.Redis restores the subscription automatically after a reconnect; the listener registrations advertise wake availability so pollers relax their interval.
Constructors
ValKeyWakeListener(IRelayWakeHub hub, IOptions<ValKeyCoordinationOptions> options, ValKeyCoordinationConnection connection, ILogger<ValKeyWakeListener> logger)
Methods
override Task ExecuteAsync(CancellationToken stoppingToken)
Subscribes to the ValKey wake pattern for the lifetime of the host and forwards each remote publish into the local hub, restoring the subscription automatically across reconnects.
Nuvora.Nexus.Relay.Coordination.ValKey.DependencyInjection
ValKeyCoordinationServiceCollectionExtensions
public static class ValKeyCoordinationServiceCollectionExtensions
Registration helpers for the ValKey coordination primitives. Call ValKeyCoordinationServiceCollectionExtensions.AddRelayValKeyCoordination once, then add the primitives the host needs; the storage-agnostic electors (DistributedLockLeaderElector, LeaseLeaderElector) work on top of these unchanged.
Methods
static IServiceCollection AddRelayDistributedLockValKey(this IServiceCollection services)
Registers ValKeyDistributedLock as the scoped IDistributedLock. Session-scoped locks behave as on PostgreSQL (TTL + renewal instead of a held connection); transaction-scoped locks are scope-bound — released when the command scope is disposed, i.e. after the unit of work commits or rolls back.
static IServiceCollection AddRelayLeaseStoreValKey(this IServiceCollection services)
Registers the ValKey-backed ILeaseStore (renewable, fenced leases on the server clock). Used for leader-lease renewal with proactive failover and fencing tokens — e.g. with LeaseLeaderElector.
static IServiceCollection AddRelayNodeRegistryValKey(this IServiceCollection services, TimeSpan livenessTtl)
Registers the ValKey-backed INodeRegistry (heartbeat membership on the server clock). A node is live while its last heartbeat is within livenessTtl.
static IServiceCollection AddRelayValKeyCoordination(this IServiceCollection services, Action<ValKeyCoordinationOptions> configure)
Registers the shared ValKey coordination connection and options. The container owns the connection and disposes it on shutdown.
static IServiceCollection AddRelayValKeyWakeBridge(this IServiceCollection services)
Replaces the in-process IRelayWakeHub with the ValKey pub/sub bridge, so wakes fan out across every instance (the ValKey analogue of PostgreSQL LISTEN/NOTIFY). Order-independent with AddRelayEventStoreEfCore’s own hub registration.