Push notifications

Configure and operate Sockudo's core push notification platform for FCM, APNs, Web Push, HMS, and WNS.

20 min read
View .mdEdit on GitHub

Sockudo ships a durable push notification pipeline next to its realtime server. WebSockets reach clients that are connected right now; push notifications reach devices that are offline, backgrounded, suspended by the OS, or outside the active channel session. Use this page when you need to register devices, target them by channel, user, or device, and deliver through FCM, APNs, Web Push, HMS, or WNS with idempotency, retries, and observable status.

For ActivityKit start, update, end, push-token rotation, and iOS 18 broadcast channels, see Apple Live Activities. For metrics, alerts, and outage runbooks, see Push operations.

Device or browserYour backendSockudo push APIApplication eventPush queueFCMAPNsWeb PushHMSWNSDevice receives push provider tokenregister devicesubscribe to channelpublish or rule
flowchart TB
  D[Device or browser] -->|provider token| B[Your backend]
  B -->|register device| S[Sockudo push API]
  B -->|subscribe to channel| S
  A[Application event] -->|publish or rule| S
  S --> Q[(Push queue)]
  Q --> F[FCM] & AP[APNs] & W[Web Push] & H[HMS] & N[WNS]
  F & AP & W & H & N --> R[Device receives push]

How push works

Every notification moves through the same five stages. Each stage has its own API surface and its own failure modes, so it helps to keep them separate in your head.

StageWhat happensWhere it lives
1. RegistrationYour backend stores a device: a stable id, an optional clientId, and the provider recipient (FCM registration token, APNs device token, Web Push subscription, HMS token, or WNS channel URI).POST /apps/{appId}/push/deviceRegistrations
2. SubscriptionA device is mapped to a realtime channel so channel-targeted publishes can find it.POST /apps/{appId}/push/channelSubscriptions
3. PublishYou submit a publish: one or more targets plus a payload. Sockudo validates, renders provider payloads, persists the work durably, and returns 202 with a publishId.POST /apps/{appId}/push/publish
4. Provider deliveryPlanner, shard, and provider workers resolve targets to devices and send to FCM, APNs, Web Push, HMS, or WNS.Push queue stages (push.publish.v1, push.shards.v1, push.delivery.<provider>.v1)
5. Status and feedbackFeedback workers record each provider outcome, schedule retries, dead-letter exhausted work, and invalidate dead tokens.GET /apps/{appId}/push/publish/{publishId}/status

The key mental model: a 202 means “durably accepted”, not “delivered”. Delivery is asynchronous, and the publish status record is the source of truth for what happened next.

Concepts

ConceptMeaning
Device registrationA device record tied to one provider recipient and an optional clientId. Responses expose only a tokenHash, never the raw token.
Device identity tokenA per-device secret issued on admin registration. It lets a device-scoped caller update its own registration and subscriptions.
Channel subscriptionA mapping between a device and a realtime channel for push targeting.
CredentialProvider configuration for FCM, APNs, Web Push, HMS, or WNS.
PublishA push request accepted by Sockudo and fanned out asynchronously.
Publish statusThe operational record for accepted, scheduled, dispatched, failed, or cancelled push work.
TemplateA stored, localized notification body that a publish references by templateId.

Provider support

ProviderPlatformsCargo featureRecipient (transportType)Notes
FCMAndroid, web, cross-platform app backendspush-fcmgcm with registrationTokenBest default for Android and Firebase-backed apps.
APNsiOS, iPadOS, macOS, watchOS, tvOS, visionOSpush-apnsapns with deviceTokenUse sandbox for development tokens and production for App Store/TestFlight tokens.
Web PushBrowsers and installed PWAspush-webpushweb with endpoint, p256dh, authEndpoints must be public HTTPS URLs; payload size and browser support vary.
HMSHuawei devicespush-hmshms with registrationTokenUse when shipping to Huawei Mobile Services environments.
WNSWindows appspush-wnswns with channelUriUse for Windows notification channels.

Sockudo normalizes admission, idempotency, queueing, retries, status retention, and feedback. Provider-specific limits still apply after the request leaves Sockudo.

