Skip to content
Registry StackDocsDevelopment (unreleased)

Deploy Registry Messaging

View as Markdown

An author has handed you a Registry Messaging package and its digest, as Author a Messaging package produces. Here you serve it against PostgreSQL behind your TLS edge, then operate its messages and retention.

  • PostgreSQL 17 or newer over TLS: one database, a migration role, and a runtime role.
  • An OpenID Connect issuer that issues RFC 9068 access tokens to the clients the access profiles name. Messaging verifies tokens and issues none.
  • A TLS proxy in front of the listener, which serves plain HTTP on a private address.
  • A connection for each provider: an SMTP relay, and each HTTP provider’s base URL, credential, and callback secret.
  • Secret files the runtime user owns, and a directory for the audit journal.

Messaging needs no broker or cache, and connects to no database but its own.

Choose a tag, normally the latest release, download messaging-<tag>-linux-amd64 and messagingctl-<tag>-linux-amd64, and authenticate both with Verify a release. Install the pair from one tag:

Terminal window
tag="${TAG:?set TAG to the release you verified}"
mkdir -p ~/.local/bin
for binary in messaging messagingctl; do
install -m 0755 "${binary}-${tag}-linux-amd64" "$HOME/.local/bin/${binary}"
done
export PATH="$HOME/.local/bin:$PATH"
messaging --version
messagingctl --version

For another platform, build both from a checkout with cargo build --release --locked -p registry-messaging -p registry-messagingctl.

The image ghcr.io/registrystack/messaging:<tag> carries both binaries and runs messaging --runtime-config /etc/registry-messaging/runtime.yaml serve. Mount the package, runtime file, and secrets read-only, give the audit path writable storage, and deploy by digest.

Each release publishes the messaging and messagingctl binaries for Linux amd64 only, checked against the release SHA256SUMS, and the container image for linux/amd64 only. There is no Messaging installer and no Linux arm64 or macOS build of either binary. The unified clients carry a messaging namespace: @registrystack/client on npm (Linux x64 and arm64 with glibc, macOS arm64) and registry-stack-client on PyPI (manylinux x86_64 and aarch64, macOS arm64).

  • An SMTP relay is the built-in email transport.
  • Twilio SMS uses the form-sms-gateway provider example, with signed callbacks.
  • AWS End User Messaging SMS uses the aws-sms provider example, with SigV4-authenticated SendTextMessage; it records acceptance only and ingests no delivery events.
  • Other HTTP gateways use reviewed request and response scripts over configured HTTP connections.
  • Mailpit and a mock SMS gateway are local development transports.

The AWS example has offline and local wire-contract tests. Verifying actual carrier delivery needs a configured AWS account, an approved origination identity, and a real destination.

The 202 from POST /v1/messages means Registry Messaging admitted the message to its dispatch queue and nothing more: the message can still become failed, expired, cancelled, or unknown. submitted means the provider accepted the message, never that it was delivered. Neither acceptance nor submitted is proof of delivery to the recipient or of legal service.

Create the roles and the database, then hand the schema to the migration role:

CREATE ROLE messaging_migration LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE
NOINHERIT NOBYPASSRLS;
CREATE ROLE messaging_runtime LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE
NOINHERIT NOBYPASSRLS;
CREATE DATABASE messaging;

Set each role’s password with \password messaging_migration and \password messaging_runtime in psql, which prompts for it instead of taking it in a statement.

In the messaging database:

REVOKE ALL ON DATABASE messaging FROM PUBLIC;
GRANT CONNECT ON DATABASE messaging TO messaging_migration, messaging_runtime;
ALTER SCHEMA public OWNER TO messaging_migration;
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO messaging_runtime;
ALTER DEFAULT PRIVILEGES FOR ROLE messaging_migration IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO messaging_runtime;
ALTER DEFAULT PRIVILEGES FOR ROLE messaging_migration IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO messaging_runtime;

The package carries no runtime file. messagingctl init <directory> writes a starter project with runtime.example.yaml at its root; copy that file to /etc/registry-messaging/runtime.yaml and set it for this host.

Set package.root to the absolute path of the package directory. Optionally set package.expectedDigest to the digest the author reported, which pins the runtime to that package.

Set listener.bind to the private address your proxy reaches, and tlsTermination to operator-controlled-upstream: the example’s development-loopback is refused on any non-loopback bind, and a public unicast address is refused under every setting. Set authentication.oidc to your issuer and audience; allowedClients must list every client an access profile names.

Each provider the package declares gets a connection with the same id and type:

