10 min read
Push notifications with APNs: the path from token to delivery
The APNs path from token registration to delivery, including payload limits, collapse behavior, and diagnosing silent failures.
On this page13
A remote notification travels through four places: the device token, your server, APNs, and a device that decides on its own whether the notification appears. Three of those are under your control. The fourth is where most "push is broken" reports come from, and it is the one no test on your side covers.
This is the path end to end, with the failure modes that cost the most time in production.
1. The whole path in one pass
The app asks the system for a token. The system hands back an opaque string tied to this install. The app sends that string to your backend. Your backend stores it against a user. Later, the backend sends an HTTP/2 request to api.push.apple.com with the token in the URL, a small JSON body, and a few headers. APNs either accepts the request or returns a reason. If accepted, delivery is APNs's problem from then on.
Two consequences follow immediately. Your backend needs the token before it can do anything, so registration is a required step in every flow that ever sends a push. And APNs accepting a push says nothing about whether it appeared on screen.
2. A token identifies an install, not a person
UIApplication.shared.registerForRemoteNotifications()The token arrives in the app delegate, as bytes:
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let token = deviceToken.map { String(format: "%02x", $0) }.joined()
Task { await pushService.register(token: token) }
}Send it to the server in hex. Do not keep it in UserDefaults as the source of truth, do not format it with dashes, and do not assume it is stable.
Sandbox and production tokens are different strings for the same device. A debug build registers against the sandbox environment and gets a token that api.push.apple.com will reject with BadDeviceToken. That mismatch is the first thing to check when pushes work in development and fail in TestFlight.
3. Tokens rotate, and the table has to admit it
A new token appears after a reinstall, a device restore, occasionally after an OS update, and whenever the person signs into a different Apple Account on that device. The old token does not always go away cleanly, so the server side needs to handle several tokens per person without assuming one.
Keep a row per install, keyed by the token plus its environment:
device_token text, unique with environment
environment sandbox | production
user_id foreign key
platform ios | watchos | macos
app_version last seen
last_seen_at timestamp
invalidated_at timestamp, null while activeThree rules make the table usable. When the app registers a token you already have, update last_seen_at instead of inserting. When registration sends a token you do not have for that user, keep the old row until APNs tells you it is gone. And when APNs returns 410 Unregistered, set invalidated_at and stop sending to that row. Deleting the row immediately loses the history you need to explain a delivery problem three weeks later.
4. Authenticate with a key, not a certificate
APNs accepts either a certificate or a JWT signed with a .p8 key from the developer portal. Use the key. It does not expire yearly, it works for every app in the team, and it is one secret instead of one per app and environment.
The JWT is ES256 with kid set to the key ID and iss set to the team ID. Cache it for an hour and refresh at most every 20 minutes. Requesting a new JWT more often returns TooManyProviderTokenUpdates, and the limit is per key, so a bug in one service degrades every app that shares it.
curl --http2 \
--header "authorization: bearer $JWT" \
--header "apns-topic: com.example.app" \
--header "apns-push-type: alert" \
--header "apns-priority: 10" \
--header "apns-id: $(uuidgen)" \
--data @payload.json \
https://api.push.apple.com/3/device/$DEVICE_TOKENA successful send returns 200 with an apns-id header and nothing else. Keep the header on --http2. HTTP/1.1 to APNs fails in a way that looks like a network problem.
5. The headers decide what happens to the message
| Header | What it does | Common mistake |
|---|---|---|
apns-topic | Routes to the app; must match the bundle ID | Using the wrong suffix for VoIP or Live Activities |
apns-push-type | Declares alert, background, voip, liveactivity, and others | Omitting it; APNs rejects the request |
apns-priority | 10 for immediate, 5 for power-considered, 1 for background | Sending background pushes at 10, which is rejected |
apns-expiration | UNIX timestamp, or 0 to discard if undeliverable | Leaving 0 on anything that matters later |
apns-collapse-id | Replaces a pending notification with the same id | Reusing one id for unrelated messages |
apns-expiration is the one people skip. With 0, APNs tries once and drops the message if the device is offline. For a chat message that is correct. For "your prescription is ready", it is not: set an expiry in hours and let APNs hold it.
6. The payload is 4 KB, and that is the whole budget
{
"aps": {
"alert": {
"title": "Order shipped",
"body": "Arriving Tuesday"
},
"badge": 3,
"sound": "default",
"thread-id": "order-4417",
"category": "ORDER_UPDATE",
"mutable-content": 1,
"relevance-score": 0.8
},
"orderID": "4417"
}The limit is 4096 bytes for the entire body, and custom keys count. A common failure is a payload that grows because someone adds a full item list for the notification service extension to render. At some point it crosses the limit and APNs returns PayloadTooLarge, usually right before a marketing push.
Send identifiers, not content. The service extension can fetch the image and the extra text when it runs, and it can fail without breaking the notification if you write it that way.
Localize with loc-key and loc-args rather than sending a pre-rendered string. It costs fewer bytes and it respects the device language instead of the server's guess.
7. Collapse IDs and the notifications you should not send
apns-collapse-id is at most 64 bytes. A push with an id that matches one still pending replaces it rather than adding a second banner. For a live sports score or a file transfer progress note, that is the difference between one useful notification and forty.
The inverse mistake is reusing a collapse id across unrelated messages, which silently drops the earlier one. Scope it to the entity: order-4417-status, not orders.
Grouping is a different mechanism. thread-id controls how notifications stack in Notification Center; collapse controls what reaches the device at all.
8. Background pushes have their own rules
A push with content-available: 1 and no alert wakes the app briefly to fetch. It requires apns-priority: 5, and it comes with limits worth designing around:
- delivery is not guaranteed, and it may be delayed for hours
- the system coalesces them and keeps roughly one pending per app
- a force-quit app does not receive them until the person opens the app again
- Low Power Mode can suppress them entirely
That makes background pushes an accelerant for sync, never the mechanism that makes sync correct. If the app only reconciles data when a background push arrives, users will see stale screens and report it as data loss.
9. When APNs says no
APNs returns a JSON body with a reason. The ones that matter:
| Reason | What it means | What to do |
|---|---|---|
BadDeviceToken | Token is malformed or from the other environment | Check sandbox vs production |
DeviceTokenNotForTopic | Token belongs to a different bundle | Fix the topic or the token row |
Unregistered (410) | Install is gone | Invalidate the token, stop sending |
PayloadTooLarge | Body over 4096 bytes | Trim the payload, fetch the rest |
BadTopic / MissingTopic | Topic header wrong or absent | Verify the header and suffix |
ExpiredProviderToken | JWT older than an hour | Refresh and retry once |
TooManyRequests | Rate limited for this device or topic | Back off, then retry |
ServiceUnavailable / Shutdown | APNs is having a bad day | Retry with backoff |
Two habits keep this manageable. Retry 429 and 503 with exponential backoff and a cap, and never retry 410, BadDeviceToken, or PayloadTooLarge. Those are deterministic, and retrying them turns one bad row into a queue full of failures.
Log the apns-id from the response with the send attempt. When someone asks whether a specific notification went out, that header is the only join key you get.
10. Delivered is not the same as visible
Once APNs accepts the push, the device decides. These are the reasons a push is delivered and never shown:
- the person denied notification permission, which returns nothing to your server
- provisional authorization sends it quietly to Notification Center with no banner
- a Focus mode or the scheduled summary holds it
- the app was in the foreground and the delegate did not opt into displaying it
- the payload used
interruption-level: passive, which means no banner by design
For the last case:
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification
) async -> UNNotificationPresentationOptions {
[.banner, .sound, .badge]
}Time Sensitive delivery needs the matching entitlement and an interruption-level of timeSensitive. Critical alerts need Apple's approval and are not something to plan a feature around before you have it.
Permission itself is a product decision. Ask after the person has done something worth notifying them about, and keep a settings entry that shows the current state. An app that asks on first launch and gets denied spends the rest of its life unable to reach that person.
11. What to instrument
Three numbers cover most incidents: sends accepted by APNs, notifications displayed, and taps. Accepted minus displayed is the delivery gap, and it is almost always one of the four reasons above.
Log per attempt: token prefix, environment, topic, push type, status code, reason, and apns-id. Without environment in that log, every sandbox incident looks like a production one.
12. Test the parts the simulator cannot test
xcrun simctl push is useful for layout and for the service extension, and it bypasses APNs entirely. It will not catch a bad topic, an expired JWT, or a sandbox token in production.
So test in three places: simctl for payload shape, a debug build against the sandbox endpoint for auth and headers, and a TestFlight build for the real thing. The TestFlight pass is where environment mistakes surface, which is exactly why it belongs in the release checklist and not in a spot check after users complain.
13. Treat it as an interruption budget
Push is the only channel where a mistake reaches a person's lock screen. That argues for fewer, better notifications: one per meaningful event, collapse ids on the noisy ones, an expiry that means something, and no send at all when the app could show the same information on next open.
The plumbing is a day of work done properly. The judgment about what deserves an interruption takes longer, and it decides whether people keep the permission on.