Set up the server

  1. Build Sockudo with the push features you need. monolith runs the planner, dispatcher, provider, feedback, retry, repair, and cleanup workers inside the server process. The full feature set includes every push provider.

    Terminal window
    cargo build -p sockudo --release --features "push-fcm,push-apns,push-webpush,monolith"
  2. Choose durable storage and a durable queue. storage_driver accepts memory, postgres, mysql, dynamodb, surrealdb, or scylladb. queue_driver is memory or a broker driver. A broker queue_driver runs on the shared [queue] backend and must match queue.driver. Push needs per-message delays, so it starts only on redis, redis-cluster, standard sqs and pulsar; see push queue backends.

  3. Enable each provider and configure its credentials (see Provider credentials).

    config.toml
    [push]
    storage_driver = "postgres"
    queue_driver = "redis"
    allow_memory_drivers = false
    fcm_enabled = true
    apns_enabled = true
    webpush_enabled = true
    publish_status_ttl_days = 30
    analytics_retention_days = 30
    scheduler_interval_secs = 5
    cleanup_interval_secs = 300
    cleanup_batch_size = 1000
    cleanup_max_deleted_per_tick = 100000
    [push.apns]
    # Required whenever apns_enabled = true.
    topic = "com.example.app"
  4. Start the server and confirm each provider worker reports ready in the logs. A provider whose credentials are missing logs a warning and does not start its dispatch worker.

APNs connection pooling, Live Activity topics, broadcast and channel-management endpoints, and timeouts are configured under [push.apns]. Retry policy lives under [push.retry], the provider circuit breaker under [push.circuit_breaker], per-app defaults under [push.default_quotas], and log redaction under [push.payload_redaction]. See the configuration reference for every key.

Provider credentials

Provider workers in a monolith process load credentials at boot, from environment variables or from a credential stored through the push API. Most provider credential variables also accept an unprefixed alias, for example FCM_PROJECT_ID, APNS_TEAM_ID, or VAPID_PRIVATE_KEY.

ProviderEnvironment credentialsStored credential
FCMPUSH_FCM_SERVICE_ACCOUNT_JSON_PATH or PUSH_FCM_SERVICE_ACCOUNT_JSON. PUSH_FCM_PROJECT_ID is optional when the service account JSON contains project_id. PUSH_FCM_PROVIDER_TOKEN (with PUSH_FCM_PROJECT_ID) remains only for short-lived legacy static-token dispatch.Upload to push/credentials/fcm and set PUSH_FCM_APP_ID (and optionally PUSH_FCM_CREDENTIAL_ID, default fcm).
APNsPUSH_APNS_TEAM_ID, PUSH_APNS_KEY_ID, and PUSH_APNS_PRIVATE_KEY_PATH or PUSH_APNS_PRIVATE_KEY for token auth; or PUSH_APNS_PROVIDER_TOKEN. Topic from [push.apns].topic or PUSH_APNS_TOPIC.Upload to push/credentials/apns and set PUSH_APNS_APP_ID (and optionally PUSH_APNS_CREDENTIAL_ID, default apns). Stored material can be p12, pem, or teamId + keyId + privateKey.
Web PushPUSH_WEBPUSH_VAPID_PRIVATE_KEY (required) and PUSH_WEBPUSH_VAPID_CONTACT (defaults to mailto:sockudo-webpush@example.com).Accepted by push/credentials/webpush; the dispatch worker reads the VAPID key from the environment.
HMSPUSH_HMS_APP_ID and a pre-generated PUSH_HMS_PROVIDER_TOKEN. Optional PUSH_HMS_ENDPOINT.Accepted by push/credentials/hms; the dispatch worker reads the environment.
WNSA pre-generated PUSH_WNS_PROVIDER_TOKEN.Accepted by push/credentials/wns; the dispatch worker reads the environment.

Point APNs workers at the sandbox with PUSH_APNS_ENDPOINT=https://api.sandbox.push.apple.com (or [push.apns].endpoint) when you test development-build tokens.

.env
PUSH_FCM_ENABLED=true
PUSH_FCM_SERVICE_ACCOUNT_JSON_PATH=/run/secrets/fcm-service-account.json
PUSH_APNS_ENABLED=true
PUSH_APNS_TOPIC=com.example.app
PUSH_APNS_TEAM_ID=TEAMID1234
PUSH_APNS_KEY_ID=KEYID12345
PUSH_APNS_PRIVATE_KEY_PATH=/run/secrets/AuthKey_KEYID12345.p8
PUSH_WEBPUSH_ENABLED=true
PUSH_WEBPUSH_VAPID_PRIVATE_KEY=...
PUSH_WEBPUSH_VAPID_CONTACT=mailto:ops@example.com