runtime.yaml
sms-gateway:
type: http
baseUrl: https://sms-gateway.example.org/v1/
attemptTimeoutMilliseconds: 5000
maximumResponseBytes: 65536
# At most the package's capabilities.maximumConcurrentRequests.
maximumConcurrentRequests: 4
redirects: deny
authentication:
type: static-authorization
tokenRef: secret:file/sms-gateway-token
# Required exactly when the package declares `receipts: callback`.
callbackVerifier:
type: hmac-sha256-body
header: x-signature
encoding: hex
secretRef: secret:file/sms-gateway-callback-key

Give the provider the callback URL /v1/provider-callbacks/sms-gateway on your public edge. A path-token verifier takes /v1/provider-callbacks/<id>/<token> instead, with the secret token as the last segment. A provider host on a private address is refused unless allowedPrivateCidrs names its network.

An hmac-sha1-url-form verifier takes url, the external callback URL exactly as the provider was given it, without a query. The runtime computes the signature over that configured URL and the query string it received, never over the path the request arrived on, so a proxy in front of the callback route may rewrite the path but must pass the query string through unchanged.

Under retention, the payload (rendered parts and recipient contact) is erased payloadRetentionDays after the message reaches a terminal state; the record, with its attempts and receipts, recordRetentionDays after it. receiptRetentionDays counts from acceptance and is the idempotency window: after it, an exact repeat is refused with 410 idempotency.expired. A different request under a used key is refused with 409 idempotency.key-reused at any age. A message that is queued, sending, or unknown is never erased. The example’s 7, 90, and 7 days are defaults, not a jurisdictional recommendation; the audit journal’s start record carries the values a runtime enforces.

Registry Messaging configuration lists every key with its default and bounds.

Create each file as the user that runs messaging, with no trailing newline. read -rs takes a value without echoing it or keeping it in shell history; paste postgresql://messaging_runtime:<password>@db.example.org:5432/messaging at its prompt:

Terminal window
install -d -m 0700 /run/secrets/registry-messaging
(umask 077; openssl rand -hex 32 | tr -d '\n' \
> /run/secrets/registry-messaging/messaging-audit-key)
read -rs value
(umask 077; printf '%s' "$value" > /run/secrets/registry-messaging/runtime-database-url)
unset value

Write smtp-username, smtp-password, sms-gateway-token, and sms-gateway-callback-key the same way. Each must be a regular file owned by the runtime user, mode 0400 or 0600, with one link.

serve never reads the migration credential; only apply and retention erase-expired connect with it. Write migration-database-url, the URL for messaging_migration, only on the host that runs those two commands.

check --runtime-config checks the file and the package at package.root offline:

Terminal window
messagingctl check --runtime-config /etc/registry-messaging/runtime.yaml
ok: /etc/registry-messaging/runtime.yaml
package digest: sha256:a77193bf48a8fdcc09a4576991fbd0441307cd23e34c550d27a740b66cd0dfce
listener: 10.42.0.7:8107
metrics listener: 10.42.0.7:9107
template: appointment-reminder 1 (email)
sample en: renders
sample fr: renders
template: appointment-reminder-sms 1 (sms)
sample en: 1 segment(s), gsm7 85 units
sample fr: 1 segment(s), gsm7 85 units
access profile: case-notices (sender)
access profile: operations (operator)
retention: payload 7 days, record 90 days, submission receipt 7 days
0 errors, 0 warnings in 20 files

The digest must be the one the author gave you. When package.expectedDigest names another package, check, plan, and apply refuse with error[messaging.package.digest-mismatch], and serve with messaging: package.expectedDigest does not pin the package at package.root, before reaching a database.

Review what activation would change. plan connects with the runtime credential and writes nothing:

Terminal window
messagingctl plan --runtime-config /etc/registry-messaging/runtime.yaml

Then record the package. apply reads the migration credential, the runtime credential (to name the role it grants access to), and the audit key, and journals the activation:

Terminal window
messagingctl apply --runtime-config /etc/registry-messaging/runtime.yaml

In one transaction, apply migrates the schema, binds the database to identity.databaseId, records the verified package as active, and grants the runtime role its access. Applying the active package again changes nothing and reports change: none. messagingctl status shows the active package and the activation history.

Start the runtime:

Terminal window
messaging --runtime-config /etc/registry-messaging/runtime.yaml serve

It logs JSON lines on standard error; MESSAGING_LOG selects error, warn, or info, and any other value exits 2. GET /health answers 200 while the process serves. GET /ready answers 200 once the database carries every migration, the ledger names this package active, and the audit writer is healthy, and 503 otherwise.

On SIGTERM the worker finishes the sends in flight and claims nothing more. Give it time, because a send cut short can leave its message unknown.

serve refuses a package other than the one the ledger names active. To roll out a new one, put the new package directory in place, update package.expectedDigest if you set it, then run plan, apply, and status, and restart.

