Skip to content

Push Notifications & Real-Time Updates

ServerlessInbox notifies clients when data has changed, so a JMAP client stays in sync without polling. It offers two channels: a WebSocket connection, described first, and JMAP’s standard PushSubscription, where a client registers an HTTPS endpoint that the server calls; see The JMAP PushSubscription standard below. Both are hints: they say that something changed, and the client fetches the data over ordinary JMAP.


JMAP tracks object state with opaque state strings. Every Email, Mailbox, and other object type has a state string that advances whenever something changes. A client that wants to stay in sync must periodically call Email/changes (or similar) with its last known state to get a list of additions, modifications, and deletions.

The WebSocket channel does one thing: it tells clients when to make those calls. The server sends a stateChange notification that includes the new state string for each affected data type. The client compares this against what it has cached and issues the appropriate JMAP /changes request.

This means the WebSocket is not a data transport — it’s a signal channel. All actual data retrieval continues via standard JMAP over HTTP.


sequenceDiagram
participant Client
participant APIGW as API Gateway (WS)
participant Auth as Authorizer λ
participant Connect as websocket-connect λ
participant Message as websocket-message λ
participant DDB as DynamoDB
participant Broadcast as state-change-fanout λ
Client->>APIGW: WSS connect (token in Sec-WebSocket-Protocol header)
APIGW->>Auth: Validate JWT
Auth-->>APIGW: Allow
APIGW->>Connect: $connect
Connect->>DDB: Store connection (TTL 24h)
Connect-->>Client: 200 (connected)
Client->>Message: {"subscribe": {...}}
Message->>DDB: Update connection with account + types
Message-->>Client: {"subscribed": {...}}
Note over Broadcast,Client: Data changes (email arrives, sent, etc.)
Broadcast->>DDB: Query connections for accountId
Broadcast-->>Client: {"stateChange": {...}}
Client->>APIGW: Disconnect
APIGW->>DDB: Delete connection record

The WebSocket connection is authenticated via the same Lambda authorizer used by the REST APIs. Because browsers cannot send custom HTTP headers during a WebSocket handshake, the JWT token is passed using the Sec-WebSocket-Protocol header — a header that browsers do allow during the upgrade request. This also keeps the token out of access logs: a token placed in the query string would be recorded in the access logs of the CDN and the API in front of the connection, whereas this header is not.

The authorizer accepts the token in either of these formats:

Sec-WebSocket-Protocol: Bearer <token>
Sec-WebSocket-Protocol: bearer, <token>

The two-part comma-separated form (bearer, <token>) is the idiomatic pattern when the client also needs to negotiate a real subprotocol alongside the token. If the server echoes back bearer as the accepted subprotocol, clients should handle this gracefully.

The authorizer validates the token before the $connect Lambda runs. If the token is missing or invalid, the connection is rejected with HTTP 401 before any frame is exchanged.

Connection records are stored in DynamoDB with a 24-hour TTL as a safety net — a clean disconnect removes the record immediately.


All frames are JSON text frames. The message type is indicated by the top-level key — there is no separate type discriminator field.

Only one message type is accepted from the client (subscribe). All others originate from the server.

Sent after connecting to tell the server which account and data types to watch. A connection can only hold one subscription; sending a new subscribe replaces the previous one.

{
"subscribe": {
"id": "req-1",
"accountId": "abc123",
"types": ["Email", "Mailbox"]
}
}
FieldDescription
idClient-generated correlation ID, echoed back in the response
accountIdThe JMAP accountId to subscribe to
typesData types to watch. Omit or send [] to watch all types

The channel carries the data types a client can track with */changes: Mailbox, Email, Thread, EmailDelivery, Identity, EmailSubmission, AddressBook, ContactCard, Principal, ShareNotification and SieveScript. It never carries User, Account or Alias. A stateChange contains only the types that changed and that the connection subscribed to.

Confirmation that the subscription was accepted.

{
"subscribed": {
"id": "req-1"
}
}

The id matches the correlation ID from the originating subscribe.

Signals that one or more data types have a new state. The client should call the relevant JMAP */changes methods to retrieve the delta.

{
"stateChange": {
"accountId": "abc123",
"changes": {
"Email": "n8",
"Mailbox": "42"
}
}
}
FieldDescription
accountIdThe JMAP accountId where the change occurred
changesMap of data type to its new state string

The client uses its previously cached state to call e.g. Email/changes with sinceState: <cached> — the server returns the list of IDs that were created, updated, or destroyed.

Returned when a client message cannot be processed.

{
"error": {
"id": "req-1",
"code": "accountNotFound",
"description": "Account not found"
}
}
codeMeaning
forbiddenThe connection’s credentials were not accepted
accountNotFoundThe requested accountId does not exist or the authenticated user cannot access it
invalidArgumentsThe message could not be parsed or a required field is missing
tooManySubscriptionsThe types list is longer than the server allows in one subscribe
serverFailThe request could not be processed; the client may retry

RFC 8620 §7.2 defines PushSubscription objects, managed with PushSubscription/get and PushSubscription/set. They let a client register an endpoint that the server posts state changes to, so the client does not have to hold a connection open to receive them.

ServerlessInbox implements both methods, alongside the WebSocket channel rather than instead of it. The arguments and responses are in the PushSubscription reference. Both methods use the urn:ietf:params:jmap:core capability and are account-less: a subscription belongs to the user and to the credential that created it, not to an account. They take and return no accountId, state, oldState or newState, and /set takes no ifInState; a request that sends accountId, ifInState or any other unknown argument is answered with the method-level error invalidArguments.