Store a credential through the API

Credential endpoints require the push-admin capability. Secret fields are encrypted before they are stored and are never returned.

POST /apps/{appId}/push/credentials/apns
Content-Type: application/json
{
"credentialId": "apns",
"version": 2,
"teamId": "TEAMID1234",
"keyId": "KEYID12345",
"privateKey": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
}
201 Created
{
"app_id": "my-app",
"credential_id": "apns",
"provider": "apns",
"version": 2
}
EndpointBody fields
POST /apps/{appId}/push/credentials/fcmserviceAccountJson (object)
POST /apps/{appId}/push/credentials/apnsp12 + p12Password, or pem, or teamId + keyId + privateKey
POST /apps/{appId}/push/credentials/webpushpublicKey, privateKey
POST /apps/{appId}/push/credentials/hmshmsAppId, clientSecret
POST /apps/{appId}/push/credentials/wnspackageSid, clientSecret
GET /apps/{appId}/push/credentialsLists stored credentials (metadata only), paged with limit and cursor.

Every credential body also accepts optional credentialId (defaults to the provider name) and version (defaults to 1).

Authorization model

Every push endpoint is a signed app API request, authenticated with the app key and secret exactly like the rest of the HTTP API. On top of that, the x-sockudo-push-capability header selects one of two capabilities:

CapabilityWhen to useWhat it may do
push-admin (default when the header is absent)Your trusted backend.Everything: credentials, templates, publishes, status, dead letters, any device or subscription.
push-subscribeDevice-scoped calls that act on one existing device.Update an existing device registration, and read, add, or remove that device’s channel subscriptions. Requires x-sockudo-device-identity-token (or an Authorization bearer token) matching the device.

An admin registration of a new device returns a one-time deviceIdentityToken. Send x-sockudo-rotate-device-identity-token: true with an admin registration to issue a new one.

Register devices

Device IDs should be stable per installation. Provider tokens rotate; register again with the same id whenever the platform SDK gives you a new token. The response tells you whether anything changed.

POST /apps/{appId}/push/deviceRegistrations
Content-Type: application/json
x-sockudo-push-capability: push-admin
{
"appId": "my-app",
"id": "ios-7f3c2a",
"clientId": "user-42",
"formFactor": "phone",
"platform": "ios",
"timezone": "Europe/Berlin",
"locale": "de-DE",
"deviceSecret": "server-assigned",
"push": {
"state": "ACTIVE",
"recipient": { "transportType": "apns", "deviceToken": "APNS_DEVICE_TOKEN" }
}
}
201 Created
{
"change": "inserted",
"tokenHash": "9c1e...",
"device": {
"appId": "my-app",
"id": "ios-7f3c2a",
"clientId": "user-42",
"formFactor": "phone",
"platform": "ios",
"timezone": "Europe/Berlin",
"locale": "de-DE",
"lastActiveAtMs": 0,
"pushState": "ACTIVE",
"pushFailureCount": 0,
"recipient": { "transportType": "apns", "provider": "apns", "tokenHash": "9c1e..." }
},
"deviceIdentityToken": "DEVICE_IDENTITY_TOKEN"
}
  • formFactor: phone, tablet, desktop, tv, car, watch, embedded, or other.
  • platform: android, ios, browser, windows, macos, watchos, tvos, or other.
  • push.state: ACTIVE, FAILING, or FAILED. Register new devices as ACTIVE.
  • deviceSecret is part of the device schema, but the server always replaces it with the hash of the issued device identity token; send any placeholder.
  • change is inserted, updated, or unchanged.

With the Node server SDK, the same call from your backend looks like this:

routes/push.ts
app.post("/api/push/devices", async (req, res) => {
const user = requireUser(req);
const result = await sockudo.activateDevice({
appId: process.env.SOCKUDO_APP_ID!,
id: req.body.deviceId,
clientId: user.id,
formFactor: "phone",
platform: req.body.platform,
timezone: req.body.timezone,
locale: req.body.locale,
deviceSecret: "server-assigned",
push: {
state: "ACTIVE",
recipient: { transportType: "gcm", registrationToken: req.body.fcmToken },
},
});
res.json({ tokenHash: result.tokenHash });
});

Other device operations:

