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.
How it fits into JMAP
Section titled “How it fits into 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.
Connection lifecycle
Section titled “Connection lifecycle”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 recordAuthentication
Section titled “Authentication”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.
Message protocol
Section titled “Message protocol”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.
subscribe — client → server
Section titled “subscribe — client → 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"] }}| Field | Description |
|---|---|
id | Client-generated correlation ID, echoed back in the response |
accountId | The JMAP accountId to subscribe to |
types | Data 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.
subscribed — server → client
Section titled “subscribed — server → client”Confirmation that the subscription was accepted.
{ "subscribed": { "id": "req-1" }}The id matches the correlation ID from the originating subscribe.
stateChange — server → client
Section titled “stateChange — server → client”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" } }}| Field | Description |
|---|---|
accountId | The JMAP accountId where the change occurred |
changes | Map 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.
error — server → client
Section titled “error — server → client”Returned when a client message cannot be processed.
{ "error": { "id": "req-1", "code": "accountNotFound", "description": "Account not found" }}code | Meaning |
|---|---|
forbidden | The connection’s credentials were not accepted |
accountNotFound | The requested accountId does not exist or the authenticated user cannot access it |
invalidArguments | The message could not be parsed or a required field is missing |
tooManySubscriptions | The types list is longer than the server allows in one subscribe |
serverFail | The request could not be processed; the client may retry |
The JMAP PushSubscription standard
Section titled “The JMAP PushSubscription standard”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.
Rights and delivery
Section titled “Rights and delivery”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 HTTPPOSTof a JSONStateChangeobject 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
POSTcarriesContent-Type: application/jsonandTTL: 3600(RFC 8030). A client that supplieskeysreceives every notification, the verification request included, encrypted as web push (RFC 8291), withContent-Encoding: aes128gcm; withoutkeysthe body is plain JSON. - Cut to the subscribed
types. A notification names only the changed types the subscription asked for.nullmeans every deliverable type;[]is accepted and delivers nothing. The deliverable types areMailbox,Email,Thread,EmailDelivery,Identity,EmailSubmission,AddressBook,ContactCard,Principal,ShareNotificationandSieveScript; any other name is rejected withinvalidProperties. EmailDeliveryis included. TheEmailDeliverytype 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
2xxis a success. The server honoursRetry-Afteron429and503, removes the subscription on404and410, 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.
The subscription object
Section titled “The subscription object”| Property | Notes |
|---|---|
id | Server-set. |
deviceClientId | Required on create, immutable, 1 to 255 characters. Your own identifier for the device; never sent in a notification. |
url | Required on create, immutable, never returned. An absolute https URL with a DNS host name, no credentials, no fragment, port 443 or no port. |
keys | Optional, immutable, never returned. {"p256dh": …, "auth": …}, both URL-safe base64. |
verificationCode | Null on create; set once on update to the received code. Always null when read. |
expires | Optional, settable. See Lifetime. |
types | Optional, 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.
Verification
Section titled “Verification”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-
2xxresponse, a timeout or a connection error) removes the unconfirmed subscription. The response to the creatingsetis the same whether or not the URL is reachable, so a client sees this as the id turning up innotFoundonget.
Lifetime
Section titled “Lifetime”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 with | expires | Ends |
|---|---|---|
| Personal access token | Your 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 session | Your 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.
Where push differs from the standards
Section titled “Where push differs from the standards”- EventSource is not served. RFC 8620 §7.3 defines an
EventSourcepush 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 valideventSourceUrltemplate. Clients usePushSubscription, 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
expireswhile signed in. - Deleted
urlandkeyscan remain in table backups. Destroying a subscription deletes its stored record, includingurlandkeys. 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.
Note on the JMAP WebSocket standard
Section titled “Note on the JMAP WebSocket standard”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.
Related
Section titled “Related”- System Architecture — how the WebSocket infrastructure fits into the overall system
- Email Processing Pipeline — what triggers state changes on the inbound path
- Email Sending Pipeline — what triggers state changes on the outbound path
- WebSocket Events Reference — quick-reference table of all message types