Supervised machine ID lease management for NoNoncense.
Every node generating nonces needs a unique machine ID (0–511). NoNoncense.MachineId
acquires and holds that ID through a pluggable strategy, automatically renewing it in the
background. Configured NoNoncense factories are enabled when a lease is accepted and disabled
when it is lost.
Usage
Add it to your supervision tree in the appropriate place (in this case, after your Repo):
children = [
...
MyApp.Repo,
{NoNoncense.MachineId,
strategy: NoNoncense.MachineId.Strategy.SqlLease,
strategy_opts: [repo: MyApp.Repo],
instances: [[base_key: System.fetch_env!("BASE_KEY")]]}
]Strategies
| Strategy | Infrastructure | Notes |
|---|---|---|
HostIdentifiers | None | Derives IDs from node names/IPs; requires identical config on all nodes; no coordination |
EnvironmentVariable | Kubernetes StatefulSet | Reads pod ordinal env var; no coordination |
SqlLease | PostgreSQL or MySQL | Dynamically coordinates across nodes; requires a migration (see module doc) |
RedisLease | Redis 8+ / Valkey 9+ | Dynamically coordinates across nodes; requires HSETEX support |
Conflict Guard
A NoNoncense.MachineId.ConflictGuard is started by default. Set
enable_conflict_guard?: false to disable it. The guard uses Erlang node networking to detect
machine ID conflicts when nodes connect. It works with every strategy but is most useful with
static strategies that have no central lease coordinator. On a conflict, the newer node loses its
lease, which disables its factories and triggers :on_lease_lost. It requires distributed Erlang;
without connected nodes, it has no peers to compare.
Options
:name- registered name of this supervisor (defaultNoNoncense.MachineId):instances(required) - list of per-instance option keywords, each accepting the same options asNoNoncense.init/1(:base_key,:epoch, etc.). Note that names must be unique for each factory, the default name isNoNoncense.:enable_conflict_guard?- whether to start aNoNoncense.MachineId.ConflictGuardas a supervised child (defaulttrue):strategy(required) - a module implementing theNoNoncense.MachineId.Strategybehaviour:strategy_opts- passed as-is to the strategy's callbacks (default[]):lease_duration- the duration, in ms, to request from the strategy on everyacquire/renewcall (the strategy may grant a different actual duration; default 8 hours):renew_interval- how often to renew, in ms; should be comfortably shorter than the lease's actual TTL to allow for retries (default 30 minutes):acquire_timeout- max total time, in ms, to keep retrying acquisition at boot before giving up and failingstart_link/1(default60_000; pass:infinityto retry forever):callback_timeout- maximum time, in ms, to wait for an acquire, renew, or release callback (default5_000):on_lease_lost- called with the reason for the lease loss, after every configured factory has been disabled to preserve uniqueness guarantees. Can be used to halt the entire node, for example. Notifications are best-effort if the lease manager is unavailable.
Lease duration and renew interval
The defaults leave a wide recovery window for a temporary connection loss to your coordinator (e.g. your database), while still renewing well ahead of the lease's expiration. If you override these, keep that balance intact - most practical uses of nonce generation, such as ID generation, will grind to a halt if generation stops, so favor conservative, generous durations over aggressive, short ones. Machine IDs are meant to stay static for the lifetime of the node, so there's little to be gained from renewing more aggressively.
Lease lifecycle
Two supervised processes share the work. The lease manager talks to the strategy to acquire, renew, and release leases. The lease store holds the current lease and enforces its local expiry, so it keeps working even when a strategy callback blocks or the manager restarts.
Startup blocks until a lease is acquired or :acquire_timeout is reached. Acquisition failures
are retried with backoff; a strategy granting an invalid machine ID or a TTL below 30 seconds
fails startup immediately.
Factories are enabled only after a lease is accepted.
The strategy may grant a TTL different from the requested :lease_duration. Local expiry is
calculated from the start of the acquire or renew call, using the granted TTL less a 10-second
safety margin. Renewal is scheduled one safety margin before the earlier of the configured
:renew_interval and local expiry, or immediately if that time has already passed. A lease is
rejected if its TTL is below 30 seconds or the call has exhausted its local validity window;
release is attempted on a best-effort basis.
Acquisition, renewal, and release run in isolated tasks bounded by :callback_timeout. During
startup, the remaining :acquire_timeout also bounds these calls. A timed-out call may still
have taken effect in the coordinator; see NoNoncense.MachineId.Strategy for the resulting
requirements on strategy implementations.
Lease loss and recovery
A transient or ambiguous renewal failure is retried with backoff while the lease remains locally
valid. A confirmed loss or local expiry disables the factories and triggers :on_lease_lost with
the reason. Expiry is enforced independently of strategy callbacks, although timer latency can
delay factory shutdown briefly after the local deadline. Notifications are best-effort if the
lease manager is unavailable.
Coordinating strategies retry acquisition after a loss; deterministic strategies do not, since
they would return the same ID. A successful reacquisition reinitializes the factories. The
:on_lease_lost callback can notify, halt the node, or take another application-specific action;
it runs in the lease manager, so a blocking callback delays recovery.
A lease can survive a lease manager crash and be renewed on restart. On graceful shutdown, factories are disabled and release of any still-valid lease is attempted on a best-effort basis.
Summary
Functions
Starts the machine ID supervisor, blocking until the initial lease is acquired.
Types
@type lease_opt() :: {:strategy, module()} | {:strategy_opts, keyword()} | {:lease_duration, pos_integer()} | {:renew_interval, pos_integer()} | {:acquire_timeout, pos_integer() | :infinity} | {:callback_timeout, pos_integer()} | {:on_lease_lost, (term() -> any())}
@type opt() :: lease_opt() | {:name, module()} | {:instances, [NoNoncense.init_opt()]} | {:enable_conflict_guard?, boolean()}
Functions
@spec start_link([opt()]) :: Supervisor.on_start()
Starts the machine ID supervisor, blocking until the initial lease is acquired.
Options
:name- registered name of this supervisor (defaultNoNoncense.MachineId):instances(required) - list of per-instance option keywords, each accepting the same options asNoNoncense.init/1(:base_key,:epoch, etc.). Note that names must be unique for each factory, the default name isNoNoncense.:enable_conflict_guard?- whether to start aNoNoncense.MachineId.ConflictGuardas a supervised child (defaulttrue):strategy(required) - a module implementing theNoNoncense.MachineId.Strategybehaviour:strategy_opts- passed as-is to the strategy's callbacks (default[]):lease_duration- the duration, in ms, to request from the strategy on everyacquire/renewcall (the strategy may grant a different actual duration; default 8 hours):renew_interval- how often to renew, in ms; should be comfortably shorter than the lease's actual TTL to allow for retries (default 30 minutes):acquire_timeout- max total time, in ms, to keep retrying acquisition at boot before giving up and failingstart_link/1(default60_000; pass:infinityto retry forever):callback_timeout- maximum time, in ms, to wait for an acquire, renew, or release callback (default5_000):on_lease_lost- called with the reason for the lease loss, after every configured factory has been disabled to preserve uniqueness guarantees. Can be used to halt the entire node, for example. Notifications are best-effort if the lease manager is unavailable.
Lease duration and renew interval
The defaults leave a wide recovery window for a temporary connection loss to your coordinator (e.g. your database), while still renewing well ahead of the lease's expiration. If you override these, keep that balance intact - most practical uses of nonce generation, such as ID generation, will grind to a halt if generation stops, so favor conservative, generous durations over aggressive, short ones. Machine IDs are meant to stay static for the lifetime of the node, so there's little to be gained from renewing more aggressively.