RequestCapabilityResult
GET /apps/{appId}/push/deviceRegistrations/{id}admin, or subscribe with the device’s identity tokenThe device (without raw tokens).
GET /apps/{appId}/push/deviceRegistrations?limit=&cursor=admin{ "items": [...], "next_cursor": ..., "has_more": ... }
DELETE /apps/{appId}/push/deviceRegistrations/{id}admin, or subscribe with the device’s identity token204 No Content
DELETE /apps/{appId}/push/deviceRegistrations?clientId=user-42admin{ "deleted": n, "consistency": "eventual" }

List endpoints accept limit between 1 and 1000 and return an opaque next_cursor.

Subscribe devices to channels

A channel subscription lets a publish that targets { "type": "channel" } reach every device subscribed to that channel. Pass the tokenHash returned by registration.

POST /apps/{appId}/push/channelSubscriptions
Content-Type: application/json
x-sockudo-push-capability: push-admin
{
"appId": "my-app",
"channel": "orders",
"deviceId": "ios-7f3c2a",
"clientId": "user-42",
"provider": "apns",
"tokenHash": "9c1e..."
}

The response is 201 Created with the stored subscription. With the Node SDK:

await sockudo.upsertChannelPushSubscription({
appId: process.env.SOCKUDO_APP_ID!,
channel: "orders",
deviceId: "ios-7f3c2a",
clientId: "user-42",
provider: "apns",
tokenHash: registration.tokenHash,
credentialVersion: 1,
});
RequestResult
GET /apps/{appId}/push/channelSubscriptions?channel=ordersDevices subscribed to a channel.
GET /apps/{appId}/push/channelSubscriptions?deviceId=ios-7f3c2aChannels a device is subscribed to. push-subscribe callers must pass their own deviceId.
GET /apps/{appId}/push/channelSubscriptions/channelsEvery channel with at least one push subscription (admin only).
DELETE /apps/{appId}/push/channelSubscriptions?channel=orders or ?deviceId=...{ "deleted": n }. One of channel or deviceId is required.
Client app
Your backend
Sockudo
Push provider
1current provider token
2verify user and device
3register device
4subscribe device to channel
5publish push
6202 publishId
7provider request
8accepted or failed
9get publish status
10state and counters
sequenceDiagram
  participant App as Client app
  participant API as Your backend
  participant S as Sockudo
  participant P as Push provider

  App->>API: current provider token
  API->>API: verify user and device
  API->>S: register device
  API->>S: subscribe device to channel
  API->>S: publish push
  S-->>API: 202 publishId
  S->>P: provider request
  P-->>S: accepted or failed
  API->>S: get publish status
  S-->>API: state and counters

Publish

A publish combines targets (recipients) with a payload. Publish requires push-admin.

POST /apps/{appId}/push/publish
Content-Type: application/json
x-sockudo-push-capability: push-admin
{
"publishId": "order-ord_123-packed",
"recipients": [
{ "type": "channel", "channel": "orders" },
{ "type": "client", "client_id": "user-42" }
],
"payload": {
"title": "Order updated",
"body": "Order ord_123 is packed",
"collapseKey": "order-ord_123",
"templateData": { "order_id": "ord_123" }
}
}
202 Accepted
{
"publishId": "order-ord_123-packed",
"status": "accepted",
"expectedRecipients": 2,
"fanoutRegime": "fastPath",
"renderedPayloads": [
{
"provider": "apns",
"payload": {
"headers": { "apns-push-type": "alert", "apns-priority": "10", "apns-collapse-id": "order-ord_123" },
"aps": { "alert": { "title": "Order updated", "body": "Order ord_123 is packed" }, "sound": null },
"data": { "order_id": "ord_123" }
},
"usedOverride": false
}
]
}

renderedPayloads contains one preview per provider (FCM, APNs, Web Push, HMS, WNS, and the realtime transport); the example above shows only APNs. fanoutRegime is fastPath below push.fanout_fast_threshold expected recipients and shardPath above it.

With the Node SDK:

const response = await sockudo.publishPush({
publishId: "order-ord_123-packed",
recipients: [
{ type: "channel", channel: "orders" },
{ type: "client", client_id: "user-42" },
],
payload: {
title: "Order updated",
body: "Order ord_123 is packed",
templateData: { order_id: "ord_123" },
},
});
console.log(response.publishId);

Targets

