Web and networkingDive 10 of 12
How a push reaches your lock screen
Your chat tab is closed. Ana is running five minutes late. Follow one encrypted message through keys, queues, a sleeping phone and the bytes that wake it.
- Levels
- 10
- Reading
- 43 min
- Depth
- Idea to Silicon
- Published
“Ana: running 5 min late”
Encrypt once. Let a stranger carry it.Awaiting authenticated decryption.
Generating P-256 keys with WebCrypto.
A message with no tab to receive it
Ana opens your chat app and sends Ana: running 5 min late
. The recipient has locked their phone. Your tab is closed. There is no JavaScript timer waiting to check for messages, no DOM to update and no WebSocket owned by that page. Yet a few moments later the lock screen can show a notification from Chat. What received it?
The tempting answer is a service worker. That is only the middle of the answer. A service worker is an event-driven JavaScript program that the browser can start when needed. It is not a daemon that gets to keep a socket open all night. Something outside the website must maintain reachability, receive the message, identify the right registration and arrange to run that worker. Web Push splits those jobs across the browser, a push service and the operating system.
Why every site cannot keep its own connection
With an open chat tab, a WebSocket is an excellent way to deliver messages. Closing the tab ends that page’s lifetime. Keeping a hidden page alive for every site would retain memory and code that the user thought they had closed. Polling is worse: a timer wakes the device to ask whether anything happened, then often goes back to sleep with an empty answer. Shortening the interval improves latency by spending more requests and more wakeups.
A connection per background site is technically imaginable, but it fights the mobile power model. Idle TCP connections need state in endpoints and middleboxes. NAT mappings expire, networks change and heartbeats use the radio. Twenty independently scheduled keepalives can wake a device more often than one coordinated channel. A platform push client can share connection maintenance across many recipients while letting their application code remain stopped.
That sharing is the central bargain. Your server hands a small, encrypted envelope to a courier chosen by the user agent. The courier can hold it while the device is offline. The device already has a way to hear from that courier, so your origin does not need its own permanent background connection. When the envelope arrives, the browser can start your origin’s worker and hand it the plaintext.
| Mechanism | Open page needed? | What waits? | Best job |
|---|---|---|---|
| Polling | Usually a running client | Application timer | Periodic refresh while active |
| SSE / WebSocket | Page or another permitted active context | Your connection | Live conversation in the foreground |
| Web Push | No open tab | Shared platform/browser push channel | User-visible, time-sensitive background alerts |
Four actors, two kinds of protection
The application server knows Ana’s message and who should receive it. The push service knows how to address the recipient’s subscription. The user agent is the browser-side implementation that owns the subscription and its private decryption key. The service worker is your origin’s application code, invoked after the browser has decrypted the payload. Finally, the operating system decides how a requested notification appears.
HTTPS protects the server-to-service hop. It ends at the push service, so it alone would let the courier read every chat alert. Web Push adds message encryption that survives that TLS termination. The push service routes ciphertext; the recipient decrypts it. Authentication of the sending server is a separate mechanism, VAPID. Those three protections solve different problems and use different keys.
Knows Ana’s message. Holds the subscription, VAPID private key and a fresh ECDH sending key.
Sees destination, size, timing and delivery headers. Has no subscriber private key or auth secret.
Decrypts, dispatches push, renders Chat. No open tab required.
The website does not stay awake. A shared push client receives an envelope and wakes the right application only when there is work.
An address and two pieces of key material
Before the tab closes, the recipient opts in to chat alerts. The app needs permission to show notifications and a return address that the push service will recognize. In the classic Push API, that address belongs to a service worker registration. A registration persists beyond any particular worker instance, so the browser still knows what script and origin should receive future events.
Use a secure context and register the worker within the scope that should own chat notifications. Ask after a meaningful action such as Notify me about replies
, rather than on the first page load. On iOS, where Web Push arrived for Home Screen web apps in 16.4, the permission request must follow a direct user interaction. A denied permission is a user choice, not a transient network error to retry.
An explicit Notification.requestPermission() request resolves to granted, denied or default. Only granted authorizes notifications. A dismissed prompt can leave the state at default. subscribe() can request the permission itself, so a separate permission prompt is not needed in the example below.
Prepare the active worker registration before enabling the opt-in button. Then call the permission-gated API directly from the click handler, before awaiting registration, a network fetch or other unrelated work. Safari needs that user activation at the API call, asApple’s setup guidancespecifies. The example invokes subscribe() immediately on the prepared registration; it asks for notification permission if needed. An app using an explicit requestPermission() prompt should likewise start that request directly in the gesture handler.
// Prepare the registration on load, before offering the opt-in button.
const button = document.querySelector("#enable-chat-alerts");
button.disabled = true;
const raw = atob(VAPID_PUBLIC_KEY_B64URL.replace(/-/g, "+").replace(/_/g, "/"));
const applicationServerKey = Uint8Array.from(raw, c => c.charCodeAt(0));
await navigator.serviceWorker.register("/sw.js");
const registration = await navigator.serviceWorker.ready;
const options = { userVisibleOnly: true, applicationServerKey };
button.disabled = false;
button.addEventListener("click", async () => {
// Call the permission-gated API before awaiting unrelated work.
const subscription = await registration.pushManager.subscribe(options);
// subscribe() asks for notification permission if it is not yet granted.
// POST subscription.toJSON() to your authenticated application server.
// Bind it to this signed-in user and device; protect against CSRF.
});userVisibleOnly: true promises that messages will lead to user-visible effects. It is not a request to bypass focus modes or force the screen on.applicationServerKey is the application’s VAPID public key, a P-256 elliptic-curve point. Supplying it restricts use of the subscription to a server that can prove possession of the matching private key. It is not the recipient’s encryption key.
The resulting PushSubscription serializes to an endpoint URL, an optional expiration time and two key values. Save that object on your server, bound to the signed-in account and this device. One user can have several subscriptions across profiles and devices. Signing out should update that association so the next person using the browser does not inherit private alerts for the previous account.
The endpoint is an opaque capability
The browser selects the service. Chrome commonly uses FCM, Firefox uses Mozilla’s autopush infrastructure, and Safari uses Apple Web Push. The server should store and use the endpoint it receives rather than infer it from a user-agent string or rewrite its path. An endpoint identifies a subscription, not a stable person. Treat the full URL as sensitive routing material and avoid placing it in public logs.
The p256dh field is a 65-byte uncompressed P-256 public point:04, then a 32-byte x-coordinate and a 32-byte y-coordinate. Base64url without padding makes that 87 characters. The auth field is a 16-byte random authentication secret, encoded as 22 base64url characters. The browser keeps the corresponding ECDH private key. Your server needs the public point and auth secret together to construct encrypted payloads the subscriber will accept.
Choose Allow, then create the keys.
- p256dh
- —
- auth
- —
No browser permission prompt or network request will be made.
Decoding the two strings is an important server-side boundary. Base64url uses - and _ instead of the last two characters in ordinary base64, and commonly omits = padding. It is an encoding, not encryption. Validate the decoded point, lengths and endpoint before storing them. Because your server will later contact that URL, apply an endpoint policy that prevents a submitted subscription from turning your sender into a request proxy to internal services.
An expirationTime of null means no expiry timestamp was supplied. The subscription can still disappear after permission changes, browser data removal or push-service invalidation. On normal visits, reconcilegetSubscription() with your database. The pushsubscriptionchange event can help with changes, but recovery must also work when the application next opens. The registration is persistent state, not immortal state.
The Push API specificationdefines that browser-facing contract. The actual endpoint path remains the service’s business. We now have an address and the recipient’s encryption material. Before opening the envelope, the courier wants to know which application server is handing it over.
A subscription is a destination plus encryption material. The VAPID key passed to subscribe identifies the sender; p256dh identifies the recipient’s encryption key.
Prove which server is speaking
Ana’s chat server could send requests from thousands of machines. The push service needs a stable application identity to bind subscriptions, attribute traffic and contact an operator if something goes wrong. Voluntary Application Server Identification: a signed token and public key carried with a Web Push request, specified in RFC 8292. provides that identity without making every app server register a new vendor account.
The server creates a long-lived ECDSA signing key pair on the P-256 curve. Its public key is the one used when subscribing. Its private key stays on the backend in production. For a delivery request, the server signs a JSON Web Token with ES256: ECDSA over SHA-256. The token’s identity is self-asserted. Its useful proof is that this request came from someone holding the same private key that owns the bound subscription.
Three segments with precise meanings
A compact JWT is base64url(header).base64url(claims).base64url(signature). The header names alg: "ES256"; this lab also includes typ: "JWT". The claims contain aud, the push endpoint’s origin, and exp, an expiration expressed as whole seconds since the Unix epoch. A token must not expire more than 24 hours after the request. A sub contact can be a mailto: or https: URI.
The audience is easy to get wrong. For an endpoint under https://fcm.googleapis.com/wp/…, use https://fcm.googleapis.com. Do not put your chat origin there and do not include the endpoint path. The audience says which push service is intended to accept the token. An unusual explicit port belongs to the origin; a default HTTPS port is omitted by normal origin serialization.
The signature covers the ASCII bytes of the first encoded segment, a literal period and the second encoded segment. It does not cover prettified JSON, and it does not cover the message body. ECDSA produces two integers, r and s. JOSE’s ES256 representation is exactly 64 bytes, r || s with each integer padded to 32 bytes. WebCrypto supplies that raw format. Some server libraries instead expose DER signatures, which need conversion before they become JOSE signatures.
- Public key k · uncompressed P-256
- Header · base64url and decoded JSON
- Payload · base64url and decoded JSON
- Signature · 64 bytes, r || s
Exact signing input and Authorization header
Generating an ECDSA P-256 signing key.
The HTTP header is Authorization: vapid t=token, k=public_key. The t parameter holds all three JWT segments, joined by periods. The k parameter holds the 65-byte uncompressed public point in base64url. It is a public key, so the verifier can check the signature without ever receiving the signing secret. TLS protects these headers in transit to the service.
Verification has two parts. A cryptographically valid signature can still carry an expired token or the wrong audience. A service must check those claims and, for a restricted subscription, match the presented key to the subscription’s bound application key. Changing a key on the server alone cannot update that binding. This is why VAPID key rotation needs a migration plan rather than a simple environment-variable edit.
Servers can reuse a still-valid token for requests to the same audience. A token is not a per-message nonce, and ES256’s randomized signature means signing identical claims need not produce identical signature bytes. Choose an expiry that tolerates modest clock skew while meeting the 24-hour upper bound. Keep sender clocks synchronized; a signature library cannot repair a clock that manufactures invalid claims.
RFC 8292 also requires the signing key to be different from the key used for payload ECDH. Both use P-256, which makes the confusion tempting. Separate keys prevent one protocol’s use of a private scalar from being entangled with the other. VAPID answers which server?
; the next layer answers who can read Ana’s message?
VAPID signs a short-lived statement for the push service. It neither encrypts the payload nor proves that the recipient saw it.
An envelope the courier cannot open
The push service can authenticate Chat, but it should not learn that Ana is late. The server therefore encrypts the payload for the subscriber before making its HTTPS request. RFC 8291 defines how Web Push combines elliptic-curve agreement with the aes128gcm content encoding from RFC 8188. Here every operation is performed by WebCrypto, including the reverse calculation as the recipient.
For this app, the plaintext is a JSON object with title Chat
, body Ana: running 5 min late
and URL /rooms/42. JSON is our application’s format, not a requirement of the push protocol. The encryption layer takes UTF-8 bytes. A service worker could instead receive text, CBOR or any other agreed byte format.
Agree on a secret without sending it
The subscriber already has a private scalar and a public point U = uG on P-256. The application server generates a fresh ephemeral key pair, private scalar a and public point A = aG. Its ECDH operation with U yields the same shared secret as the recipient’s ECDH operation with A, because a(uG) = u(aG). For P-256, WebCrypto exposes the 32-byte x-coordinate of that shared point as the ECDH secret.
The server knows its fresh private key and the subscription’s public point. The browser knows its subscription private key and receives the server’s fresh public point inside the encrypted-body header. The push service sees the public points but lacks either private scalar. Fresh sender keys also keep independent sends from reusing the same ECDH agreement. They do not give full forward secrecy against later compromise of the long-lived receiver key plus the subscription auth secret.
Two derivations, deliberately separated
ECDH output is not used directly as an AES key. First, HKDF-SHA-256 combines it with the subscription’s 16-byte auth secret. HKDF has an extraction stage, HMAC with the salt as key, and an expansion stage with an explicit context string. The first context is "WebPush: info" || 00 || ua_public || as_public. Its exact spelling, terminating zero byte and public-key order matter.
The resulting 32-byte IKM feeds a second HKDF extraction with a new random 16-byte message salt. Two expansion labels then produce a 16-byte content encryption key, CEK, and a 12-byte nonce. Each ASCII label ends in 00. Since all the desired outputs fit within one SHA-256 block, expansion is simply HMAC over the label and the 01 block counter, truncated to the required length.
shared = ECDH(as_private, ua_public) // 32 bytes
PRK_key = HMAC-SHA-256(auth, shared)
key_info = "WebPush: info" || 00 || ua_public || as_public
IKM = HMAC-SHA-256(PRK_key, key_info || 01) // 32 bytes
PRK = HMAC-SHA-256(salt, IKM)
CEK = HMAC-SHA-256(PRK, "Content-Encoding: aes128gcm" || 00 || 01)[0:16]
NONCE = HMAC-SHA-256(PRK, "Content-Encoding: nonce" || 00 || 01)[0:12]
record_plaintext = UTF8(message) || 02 || zero_padding
record = AES-128-GCM(CEK, NONCE, record_plaintext, AAD=empty)
body = salt || uint32be(rs) || 41 || as_public || recordGeneral RFC 8188 records XOR the base nonce with a record sequence number. Web Push uses exactly one record, numbered zero, so this XOR leaves the nonce unchanged. The additional authenticated data for AES-GCM is empty. The derivation binds the public keys and salt into the key schedule; there is no separate Web Push AAD header to invent.
An 86-byte header, then one authenticated record
The body begins with the salt, a four-byte unsigned big-endian record size, one byte of key identifier length and the 65-byte sender public key. That is 16 + 4 + 1 + 65 = 86 bytes. For a record size of 4096, the bytes are 00 00 10 00. The identifier length is decimal 65, hexadecimal 41. The public point’s own first byte is 04; do not confuse it with the length byte before it.
Before encryption, append the final-record delimiter 02 to the application bytes, followed by any chosen zero padding. AES-128-GCM encrypts that sequence and appends a 16-byte authentication tag. The delimiter is encrypted too. The recipient authenticates first, then scans backwards past zero padding and requires 02. A different delimiter, an invalid point or a bad GCM tag makes the message unusable.
Computing…Computing…Computing…Computing…Computing…Computing…Inspect the full key schedule (local teaching keys)
- ECDH shared secret · 32 bytes
- PRK_key · HMAC(auth, shared)
- key_info · label, 00, ua_public, as_public
- IKM · 32 bytes
- PRK · HMAC(salt, IKM)
- CEK · 16 bytes
- Nonce · 12 bytes
- Plaintext + 02 + zero padding
Deriving keys with WebCrypto.
The RFC’s Appendix A uses the sentence When I grow up, I want to be a watermelon
with fixed input keys and salt. The included test checks the shared secret, both PRKs, IKM, CEK, nonce, complete header and ciphertext against that vector exactly, then decrypts it with the recipient private key. This catches label, byte-order and padding errors that a sender-and-receiver round trip could otherwise share.
The portable encrypted-body allowance is 4096 bytes. Subtract the 86-byte header, one delimiter and 16-byte tag and you have 3993 bytes for application plaintext plus optional zero padding. It is a byte count, not a JavaScript string length. Emoji and non-ASCII letters can consume several UTF-8 bytes each. The rs value must exceed the ciphertext record length, including tag; it is not the size of the complete HTTP body.
Padding can hide some length differences by rounding payloads into buckets, at a cost to that budget. It cannot hide which subscription receives messages, when messages arrive, the urgency or Topic headers, or their total padded size. The application server still sees Ana’s plaintext in this design. To hide it from your own backend, the chat application needs a separate end-to-end messaging protocol before Web Push encryption even begins.
Encrypt for the subscriber, authenticate the server separately, and count the envelope’s header and tag inside the 4 KB body budget.
A short-lived worker, a lasting notification
Set the sealed envelope aside for a moment and look at its destination. When the phone receives it, the user agent parses the header, repeats the key derivation with the subscriber private key, verifies the tag and decrypts the payload. Your service worker does not implement that cryptography. Its push event receives the already-decrypted application bytes.
If no worker instance is running, the browser starts one from the active registration. Top-level worker code runs, installs event listeners and then receives the event. That makes top-level listener registration essential: a handler installed only after an unrelated asynchronous setup can miss the event that started the worker. Avoid treating global variables as durable state; another event may arrive in a fresh instance.
event.data is a PushMessageData object for a message with data. Its json() method parses the bytes as JSON. It is synchronous and can throw for malformed JSON. In our application, the server controls a small validated schema with a title, body and fixed application route. A production handler needs a deliberate invalid-payload policy that still meets its user-visible promise, rather than silently swallowing parse errors.
The promise is part of the event
event.waitUntil(promise) tells the browser that asynchronous work belongs to the event. Call it during event handling and pass the notification promise, or a promise chain that eventually returns it. Simply starting an async function does not keep an event alive: without the lifetime extension, the browser may terminate the worker before the work finishes. Even with it, browsers impose practical execution limits; push is a short task, not a perpetual background process.
self.addEventListener("push", event => {
const message = event.data.json(); // This app's validated payload schema.
event.waitUntil(self.registration.showNotification(message.title, {
body: message.body,
tag: "room42",
renotify: true,
badge: "/assets/chat-badge.png",
actions: [{ action: "open", title: "Open chat" }],
data: { url: "/rooms/42", messageId: "msg-1041" },
}));
});
self.addEventListener("notificationclick", event => {
event.notification.close();
event.waitUntil((async () => {
const url = new URL(event.notification.data.url, self.location.origin);
if (url.origin !== self.location.origin) return;
const windows = await clients.matchAll({ type: "window", includeUncontrolled: true });
const existing = windows.find(client => client.url === url.href);
if (existing) return existing.focus();
return clients.openWindow(url.href);
})());
});showNotification() asks the platform to create a persistent notification associated with the registration. The tag lets a newer notification replace an older one for the same conversation. renotify: true, used with a nonempty tag, requests renewed attention on replacement. It does not override silent mode. actions describes optional buttons, badge supplies a small platform-specific image, anddata stores application metadata for a later click.
Not every platform renders every option. In particular, action buttons, badge treatment, sound and lock-screen previews depend on the browser, device and user settings. The API describes a notification; the OS controls its presentation. Put the essential message in the title and body, so the notification remains useful when extra actions are absent.
A click starts another event, notificationclick, possibly in another worker instance. Close the notification, inspect its data and extend this event with waitUntil() too. Search window clients for the exact room URL and focus a match; otherwise use clients.openWindow(). Opening a window is allowed in the activation context of the notification click. Validate navigation targets so untrusted message data cannot redirect a user to an unrelated origin.
Ana: running 5 min late
A local event model; no service worker or OS notification is registered.
What if no notification appears?
Classic Web Push is not a general-purpose silent wake channel. WebKit documents revocation of subscriptions whose push handlers fail to show notifications. Chromium has used generic browser-generated notificationswhen an application fails to display one. Firefox documents quota rulesfor pushes that do not generate notifications. These are browser policies, not one universal fixed penalty. Write the handler to fulfill the visible promise rather than depending on any particular fallback.
Declarative Web Push changes the fallback model. WebKit shipped it for Home Screen web apps in iOS and iPadOS 18.4; Safari 18.5 added it on macOS, as documented in WebKit’s release notes. The payload describes a proposed notification directly. An immutable declarative push is displayed without waking the worker. A mutable one permits worker processing and retains the proposed notification as a fallback. WebKit also exposes subscription management without an installed worker in this model.
{
"web_push": 8030,
"notification": {
"title": "Chat",
"body": "Ana: running 5 min late",
"navigate": "https://chat.example/rooms/42"
}
}The numeric web_push: 8030 marker selects declarative parsing. The nested notification needs a title and anavigate URL for activation without JavaScript. Withmutable omitted or false, the user agent displays this notification directly, even if a worker is registered. That avoids waking JavaScript merely to copy the supplied title and body into a notification.
To let a worker customize the alert, add "mutable": trueat the top level, alongside web_push andnotification. It belongs outside the notification dictionary. An eligible worker can then receive a push event and propose a replacement; if it throws, fails to display one or is unavailable, the supplied notification still provides the fallback. This is the payload used by the lab’s handler-failure path. The field and default are defined in thePush API’s declarative message algorithm; WebKit’s published examples use the same web_push,notification and navigate names.
{
"web_push": 8030,
"mutable": true,
"notification": {
"title": "Chat",
"body": "Ana: running 5 min late",
"navigate": "https://chat.example/rooms/42"
}
}Both variants keep Web Push encryption, VAPID and HTTP delivery. They describe user-visible output rather than permission for hidden work. Use feature detection and a compatible payload handler when serving browsers with different support.
The registration outlives the worker, and the notification outlives the event. waitUntil connects asynchronous work to the short lifetime in between.
Hand the envelope to a push service
Return to Chat’s backend. It has stored the recipient’s subscription, signed a VAPID token for the endpoint origin and encrypted the JSON into one binary body. Now it makes an HTTPS POST to that exact endpoint. This is the application-server side of RFC 8030. The server does not connect to the phone’s changing IP address, and the recipient need not expose an inbound port.
The body is raw binary, not its base64url representation. Base64url is useful for the keys in subscription JSON and for token segments, but encoding the whole encrypted body again would send different bytes and waste space. The header Content-Encoding: aes128gcm tells the receiver which content coding is present. A content type of application/octet-stream is appropriate for that encrypted representation.
Delivery instructions live outside encryption
TTL is required. It is a nonnegative integer number of seconds the service may retain the message. A five-minute chat update might use TTL: 300. If the user reconnects after that window, the server would rather they refresh the conversation than receive a stale running five minutes late
notification. The service may enforce a shorter retention period; the requested value is an upper limit, not a storage guarantee.
TTL: 0 asks for delivery only if it is possible immediately, without offline storage. That is useful for very transient information, but it discards the main advantage of store-and-forward delivery. It also does not make the request synchronous with display: acceptance, device receipt and notification presentation remain separate events.
Urgency can be very-low, low, normal or high. It tells the service how time-sensitive the message is, so delivery can fit power constraints. It is not an access-control bypass or a guaranteed latency class. A chat mention might justify more urgency than an unread-count refresh, while an expired meeting reminder should not wake a phone at all.
Topic gives a waiting message a replacement identity within one subscription. A newer envelope with the same Topic replaces its predecessor in the service’s queue. Use at most 32 URL-safe base64 characters. A room identifier such as room42 is enough for this demonstration. The service can compare Topic strings without understanding the encrypted JSON.
- Plaintext
- —
- Body / portable limit
- —
- HPACK + frame headers
- —
Exact HTTP/2 frame bytes (hex)
HEADERS uses literal names and values without Huffman coding or indexing. Stream 1, END_HEADERS; DATA carries END_STREAM.
Preparing a local request. Nothing is sent.
HTTP/2 uses binary frames and lowercase field names. The :method, :scheme, :authority and :path pseudo-fields replace an HTTP/1.1 request line and Host header. The builder encodes its header block with HPACK literal names and values, with no Huffman coding or dynamic indexing. This intentionally simple encoding gives an exact, reproducible count for the fields shown, even though real clients often compress them more efficiently.
The first frame is HEADERS on stream 1 with END_HEADERS set. The second is DATA with END_STREAM set. We assume the HTTP/2 connection is already established; its client preface and SETTINGS exchange precede these bytes. A different live client may split frames differently or reuse another stream number without changing the push semantics.
| Response | What it establishes | Server action |
|---|---|---|
| 201 + Location | Message accepted; Location identifies its resource | Record acceptance separately from display or reading |
| 404 / 410 | Unknown or gone subscription, depending on service | Retire that endpoint |
| 413 | Body exceeds the service’s allowance | Reduce payload size |
| 429 | Request rate is excessive | Honor Retry-After and back off |
| 400 | Malformed request; may also reject identical VAPID and ECDH keys | Repair header syntax and body format; use separate signing and key-agreement keys as required by RFC 8292 §3.2 |
| 401 | Missing authorization, depending on service | Supply VAPID authorization and validate audience, expiry and signature |
| 403 | Invalid VAPID authentication, including a key that differs from the subscription’s applicationServerKey | Sign with the key bound to that subscription; check claims and signature. During rotation, obtain a subscription bound to the new key |
The success response does not mean the phone is online, the worker ran or a human read the message. RFC 8030 defines optional receipt mechanisms, but support and meaning must be checked with the service. For an application read receipt, the chat itself needs an authenticated acknowledgement after the recipient actually opens or reads the room.
Wait for the phone, not for a page
The service has accepted Ana’s envelope. It now owns a delivery problem rather than a JavaScript problem. It maps the endpoint to a subscriber, applies retention and replacement policy, and waits for a usable route to the device. If the phone is temporarily unreachable, the ciphertext can stay queued until the TTL runs out. That is the store-and-forward part of Web Push.
Suppose Ana first says she is five minutes late, then immediately corrects herself to two minutes. If both requests use Topic room42 while the phone is offline, only the newest waiting envelope needs to survive. The push service can do that replacement without decrypting either message. If your product must preserve both events, omit the shared Topic and keep the authoritative conversation history on your server.
Replacement is scoped to a subscription and a waiting message. It cannot retract a notification already displayed, and it is not a global deduplication key. When delivery has already happened, the next push can create a second event. The worker’s notification tag handles a different replacement boundary: the notification UI on the device. Using the same room identifier for both is convenient, but their mechanisms and lifetimes remain separate. Replacement is applied before retention: if a new TTL: 0 message uses the same Topic while the phone is offline, it removes the old waiting envelope and then expires itself. Neither envelope remains for the next reconnect.
- Model clock
- 0 s
- Waiting envelopes
- 0
- Replaced / expired
- 0 / 0
Phone offline. Queue an update, then queue another with the same Topic.
One subscription, server-requested TTL, no service-side shortening. Reconnect is an instantaneous delivery opportunity in this model.
The persistent connection belongs to a platform
On Android devices with Google Play services, FCM supplies a shared platform connection instead of requiring every application to maintain one. Android’s Doze guidance explicitly recommends FCM for this purpose. Chrome’s use of FCM fits that architecture, while browser and device configurations without Google Play services can use different paths. Do not generalize one Android implementation into a requirement of Web Push.
Apple’s Web Push implementation uses APNs, the same infrastructure used for native push notifications. The device maintains platform-level reachability, and the browser associates a received Web Push envelope with the right web app. The server still uses the standard Web Push request and subscription; it does not need to send the native APNs JSON API format or obtain native-app credentials just to deliver Safari Web Push.
Queue, route, expire. Forward the encrypted envelope.
Browser validates and decrypts its Web Push messages before handing plaintext to application code.
Heartbeats are a reachability cost
A TCP connection can look open while a NAT or firewall has discarded its mapping. Network transitions can also replace the phone’s address. Push clients therefore need some combination of traffic, heartbeats, reconnect logic and session restoration to discover failure and keep routes useful. The exact keepalive interval is an implementation choice influenced by network conditions, not a Web Push constant.
FCM’s network documentation describes connection and firewall requirements, including long-lived connections. It does not establish a universal byte-level FCM envelope or heartbeat schedule for every Chrome release. APNs likewise exposes documented service behavior without turning its private device transport into the RFC 8030 request format. The two hops must not be drawn as one end-to-end HTTP/2 stream.
Power policy adds another queue boundary. Android can defer background work during Doze. FCM documents that normal-priority delivery can be delayed and high-priority, user-visible messages can receive a short opportunity to run. FCM’s native priority settings and Web Push Urgency belong to different APIs; there is no portable promise that a particular Urgency value maps to a specific wake schedule on every device.
Apple’s Focus, notification preferences, network availability and system power management can similarly affect when or how the user sees an alert. The service can accept and route a message while the OS chooses not to show a banner or reveal its body on the lock screen. Put deadlines and fallback behavior in the product design instead of assuming that high means interrupt immediately
.
Topic, TTL and urgency help a shared courier decide what is still worth delivering. They do not replace application history or the OS’s presentation policy.
Delivery is a state machine
A sender is easier to operate when it records transitions instead of one ambiguous sent
flag. Ana’s message can be committed in the chat database, scheduled for notification, accepted by a push service, delivered to a user agent, displayed by the OS and finally opened by the user. Those are different observations, often made by different systems. Store the authoritative chat message first; push is an alert about that durable event.
Retire addresses that no longer exist
A subscription is disposable routing state. A 404 or 410 for a previously stored endpoint normally means it is time to retire that subscription according to the service’s documented response. Do not continue retrying every new chat message against it. Keep the user’s account and messages; remove or deactivate the endpoint association and let the next authenticated client visit reconcile a new subscription.
Other failures need different treatment. A 413 will not improve after waiting if you resend the same oversized body. A VAPID audience error will not improve with jitter. Check the endpoint origin, expiration, signing key and key binding before retrying authentication failures. Rate limiting and temporary server failures are the cases where a time-based retry policy makes sense.
Use exponential backoff with jitter so many senders do not retry in synchronized waves. One simple policy picks uniformly between zero and min(300, 2n) seconds for retry index n. A supplied Retry-After is a lower bound for that retry; it may be a delay in seconds or an HTTP date. The lab uses a 60-second example. Check the message’s application deadline too: retrying a time-sensitive alert after its relevance window wastes both service capacity and battery.
No retries attempted.
A connection failure before the response is especially awkward. The service might have accepted the request before your connection died. Retrying can duplicate delivery. Use application message identifiers for deduplication where appropriate, use a stable notification tag for replacement, and design alerts so a repeat does not perform a second destructive action. An alert should lead to a server-validated state change, not itself authorize one.
Rotate the right key at the right boundary
There are three key lifetimes. The subscriber’s ECDH pair and auth secret belong to a subscription. The VAPID signing key identifies your application server and may bind many subscriptions. The sending ECDH key and salt are fresh for each encryption. Losing track of these lifetimes causes migrations that look like random delivery failure.
For planned VAPID rotation, keep the old signing key available for subscriptions bound to it while clients establish subscriptions under the new key. Store a key version alongside each endpoint. A client may need to unsubscribe and subscribe again with the new application key; it cannot just change the server’s recorded public key. If the old private key is compromised, retaining it for convenience is no longer the right tradeoff: revoke and re-establish the affected route.
At every normal application visit, check permission and subscription state, then update the authenticated account-device association. Reconcile sign-in and sign-out explicitly. On iOS and iPadOS, the Home Screen web-app requirement introduced in 16.4 remains a deployment consideration documented by Apple’s Web Push guide. Feature detection and clear installation guidance are more useful than showing a nonfunctional permission button in an unsupported context.
Confidential content still has visible metadata
The push service cannot decrypt this message, but it can see when the server contacts it, which endpoint is addressed, the body length and the unencrypted delivery headers. A meaningful Topic can reveal a stable conversation grouping. Prefer opaque identifiers over usernames or message text. Logs and analytics deserve the same care: a full subscription object includes the auth secret and should not be copied into ordinary request logs.
Encryption also ends before the lock screen. The intended user agent sees plaintext, and the OS may show its preview to someone nearby. For sensitive chats, consider a generic New message
notification, with details available only after opening the application. The right preview policy is a product and user-setting decision; adding another TLS layer cannot solve it.
Retry temporary conditions, repair invalid requests and retire dead subscriptions. Keep delivery observations separate from the chat’s source of truth.
Count the bytes on one real hop
We can now descend from the application request to the server’s outgoing bytes. Choose one specific hop: Chat’s server to the push service over an established HTTP/2 connection inside TLS 1.3. We know the exact encrypted Web Push body and the exact HPACK encoding produced above. The ledger below counts this hop; FCM and APNs use a separate device transport.
For the default compact JSON, the application has 67 UTF-8 bytes. The encryption header adds 86, the final delimiter adds one and AES-GCM adds 16, producing a 170-byte body. Change the request builder and the calculator below uses the new body and header block. If you fill the portable budget, the body becomes exactly 4096 bytes while the other layers still add overhead around it.
HTTP/2 framing comes first
Every HTTP/2 frame begins with a nine-byte header: a 24-bit payload length, an eight-bit frame type, eight flag bits and a 31-bit stream identifier preceded by a reserved bit. A DATA frame is type zero. END_STREAM is flag 01. With a 170-byte body on stream 1, its header is 00 00 AA 00 01 00 00 00 01. The first three bytes count only the frame payload.
- Payload length170 bytes, unsigned big-endian
- TypeDATA
- FlagsEND_STREAM; no padding
- Stream identifierReserved bit zero, stream 1
The preceding HEADERS frame adds its own nine bytes plus the HPACK block. Header compression depends on the connection’s table state, indexing decisions and Huffman coding, so there is no universal Web Push headers cost X bytes
. Our builder chooses explicit literals, making its size concrete. A real connection’s cookie-free push request can still carry a substantial VAPID header compared with a short chat body.
TLS wraps the stream, not the push object
For this example, put both HTTP/2 frames into one unpadded TLS 1.3 application-data record using an AEAD with a 16-byte tag. TLS adds a five-byte outer record header, one encrypted inner content-type byte and the tag: 22 bytes total. TLS 1.3’s outer type is application_data, hexadecimal 17, and its legacy record version is 03 03. The header length covers the encrypted inner plaintext and authentication tag, excluding the five-byte header itself.
TLS has its own traffic keys and sequence-number-based nonces. They are completely separate from the Web Push CEK and nonce. The resulting double encryption is useful: TLS protects the request from network observers; Web Push keeps the payload confidential after TLS terminates at the push service. The latter can read the HTTP fields while the chat content remains sealed.
Waiting for the request builder’s actual encrypted bytes.
Established HTTP/2 + TLS 1.3, AES-GCM 16-byte tag, one unpadded TLS record, full-size TCP segments, no ACK-only packets or retransmissions. Counts cover server → push service.
The TLS record is just bytes in a TCP stream. At a 1500-byte path MTU, IPv4 without options and TCP without options leave 1460 bytes per segment. With a 40-byte IPv6 header, that falls to 1440. TCP timestamps commonly increase the TCP header from 20 to 32 bytes in a padded option layout, reducing the payload capacity further. The calculator sums the selected headers once per data-bearing segment.
These counts assume full-sized segments where possible, one record and no retransmissions. They exclude TCP acknowledgements in the opposite direction, the TLS handshake, HTTP/2 setup, DNS, Ethernet or Wi-Fi framing and any tunnels. Real TCP can split or combine writes differently. A browser’s read() boundaries have no obligation to match TLS records, HTTP/2 frames or push payloads.
The relevant framing rules are in HTTP/2, RFC 9113, HPACK, RFC 7541, and TLS 1.3, RFC 8446. The next hop is a different connection with its own framing and encryption. A 4 KB Web Push body is therefore a portable application limit, not the total number of bytes paid by a radio.
Count each layer on a named hop. Body bytes survive forwarding; HTTP/2, TLS and TCP boundaries belong to that connection.
Wake a radio, then put it back to sleep
At the bottom, the phone has a persistent connection
does not mean its application CPU spins forever or its radio continuously transmits. Connection state can persist while the device spends much of its time in low-power states. The transport is a logical relationship; radio activity is scheduled physical work.
A TCP connection is not an RRC state
The cellular access link has its own state machine, Radio Resource Control (RRC). In LTE attached to the EPC core, RRC_IDLE means the device can monitor paging without an active RRC connection to the base station. RRC_CONNECTED gives the network an established context for scheduling data. Releasing that radio connection need not close the TCP socket: the IP session and remote endpoint can remain while radio resources are rebuilt for the next burst. These LTE states and transitions are specified in3GPP TS 36.300 §7.2.
5G NR also has RRC_INACTIVE. The device and radio network retain context while ordinary active data transfer is suspended. Incoming traffic can trigger RAN paging, followed by an RRC resume rather than rebuilding all that context from idle. An idle device instead needs connection establishment. The ordinary resume path is defined inTS 38.300 §9.2.2; small-data procedures provide additional paths for eligible traffic. Being reachable through any of these states says nothing about whether Chat’s tab or the application processor is currently running.
The modem wakes to listen before the app wakes to run
Paging uses discontinuous reception, DRX. Instead of listening continuously, the modem monitors the paging occasion assigned to the device within each configured cycle. In NR, a paging occasion can contain several control-channel monitoring occasions; it is not necessarily one instantaneous signal.TS 38.304 §7.1defines this selection. Take an illustrative cycle of 128 radio frames: with the 10 ms frame duration inTS 38.211 §4.3.1, that cycle lasts 1.28 seconds. The modem listens during its assigned occasion, then can sleep between occasions. The configured cycle and monitoring pattern determine the wait, not a timer in the website.
Follow Ana’s envelope on an idle cellular link. Downlink traffic reaches the carrier’s core, which triggers paging toward the serving area. At its listening opportunity the modem recognizes a page for this device, performs access signalling and establishes or resumes the radio connection. The base station can then schedule downlink data. If the device was alreadyRRC_CONNECTED, connected-mode DRX can instead gate when it monitors scheduling; it does not need this idle-to-connected paging path. The scheduling, channel decoding and link-layer retransmissions all happen before the browser can inspect a Web Push header.
The modem and application processor have separate work to do. The modem can service radio listening opportunities while the application processor sleeps. When received data needs host processing, platform-specific interrupts or interprocessor messaging can wake the application processor. Host networking and the platform push client then process and route the envelope; the browser decrypts it and schedules the worker. Which networking tasks are offloaded, exactly which processor wakes first and how long it stays awake depend on the chipset and OS. None of that requires the closed chat page’s JavaScript to have been running.
The carrier sees network-layer traffic, not the semantic fact that Ana is late. A packet addressed to an established push connection is simply data to deliver. The modem’s protocol stack handles radio control, link-layer framing, scheduling, error correction and retransmission. The browser and worker sit far above those mechanisms. A page does not acquire permission to set cellular wakeup timings by choosing Urgency: high.
Small payload, potentially larger wake cost
The energy cost of an alert includes more than receiving 170 body bytes. Signalling, access and resume work cost energy before useful data arrives. After the last packet, the network may retain the RRC connection for anticipated follow-up traffic. Connected-mode DRX can reduce listening during that interval, but the modem may still consume more than its lower-power baseline. A later release can return LTE to idle or suspend NR into inactive. This post-traffic cost is the radio tail. Its duration and power depend on network timers, DRX configuration and hardware; a persistent TCP socket does not specify them.
Etail ≈ (Ptail − Psleep) × ttail
This constant-power approximation isolates the extra energy after the last packet. A real trace integrates the changing power above the sleep baseline. A second alert during that tail may extend the higher-power interval; batching both alerts into one burst can let the modem return to sleep sooner. The application processor also has its own wake and execution cost, so the RF byte count alone cannot predict the device’s energy use.
Shared connections help because the system can coordinate maintenance traffic and background delivery. Batching low-priority work can reduce the number of separate wakeups. Urgent, user-visible work can justify waking sooner. The same engineering tension appears at every level: more immediacy means fewer opportunities to combine work and sleep. Short payloads help, but deleting unnecessary notifications can save more than shaving a few bytes from a header.
The CPU does not need to keep your chat JavaScript running while it waits.
A causal model of cellular delivery, without invented radio timings. Wi-Fi uses a different link and power-save protocol.
Wi-Fi reaches the same application outcome through a different link. Access-point buffering, beacon timing and client power-save behavior determine when a sleeping station receives traffic. A network switch from Wi-Fi to cellular may break the old TCP path and force the platform push client to reconnect. Store-and-forward delivery bridges that interruption only while the envelope remains valid.
Public platform documentation supports the broad power model, while modem firmware, push-client scheduling and vendor-private framing remain implementation-specific. Android’s guidance on server-initiated traffic explains why avoiding periodic application polling matters. For radio architecture,3GPP TS 38.300, Release 18 describes 5G NR states and discontinuous reception. Neither source gives a universal latency guarantee for a Web Push notification.
Once the protected device channel delivers the envelope, the platform routes it to the browser. The browser checks the 86-byte header, derives the same CEK and nonce, verifies the GCM tag and strips the final delimiter and padding. It starts the registered worker and dispatches the decrypted JSON. The worker extends the event lifetime with waitUntil() and asks to display Chat. The OS applies the user’s notification and privacy settings.
The lock screen can now say Ana: running 5 min late
. The tab was never secretly left open. A subscription preserved the address and receiver keys, a signed token identified the sender, an authenticated envelope protected the content, a shared courier waited for reachability, and a short event turned bytes into a notification. When the user taps it, a different event brings the chat page back into existence.
Background reachability comes from coordinated platform and network machinery. The web app borrows a short opportunity to notify, then lets the device sleep again.
End of Web Push · 10 levels, Idea to Silicon
Where to next
Next in Web and networking · 11 of 12
How HTML becomes pixels
One product card, from arriving bytes to a glowing display. Build its DOM, resolve its CSS, and find out why moving a badge can cost a frame.
Practical notes
Send a Web Push notification from Node
Generate a VAPID identity, save a browser subscription, and build an encrypted push request with Node crypto before sending it to the subscription endpoint.