Once apply records a new digest, a runtime restarting on the old directory refuses to start, and one still serving it answers /ready with 503. Record a package only when every host has the new directory, and restart them together.

After a change that narrows what a caller may send, an exact retry of a message the old package accepted can be refused with 403 or 422 while the first attempt is already sending, and a caller that resubmits under a new key sends twice. Stop the affected senders and let them finish their retries before you run apply.

Each replica’s worker runs eight send lanes, and each lane claims, sends, and records one message at a time. Per-replica throughput is therefore about 8 divided by the provider’s response time (a 200 ms provider caps one replica at 40 SMS per second); add replicas to go faster.

messages list prints the newest first, narrowed by --status and --limit, and show prints one message with each attempt. Neither shows a recipient:

Terminal window
messagingctl messages list --runtime-config /etc/registry-messaging/runtime.yaml
messagingctl messages show --runtime-config /etc/registry-messaging/runtime.yaml "$MESSAGE_ID"

Each action applies to one dispatch state, previews without --apply, and is journaled:

CommandDispatch stateEffect
messages retryfailedQueues the message again under a new generation
messages settle --outcome sentunknownMarks it submitted
messages settle --outcome not-sentunknownQueues it again under a new generation
messages cancelqueuedCancels it

An action on another state is refused with message.not-eligible.

When an applied operation does not finish, the code says whether anything changed. These apply to apply, the message actions, and retention erase-expired:

CodeExitMeaning
message.changed1The message changed between the read and the write. Nothing was applied; run messages show and decide again
audit.unavailable3apply or a message action found the audit destination refusing its request record. Nothing was changed; restore it and retry
audit.unconfirmed3The change was applied and its audit outcome record could not be written. Do not apply it again; restore the audit destination
message.outcome-unknown3The action may have been applied. Run messages show before acting again
package.outcome-unknown3The activation may have been recorded. Run messagingctl status before applying again
retention.outcome-unknown3The last batch may have been erased. Preview with the same --before to see what is still due
database.unavailable3The database could not be reached or refused the write

A command that finds the database not yet prepared for this package refuses with messagingctl.activation.not-activated, messagingctl.activation.package-not-active, or messagingctl.activation.grants-stale, each of which says to run plan, then apply with the migration credential.

A message is unknown when a send may have reached the provider and nobody can tell: the connection broke after the request left, the attempt timed out, or the answer could not be read. Under the default onUncertain: hold it waits for you. Ask the provider, by its console or logs at the attempt time messages show lists, whether it took the message, then settle sent or not-sent.

retention erase-expired runs the retention sweep from the operator host with the migration credential, counting every period back from --before. Preview first:

Terminal window
messagingctl retention erase-expired --runtime-config /etc/registry-messaging/runtime.yaml \
--before 2026-09-25T00:00:00Z
before: 2026-09-25T00:00:00.000Z
payloads due: 0
records due: 0
submission receipts due: 0
run again with --apply to erase
Terminal window
messagingctl retention erase-expired --runtime-config /etc/registry-messaging/runtime.yaml \
--before 2026-09-25T00:00:00Z --apply

Each batch commits and is journaled as messaging.retention.erased, so a run that fails partway keeps what it erased. A cutoff in the future is refused.

Each process writes a JSON Lines audit stream to audit.path, naming callers and recipients only by keyed pseudonyms. It is not signed; ship it to append-only storage if you need tamper evidence.

In file mode, every accepted write is fsynced; stdout mode is best-effort. The active file rotates at audit.rotateBytes, and sealed files older than audit.retentionDays are deleted. An applied messagingctl operation writes its records to a sibling file beside audit.path, named <stem>.messagingctl<ext> and rotated and retained the same way, or to standard error when the runtime audits to stdout, so command stdout stays free for JSON results. The operator who runs messagingctl therefore needs write access to the audit directory.

A writer that fails stays unhealthy until the process restarts, and /ready answers 503 until then. If the response record fails after a database commit, the effect still stands: inspect the operation’s stored result, or follow its retry contract in the code table above, and never assume a rollback. Expiry of local segments is not proof that they reached off-host storage; arrange shipping before retentionDays removes sealed segments.

EventRecorded when
messaging.runtime.startedThe runtime starts, with the package digest, runtime version, and retention in force
messaging.package.activation.finishedmessagingctl apply records, or refuses, a package
messaging.message.accepted, .refused, .replayedA submission is accepted, refused, or answered again from its idempotency key
messaging.attempt.started, messaging.attempt.finishedThe worker starts and finishes a send attempt
messaging.message.quarantinedA send may have happened and the message is held as unknown
messaging.dispatch.transitionThe dispatch state changes, naming the worker, a caller, or the operator tool
messaging.message.settledAn operator settles an unknown outcome
messaging.receipt.recordedA verified provider callback moves a delivery report
messaging.message.receipt-readA sender reads a retained submission receipt back by its idempotency key
messaging.retention.erasedA retention batch erases data
messaging.template.previewedA sender previews a template