typeFieldsResolves to
devicedevice_idOne registered device.
clientclient_idEvery device registered with that clientId.
channelchannelEvery device subscribed to that channel.
recipientrecipient (a raw provider recipient, for example { "transportType": "gcm", "registrationToken": "..." })One provider token, without a stored device. Requires push-admin.
registeredTopic, userTopictopicTopic-scoped targets.
providerTopicprovider, topicA provider-native topic.
providerConditionprovider, conditionA provider-native condition expression.
indexedFilterfilterAn indexed device filter.

Payload fields

FieldMeaning
title, bodyNotification text.
iconAn https image URL.
soundPlatform sound name.
collapseKeyCollapses superseded notifications (APNs apns-collapse-id, Web Push topic, FCM/HMS collapse_key).
templateDataArbitrary JSON delivered as the provider data object, and the source for template placeholders.
templateIdReferences a stored template.

Idempotency

Publishing is idempotent in two ways. Reusing a publishId returns the original publish instead of creating new work. Sending an identical request body (same targets, payload, overrides, and timing) also resolves to the original publish. Idempotency records last until expiresAtMs, or 24 hours when no expiry is set.

Track publish status

GET /apps/{appId}/push/publish/order-ord_123-packed/status
x-sockudo-push-capability: push-admin
200 OK
{
"appId": "my-app",
"publishId": "order-ord_123-packed",
"state": "succeeded",
"counters": {
"planned": 2,
"dispatched": 2,
"succeeded": 2,
"failed": 0,
"expired": 0,
"retryScheduled": 0,
"retryAttempted": 0,
"deadLettered": 0
},
"fanoutRegime": "fastPath"
}
stateMeaning
queuedDurably accepted; waiting for the planner. The publish response reports this as accepted.
planningTargets are being resolved to devices.
throttledDelivery is paused by rate or quota limits.
dispatchingProvider requests are in flight or scheduled for retry.
succeededEvery planned delivery succeeded.
partiallySucceededSome deliveries succeeded and some failed, expired, or dead-lettered. The publish response label is partially_succeeded.
failedEvery delivery failed terminally.
expiredexpiresAtMs passed before delivery.
dead_letteredRetries were exhausted with no successes.
quota_exceededRejected at admission by a fanout or delivery quota.
cancelledCancelled before dispatch.

planned is the acceptance-time audience estimate. Terminal states are absorbing: once a publish is succeeded, failed, expired, dead_lettered, partiallySucceeded, quota_exceeded, or cancelled, it never moves again.

Payload fidelity, templates, and overrides

Publish responses include renderedPayloads, one provider-specific preview per provider. The same renderer is used by admission and dispatch. Provider workers send the previewed provider payload, except for runtime-only fields such as provider tokens, APNs device tokens, generated authorization headers, and provider request IDs.

providerOverrides are provider-specific complete payloads. When an override exists for a provider, it replaces the generic payload mapping for that provider. APNs override headers become APNs request headers, Web Push headers.ttl, headers.urgency, and headers.topic become Web Push request headers, and FCM/HMS/WNS overrides are sent as the provider body with runtime recipient tokens added by the worker. Overrides are validated and size-checked before dispatch.

{
"recipients": [{ "type": "client", "client_id": "user-42" }],
"payload": { "title": "Order updated", "body": "Order ord_123 is packed" },
"providerOverrides": [
{
"provider": "fcm",
"payload": {
"message": {
"notification": { "title": "Order updated", "body": "Packed and ready" },
"android": { "priority": "high" }
}
}
}
]
}

Templates

Store localized content once and reference it by templateId:

POST /apps/{appId}/push/templates
Content-Type: application/json
{
"appId": "my-app",
"templateId": "order-packed",
"defaultLocale": "en",
"locales": {
"en": { "title": "Order packed", "body": "Order {{ data.order_id }} is packed" },
"de": { "title": "Bestellung verpackt", "body": "Bestellung {{ data.order_id }} ist verpackt" }
}
}

The response is 201 Created with the stored template. defaultLocale must exist in locales. GET /apps/{appId}/push/templates, GET /apps/{appId}/push/templates/{id}, and DELETE /apps/{appId}/push/templates/{id} list, read, and remove templates.

Templates are resolved during publish admission. A payload.templateId must reference an existing template; missing templates fail the publish request before work is accepted. Sockudo selects the template locale from payload.templateData.locale, falling back from exact locale to language and then the template’s defaultLocale. Template fields fill missing payload fields, while explicit payload fields win. Template provider overrides are applied first and request providerOverrides win when both define the same provider. The resolved payload is stored in the accepted publish work, so later template edits do not change queued delivery or retry attempts.