Managing subscriptions requires the push/manage right. A personal access token must be granted it when the token is created; OAuth sessions request it through the push/manage scope. Without it, both methods return the method-level error forbidden.

  • A hint, not data. Like the WebSocket stateChange, a notification only says that something changed. Each is an HTTP POST of a JSON StateChange object for one account, such as {"@type":"StateChange","changed":{"<accountId>":{"Email":"n8","Mailbox":"42"}}}; the client fetches the delta with */changes. A change set too large for one notification is delivered as several. A missed notification is repaired by the next change or by polling.
  • HTTPS on port 443, optionally encrypted. Every POST carries Content-Type: application/json and TTL: 3600 (RFC 8030). A client that supplies keys receives every notification, the verification request included, encrypted as web push (RFC 8291), with Content-Encoding: aes128gcm; without keys the body is plain JSON.
  • Cut to the subscribed types. A notification names only the changed types the subscription asked for. null means every deliverable type; [] is accepted and delivers nothing. The deliverable types are Mailbox, Email, Thread, EmailDelivery, Identity, EmailSubmission, AddressBook, ContactCard, Principal, ShareNotification and SieveScript; any other name is rejected with invalidProperties.
  • EmailDelivery is included. The EmailDelivery type of RFC 8621 §1.5 changes when a message is newly delivered or created, not when it is flagged, moved or deleted, so a client can react to arriving mail specifically.
  • Rights are checked at delivery. A notification is sent only for accounts the subscribing user can read with the credential that created the subscription.
  • Endpoint responses. A 2xx is a success. The server honours Retry-After on 429 and 503, removes the subscription on 404 and 410, and removes a subscription whose endpoint keeps failing. Redirects are not followed, and a receiver should answer within 5 seconds. Addresses in private or reserved ranges are not contacted.
PropertyNotes
idServer-set.
deviceClientIdRequired on create, immutable, 1 to 255 characters. Your own identifier for the device; never sent in a notification.
urlRequired on create, immutable, never returned. An absolute https URL with a DNS host name, no credentials, no fragment, port 443 or no port.
keysOptional, immutable, never returned. {"p256dh": …, "auth": …}, both URL-safe base64.
verificationCodeNull on create; set once on update to the received code. Always null when read.
expiresOptional, settable. See Lifetime.
typesOptional, settable.

url and keys are write-only: stored with the subscription, removed with it, never echoed. Naming either in properties of PushSubscription/get returns forbidden; an unknown property name returns invalidArguments. A credential sees only the subscriptions it created; any other id, a missing id and an expired one all come back in notFound.

Limits: 10 live subscriptions per user and 200 per stack (overQuota beyond that), and 20 creations per user and 200 per stack per day (rateLimit). A bad or missing property is invalidProperties, naming the property. Errors never contain the URL or the keys.

Creating a subscription does not start notifications. The server first sends one POST to the url with the body {"@type":"PushVerification","pushSubscriptionId":"…","verificationCode":"…"}. The endpoint must make that code available to the client, which confirms by updating verificationCode with PushSubscription/set. Only a confirmed subscription receives notifications.

  • The code is never returned by get, so a client can only confirm a URL that actually received it.
  • An unconfirmed subscription ends after one hour, and five wrong codes remove it.
  • A verification request that fails (any non-2xx response, a timeout or a connection error) removes the unconfirmed subscription. The response to the creating set is the same whether or not the URL is reachable, so a client sees this as the id turning up in notFound on get.

A subscription does not live forever, and renewing it is the client’s duty. The client extends it by updating expires with an authenticated request before it passes; the response carries the value now in force.

Created withexpiresEnds
Personal access tokenYour requested value, capped at the token’s own expiry; without a request, the token’s expiry.At expires, when the token is revoked or expires, when the user is removed or disabled, or when it is destroyed.
OAuth sessionYour requested value, capped at 7 days; without a request, 7 days.At expires, when the user is removed or disabled, or when it is destroyed.

The OAuth case differs from the standard; see Where push differs from the standards.


  • EventSource is not served. RFC 8620 §7.3 defines an EventSource push transport, a long-lived HTTP stream per client. Every AWS transport that can hold such a stream open bills compute for as long as each client stays connected. The session keeps a valid eventSourceUrl template. Clients use PushSubscription, the WebSocket channel, or polling instead.
  • An OAuth-created subscription is not destroyed when the session is revoked. RFC 8620 §7.2 says a subscription must be destroyed when the credentials it was created with are revoked. The identity provider sends no revocation signal and the server never sees the refresh token, so the subscription ends as described in Lifetime. A subscription created with a personal access token is destroyed when that token is revoked. Clients should destroy their subscription on sign-out and renew it before expires while signed in.
  • Deleted url and keys can remain in table backups. Destroying a subscription deletes its stored record, including url and keys. When the installation has backups or point-in-time recovery enabled for the table that holds the record, a backup keeps the deleted values until that backup expires.

RFC 8887 defines a WebSocket subprotocol for JMAP that allows full JMAP API requests and responses to be sent over the WebSocket connection — effectively replacing the HTTP transport entirely.

ServerlessInbox does not implement RFC 8887. The principle is to keep the WebSocket channel simple and unidirectional: standard JMAP over HTTP handles all API calls, and the WebSocket carries only server-initiated push notifications. This keeps the Lambda routing straightforward and avoids multiplexing request/response semantics over a persistent connection.

RFC 8887 support could be added in the future if client implementors need it.