The table lists outcome records. Each audited request writes a request record first: messaging.message.requested, messaging.message.settle.requested, messaging.receipt.requested, messaging.retention.requested, messaging.template.preview.requested, or messaging.package.activation.requested. An operation that stops before its outcome is written leaves a record with outcome unfinished, under its request event or messaging.operation.

With metricsListener set, GET /metrics on that socket answers Prometheus text. In a container whose private address is not known when you write the file, set metricsListener.networkExposure: container-private to bind 0.0.0.0: see Scrape metrics from a container.

The series are:

SeriesLabelsCounts
messaging_http_requests_totalroute, method, statusAnswered HTTP requests, by route template and status class
messaging_authentication_refusals_totalreason: refused, claims, profile, unavailableBearer credentials refused before a caller was resolved
messaging_provider_attempts_totaloutcome: accepted, transient, permanent, maybe-sentProvider attempts, by class
messaging_provider_callbacks_totaloutcome: unverified, unreadable, ignored, applied, unchanged, unmatched, ambiguous, unavailableProvider callbacks, by what became of them
messaging_limit_refusals_totallimit: rate, daily, pacing, callbackSubmissions, attempts, and callbacks a limit refused
messaging_retention_runs_totaloutcome: erased, idle, failedRetention sweeps this process ran
messaging_metrics_sample_failures_totalsample: dispatch-queueScrapes in which the database read failed, since the process started
messaging_dispatch_jobsstate: pending, leased, unknownGauge read from the database at each scrape

The database read runs in a read-only transaction inside a 5 second scrape deadline, and the server cancels a query that outlasts it. A failed read is logged with its error class (sqlstate-<code>, connection-closed, query, timeout, no-time-left or pool) and leaves the gauge without samples for that scrape.

Counters are per process and restart at zero. Watch messaging_dispatch_jobs{state="unknown"}, the messages waiting for you to settle, and messaging_provider_callbacks_total{outcome="unverified"}, which usually means the callback secret or URL differs between the provider and the runtime file. A messagingctl retention erase-expired run is a separate process: the journal records it, these counters do not.

Each of these is the whole standard-error output of serve, with nothing on standard output. The first exits 2 and the others exit 1:

OutputCause
messaging: MESSAGING_LOG must be one of error, warn, or infoMESSAGING_LOG holds another value
messaging: the Messaging package at package.root does not satisfy the shared package envelope: the package at <package.root> does not match its SHA256SUMS; changed: messaging.yaml; rebuild the package with `messagingctl package` and deploy the whole directoryA package file was changed in place. Deploy the directory messagingctl package wrote, unchanged. A missing directory is reported the same way, as does not exist or cannot be read
messaging: package.expectedDigest does not pin the package at package.root, whose digest is sha256:<digest>; deploy the pinned package or update package.expectedDigestThe package on disk is not the one package.expectedDigest names
messaging: the Messaging runtime database configuration failed: the Messaging database secret could not be resolved: the secret reference configured at database.runtimeUrlRef could not be resolved: no readable secret of that name exists under the configured providerNo file of that name exists under secretProviders.file.root, or the runtime user cannot read it
messaging: the Messaging runtime database configuration failed: the Messaging database secret could not be resolved: the secret reference configured at database.runtimeUrlRef could not be resolved: the secret file must be a regular file owned by the runtime user, with mode 0400 or 0600, and exactly one hard linkThe file exists but is a symbolic link, belongs to another user, has another mode, or has a second hard link
messaging: the Messaging database connection could not be established: Error occurred while creating a new object: error connecting to serverNothing answers at the URL’s host and port. error performing TLS handshake in its place means the server certificate is not trusted; name the CA bundle in database.caBundleRef
messaging: the Messaging query failed: db errorThe database has no schema yet. Run messagingctl plan, then apply, with the migration credential
messaging: identity.databaseId does not match the database activation ledgerThe runtime file names another deployment’s identity.databaseId, or its URL reaches another deployment’s database
messaging: the configured package is not active; run `messagingctl plan --runtime-config FILE` then `messagingctl apply --runtime-config FILE` package.root holds a package the ledger has not activated. Run plan, then apply, then start again
messaging: the OIDC issuer could not be initializedThe issuer’s discovery document could not be fetched, or a static jwksSource document holds no usable key