Template placeholders use bounded {{ data.path }} substitutions against payload.templateData. Missing placeholders fail admission with a precise invalid-template error; objects and arrays are not coerced into strings.

Delayed delivery and cancellation

const delayed = await sockudo.publishPush({
notBeforeMs: Date.parse("2026-05-19T18:00:00Z"),
expiresAtMs: Date.parse("2026-05-19T18:10:00Z"),
recipients: [{ type: "client", client_id: "user-42" }],
payload: { title: "Reminder", body: "Your room starts soon" },
});

notBeforeMs delays provider dispatch; expiresAtMs prevents late sends. Both are enforced at delivery time, including on retries.

The public HTTP API does not expose a separate schedule-create endpoint. Use POST /apps/{appId}/push/publish with notBeforeMs for delayed delivery. Persisted scheduled jobs created by internal scheduler/store integrations can be cancelled before emission with DELETE /apps/{appId}/push/scheduled/{jobId}, which returns 204 No Content.

Channel-triggered push rule

Push rules convert normal channel events into push work, with no extra API call from your backend. This is useful for product events and AI agent completion notifications.

config.toml
[[push_rules]]
enabled = true
channel_pattern = "notifications:*"
event_filter = ["agent-complete", "order-ready"]
rate_limit_per_second = 100
[push_rules.payload_mapping]
title_field = "title"
body_field = "body"
template_data_field = "data"
include_remaining_fields = true

A realtime publish such as this one now also produces a channel-targeted push to every device subscribed to notifications:user-42:

{
"name": "agent-complete",
"channel": "notifications:user-42",
"data": {
"title": "Agent finished",
"body": "Your answer is ready",
"data": {
"session_id": "sess_01J"
}
}
}
  • channel_pattern supports an exact name, *, or a trailing wildcard such as notifications:*.
  • event_filter must list 1 to 32 event names.
  • The event data must be a JSON object with string title and body fields (or the fields named by payload_mapping). Events that do not match produce no push.

Admission readiness

Sockudo fails closed before accepting publish work it already knows cannot be processed safely. The push publish API requires a healthy push queue, production-safe storage, local pipeline workers, and local provider-worker capability. Raw FCM/APNs/Web Push/HMS/WNS recipients require the matching provider worker in this process. Channel, client, and device targets require at least one active provider worker without scanning large channel subscription sets during admission; shard-path publishes also require a local shard worker. The planner still resolves exact devices asynchronously.

ResponseCause
202 with status: "quota_exceeded"Quota rejection. Sockudo persists a terminal quota_exceeded publish status and idempotency record without appending publish log work or enqueueing the pipeline.
429 with Retry-AfterQueue pressure (a critical stage crossed its lag or oldest-age threshold), or the per-app acceptance rate ([push.default_quotas].acceptance_rps, overridable with PUSH_ACCEPTANCE_RATE_LIMIT) was exceeded.
503Readiness failure: queue unhealthy, memory drivers in production, missing provider feature or credentials, or no capable worker.
400Invalid targets, payload, template, override, or Live Activity fields.
403Missing push-admin capability.

Errors use the standard body { "error": "...", "code": "...", "status": 503 }.

Cluster queue delivery guarantees

Push queue delivery is at-least-once. Accepted publish work is durable before the API returns, and every delivery result is idempotently applied by feedback workers. A provider send can still be duplicated if a worker crashes after the provider accepts the request but before push.results.v1 is produced or before the original delivery batch is acknowledged. Sockudo keeps the duplicate window bounded with stable delivery idempotency keys, deterministic retry context, and duplicate feedback suppression, but it does not claim exactly-once provider delivery.

In monolith deployments, each node consumes only stages it can process. Planner, shard, feedback, retry, and dead-letter stages are consumed only by nodes with the matching local worker enabled. Provider delivery stages such as push.delivery.fcm.v1 are consumed only by nodes whose provider worker is active and credential-ready at boot. Changing provider capability or credentials requires worker restart; stored credentials are reloaded when a supervised provider worker restarts.

External queue adapters pull broker messages into a bounded node-local ready/pending handoff before Sockudo workers ack, nack, or dead-letter them. If the local worker does not finish before the local lease timeout, the adapter requeues the envelope with backoff. Queue health and lag reported by the generic queue manager adapter distinguish this node’s local pull-ahead depth and oldest actionable handoff age from broker-wide backlog, so operators can alert on Sockudo-owned worker staleness with sockudo_push_queue_oldest_age_seconds and use backend-native tools for deeper broker visibility. The monolith repair worker also scans durable publish-log entries that remain queued past push.repair_min_age_secs and recreates missing push.publish.v1 work if an accepted publish lost its queue message before planning began.

Retry and dead letters

Provider throttling, 5xx responses, and transport failures are classified as retryable provider, quota, or network failures. Feedback workers schedule retry entries on push.retry.v1 with the original delivery job context, a deterministic retry idempotency key, the next attempt number, the first-attempt timestamp, retry deadline, and the provider error class. Retry scheduler workers consume only due entries, respect provider Retry-After deadlines when configured, and otherwise use bounded exponential backoff with deterministic jitter.

config.toml (defaults)
[push.retry]
max_attempts = 5
initial_backoff_ms = 1000
max_backoff_ms = 60000
max_elapsed_secs = 86400
jitter = true
jitter_ratio_percent = 20
respect_retry_after = true

Retries stop at the earliest of max_attempts, max_elapsed_secs, or the publish/job expires_at_ms. Exhausted retry work is emitted to push.deadletters.v1 and the publish status moves to dead_lettered unless some deliveries already succeeded, in which case it becomes partially succeeded. If the publish expiry passes before a retry can run, the publish moves to expired. Pending retry work increments retryScheduled; retry dispatch increments retryAttempted; dispatched counts terminal provider outcomes so retry attempts do not inflate completion accounting.

Publish timing is enforced at delivery time. notBeforeMs delays provider dispatch; provider workers split mixed due/future batches so due jobs are not blocked behind future jobs. expiresAtMs prevents late sends; expired delivery jobs are recorded as expired and are not sent to providers. Retry scheduling preserves the original timing window and does not run past publish or job expiry.

Operators inspect aggregate status with GET /apps/{appId}/push/publish/{publishId}/status, retry and dead-letter queue lag through the health/backpressure surfaces, and metrics such as sockudo_push_queue_oldest_age_seconds{stage=...,state=...}, sockudo_push_retry_scheduled_total, sockudo_push_retry_attempted_total, sockudo_push_retry_dead_lettered_total, sockudo_push_retry_malformed_total, and sockudo_push_provider_failures_total{failure_class=...}. Inspect and replay dead letters with GET /apps/{appId}/push/deadLetters and POST /apps/{appId}/push/deadLetters/{deadLetterId}/replay; see Push operations.

Lifecycle safety checks expose sockudo_push_invariant_violations_total{invariant=...}. The bounded status_transition label means a stale, non-monotonic status write was ignored. The metric does not include payloads, device tokens, or provider credentials.

Publish-status mutations use storage-level compare-and-swap in every backend. Short-lived write contention increments sockudo_push_status_cas_conflicts_total{component=...} and is retried with a fixed bound. sockudo_push_status_cas_exhausted_total{component=...} means that bound was exhausted; the worker returns a structured error instead of silently accepting a lost update. Component labels come from a fixed internal set and neither metric includes payloads, tokens, credentials, app IDs, or publish IDs.

Upgrade note: provider workers now enqueue internal deliveryFeedback payloads on push.results.v1 so feedback workers can schedule retries with replayable job context. Older deliveryResult payloads are still accepted, but retryable legacy results without job context are dead-lettered instead of being retried blindly.

Provider outcomes and device invalidation

Every provider response becomes a delivery outcome (accepted, rejected, retryable, expired, or cancelled) plus a failure class. The outcome decides whether the delivery is retried; the class decides what happens to the device and how the failure is counted.

failure_classTypical causeDevice effect
device_terminalThe token is permanently invalid (see below).Device registration is deleted.
device_transientA device-specific, possibly temporary failure.Failure count increments; the device moves from ACTIVE to FAILING, then FAILED.
provider_transientProvider 5xx.None.
provider_quotaProvider 429 or quota response.None.
credential_authBad key, project, topic, environment, or VAPID configuration.None.
caller_payloadThe provider rejected the payload.None.
network_transportDNS, TLS, or connection failure.None.
unknownUnclassified response.None.

Sockudo deletes or terminally invalidates a device only for device-specific terminal failures:

  • FCM UNREGISTERED, registration-token-not-registered, or an INVALID_ARGUMENT response that specifically identifies the registration token as invalid.
  • APNs BadDeviceToken or Unregistered.
  • Web Push, HMS, and WNS expired subscription/channel responses such as 404 or 410.

Provider-wide failures do not increment device failure counts and do not delete devices. This includes FCM SENDER_ID_MISMATCH or project mismatch, APNs topic/environment/auth failures, Web Push VAPID/auth failures, provider 429 quota responses, provider 5xx responses, DNS/TLS/network transport failures, and caller payload errors. These outcomes still update publish status, schedule retry or dead-letter work according to the retry policy, and emit classified metrics.

The sockudo_push_provider_failures_total{failure_class=...} metric separates these classes. The sockudo_push_token_invalidation_guard_total metric and token-invalidation-guard meta event fire when a publish crosses the built-in invalidation spike threshold: at least 10 failed deliveries and at least 20% of the planned recipients.

Retention and cleanup

The cleanup worker runs in monolith deployments when push.cleanup_interval_secs > 0. It removes terminal publish statuses older than push.publish_status_ttl_days, delivery events and operator invalidation events older than push.analytics_retention_days, expired idempotency records, and expired scheduler locks. It does not delete active scheduled jobs, active retry work, credentials, templates, or active device registrations.

Cleanup is incremental: each tick is bounded by push.cleanup_batch_size per category and push.cleanup_max_deleted_per_tick overall. See Push operations for metrics, alerts, and outage runbooks.

Capacity planning

Push fanout has a different bottleneck profile than WebSocket fanout:

  • provider rate limits
  • token invalidation churn
  • per-platform payload size limits (4096 bytes for FCM, APNs device, Web Push, and HMS payloads)
  • queue depth and worker concurrency (dispatch_worker_count, dispatch_max_outbound_requests)
  • status retention writes
  • scheduled publish scans
  • provider callback volume

Before a campaign, test admission and provider dispatch separately. A healthy API admission rate does not prove provider delivery capacity.

Benchmarking

Use the repository push benchmark for repeatable scenarios. --mode is seed (register devices and subscriptions), admission (publish load), e2e, or all.

Terminal window
node scripts/push-benchmark.mjs \
--url http://127.0.0.1:6001 \
--app-id app-id \
--key app-key \
--secret app-secret \
--mode all \
--provider fcm \
--devices 10000 \
--channels 100 \
--concurrency 50 \
--duration 60

Track accepted publishes, queue depth, provider dispatch latency, provider error classes, and status write latency.

The Criterion benchmark push_retry_scheduler/memory_drain_100k_due_retry_entries_budget_lt_5s seeds and drains 100k due retry entries through the memory queue/store path as a regression guard for retry scheduling overhead.

Troubleshooting

SymptomCheck
202 returned but no notificationInspect publish status and provider errors.
400 invalid JSON body on registrationInclude appId, deviceSecret, push.state, timezone, and locale; check field casing.
403 push-admin capability is requiredThe request sent x-sockudo-push-capability: push-subscribe to an admin-only endpoint.
401 invalid deviceIdentityTokenThe device-scoped call used a missing or rotated identity token.
APNs rejects tokenVerify bundle ID, environment, topic, and token freshness.
Web Push rejectedVerify VAPID key and contact, and that the endpoint host is public HTTPS.
FCM unauthorizedVerify service account and project.
Channel push misses usersVerify channel push subscriptions and client_id mapping.
Large push is rejectedCheck platform payload limits and remove nonessential data.
Push publish returns 503Check push queue health, memory-driver production guard, provider feature flags, provider credentials, and dispatch worker count.
Push publish returns 429Check publish-log, shard, delivery result, retry, dead-letter, active provider delivery queue depth, and sockudo_push_queue_oldest_age_seconds.
Publish remains dispatchingCheck retry scheduler workers, push.retry.v1 lag, dead-letter lag, and provider retry-after deadlines.
Publish becomes dead_letteredInspect GET /apps/{appId}/push/deadLetters, retry metrics, provider outage history, and max_attempts/max_elapsed_secs; replay only entries marked replayable.
Cleanup failures increaseCheck sockudo_push_cleanup_errors_total, store connectivity, and batch limits.

Push payloads should wake the app and include stable IDs. Fetch authoritative application state after the user opens the notification.

Next steps