Push Notifications for Mobile Apps

Khimananda Oli 7 min read Virtualization
Push Notifications for Mobile Apps

By Khimananda Oli | Last reviewed: August 2026

Delivering push notifications for mobile apps reliably requires more than calling a vendor API; it demands a secure backend proxy, proper token lifecycle management, and observable delivery pipelines. Many teams struggle because they treat notifications as a fire-and-forget feature rather than a distributed system requiring the same rigor as any other production service. This guide covers the end-to-end architecture needed to send messages safely at scale while maintaining user trust and regulatory compliance.

How do push notifications for mobile apps actually work?

Understanding the data flow is critical before writing code. The ecosystem involves three distinct actors: your application server, the platform gateway (Apple or Google), and the client device. Your server never communicates directly with the phone; instead, it authenticates with the gateway using cryptographic credentials and submits a payload containing the target token and message content. The gateway then handles the final-mile delivery over persistent connections optimized for battery life.

App BackendToken Store + QueueAPNs GatewayiOS / macOSFCM GatewayAndroid / WebMobile DeviceUser Notification
High-level architecture for push notifications for mobile apps showing backend-to-gateway-to-device flow

A common mistake in early-stage implementations is storing gateway credentials on the client side. Never embed APNs keys or FCM server keys in your mobile binary. These secrets must reside only on your backend, ideally in a managed secrets store like AWS Secrets Manager or HashiCorp Vault. For deeper context on securing infrastructure secrets, refer to our guide on Kubernetes secrets management done right. The client's only responsibility is to request permission, obtain a device token, and register that token with your API.

How do you configure FCM and APNs securely?

Configuration differs significantly between platforms, but both now mandate token-based authentication over legacy key methods. Apple requires HTTP/2 with JWT signed by a private key (.p8), while Google recommends Service Account JSON for OAuth2 access tokens. Using deprecated legacy APIs exposes you to security risks and eventual service shutdowns.

Apple Push Notification service (APNs) Setup

Generate a .p8 key in the Apple Developer Portal under Keys > Create Key. Enable "Apple Push Notifications service" and download the file immediately; it cannot be retrieved again. On your backend, use this key to sign JWTs with the ES256 algorithm. Configure your HTTP client to reuse connections aggressively, as APNs penalizes excessive connection churn. Set the apns-topic header to your app’s bundle ID exactly.

<!-- Example APNs JWT Header Structure -->
{
  "alg": "ES256",
  "kid": "YOUR_KEY_ID",
  "typ": "JWT"
}

<!-- Payload Claims -->
{
  "iss": "YOUR_TEAM_ID",
  "iat": 1723800000,
  "exp": 1723803600
}

Firebase Cloud Messaging (FCM) v1 Setup

Create a Service Account in Google Cloud Console with the "Cloud Messaging" role. Download the JSON key file and load it into your backend environment variable or secret manager. Do not commit this file to version control. Use the official Admin SDK which handles token refresh automatically. When sending, always specify the android.config.priority as "high" for time-sensitive alerts to bypass battery optimization restrictions.

  • Credential Rotation: Automate rotation every 90 days minimum for both platforms.
  • Network Security: Restrict outbound egress from your notification worker to only api.push.apple.com and fcm.googleapis.com.
  • Rate Limiting: Implement exponential backoff. APNs returns 429 when overwhelmed; FCM uses standard quota errors.
  • Environment Separation: Use sandbox endpoints for iOS development builds; production tokens fail silently against sandbox servers.

How should the backend process notification queues?

Sending notifications synchronously within an API request handler is an anti-pattern that causes latency spikes and data loss during outages. Treat notification delivery as an asynchronous background job. When a business event triggers a notification, write a record to a durable queue (SQS, RabbitMQ, or Redis Streams) and return immediately to the caller. A separate worker fleet consumes these jobs, constructs the platform-specific payload, and calls the gateway API.

API ServerMessage QueueWorker PoolPlatform GatewayEnqueue JobConsumeSend RequestResponse / ErrorRetry on Failure
Async processing sequence ensuring reliable delivery for push notifications for mobile apps

Idempotency is non-negotiable. Generate a unique UUID for each notification intent before enqueuing. Store this ID alongside the delivery status in your database. If a worker crashes mid-send and restarts, checking this ID prevents duplicate messages. For high-volume campaigns, batch sends where supported (FCM supports up to 500 tokens per multicast request) to reduce API overhead. Monitor queue depth as a primary SLI; growing lag indicates worker starvation or gateway throttling. Our article on defining meaningful SLIs and SLOs provides frameworks for setting appropriate thresholds here.

Which push notification provider should you choose?

Choosing between direct gateway integration and third-party aggregators depends on team size, compliance requirements, and feature needs. Direct integration offers maximum control and lowest cost but requires significant maintenance. Aggregators simplify multi-platform support and provide advanced analytics at higher per-message costs.

CriteriaDirect (FCM/APNs)Aggregator (OneSignal/Airship)Hybrid (SNS/Firebase Extensions)
Cost at ScaleFree (gateway only)$0.003–$0.01/msgLow ($0.50/million)
Implementation EffortHigh (custom workers)Low (SDK drop-in)Medium (managed infra)
Data PrivacyFull controlVendor processes PIICloud vendor bound
Advanced TargetingBuild yourselfBuilt-in segmentsLimited
Compliance AuditYour responsibilityShared modelCloud certifications

For Nepal-based fintech or healthtech companies handling sensitive personal data under local regulations, direct integration or hybrid cloud-native options often satisfy residency requirements better than third-party SaaS vendors who may process data in unpredictable regions. Conversely, consumer apps prioritizing speed-to-market benefit from aggregator SDKs that handle token rotation and cross-platform normalization automatically. Evaluate based on total cost of ownership including engineering hours, not just per-message pricing.

How do you monitor delivery and handle failures?

Sending a notification successfully to the gateway does not guarantee user receipt. Gateways accept payloads asynchronously and discard messages for invalid tokens, uninstalled apps, or disabled permissions without immediate error feedback. You must implement feedback loops to maintain list hygiene and detect systemic issues.

Acceptance Rate98.7%Last 24 HoursInvalid Tokens1,240Pending CleanupQueue Depth45Healthy (<100)Delivery Latency Trend (ms)
Key observability metrics for maintaining healthy push notifications for mobile apps systems

Implement two feedback channels. First, parse synchronous API responses for immediate errors like malformed payloads or auth failures. Second, poll or subscribe to asynchronous feedback services: APNs Feedback Service and FCM Topic Subscription Management. These return lists of tokens that are no longer valid. Run cleanup jobs daily to remove dead tokens from your database; accumulating them wastes resources and skews delivery metrics. For comprehensive logging strategies around these events, see structured logging best practices.

Alert on leading indicators, not just outcomes. Queue age exceeding 30 seconds warrants investigation before users notice delays. Acceptance rate dropping below 95% signals credential expiry or payload format changes. Invalid token growth above 1% daily suggests client-side registration bugs. Track click-through rates separately from delivery; high delivery with low engagement indicates content or timing problems, not infrastructure faults. Instrument your workers with OpenTelemetry traces correlating enqueue events to gateway responses for end-to-end visibility.

Secure and Compliant Push Notifications for Mobile Apps

Building trustworthy push notifications for mobile apps means treating them as privileged communication channels subject to security review and user consent laws. Always encrypt tokens at rest and in transit. Implement granular opt-in controls beyond OS-level permissions; let users choose categories and frequencies. Respect GDPR and Nepal’s Privacy Act by providing clear unsubscribe mechanisms and deleting tokens upon account deletion. Audit your notification logs regularly for PII leakage in payloads. Start with the async queue pattern described above, instrument delivery metrics from day one, and automate token cleanup to maintain system health. If your team needs help designing a compliant notification infrastructure or auditing existing setups, reach out to discuss your architecture.

Frequently Asked Questions

Push notifications for mobile apps are server-initiated messages delivered to user devices via platform-specific gateways like APNs or FCM, even when the app is closed. They enable real-time engagement, transactional alerts, and re-engagement campaigns without requiring active user sessions or polling mechanisms.

Add the latest FCM SDK dependency to your build.gradle file and upload your service account JSON key to the Firebase Console. Configure notification channels in AndroidManifest.xml for proper routing. Test delivery using the FCM API v1 endpoint with valid device tokens before production deployment.

Yes. You must generate an APNs Authentication Key (.p8) or SSL certificate in the Apple Developer Portal. Upload this credential to your backend provider or FCM console. Keys are preferred over certificates in 2026 due to automatic rotation support and simpler revocation management across environments.

Platform gateways like FCM and APNs are free. Costs arise from third-party providers, infrastructure, or engineering time. Budget for message volume tiers if using services like OneSignal or Airship. Self-hosted solutions only incur server and bandwidth expenses at scale.

Verify device token registration, network connectivity, and notification permissions. Check APNs or FCM response codes for invalid tokens or throttling. Ensure background app refresh is enabled and battery optimization is disabled for testing. Review server logs for authentication failures or payload formatting errors.

APNs supports up to 4KB for notification payloads and 5KB for silent pushes. FCM allows 4KB for data-only messages and 2KB for display notifications. Exceeding limits causes delivery failure. Compress images externally and reference URLs instead of embedding binary content directly in payloads.

Request permission after demonstrating clear value, not immediately on launch. Use pre-permission prompts explaining benefits contextually. Segment users by engagement level and personalize timing. Track acceptance rates per screen flow. Avoid repeated system dialogs; use custom UI to educate before triggering native permission requests.

Yes. Most providers offer scheduled delivery APIs accepting ISO 8601 timestamps. Store jobs in durable queues like Redis or SQS to survive restarts. Respect user timezone preferences by converting UTC to local time server-side. Validate schedules against rate limits to prevent batching failures during peak windows.

Never include PII or secrets in payloads; use opaque identifiers resolved client-side. Sign requests with short-lived tokens. Rotate APNs keys quarterly. Encrypt sensitive data fields with app-specific keys. Validate sender identity via FCM server keys stored securely in environment variables, never hardcoded in repositories.

Attach image, audio, or video URLs in the payload metadata. iOS requires Notification Service Extensions to download and modify content before display. Android uses BigPictureStyle or custom layouts. Pre-cache assets where possible. Fallback gracefully if media fails to load within platform timeout thresholds.

Monitor delivery rate, open rate, conversion rate, and uninstall correlation. Track permission grant/deny ratios per cohort. Measure latency between send and device receipt. Attribute revenue or actions to specific campaigns. Use UTM parameters or deep link identifiers to connect pushes to downstream behavior accurately.

Yes. Both APNs and FCM deliver messages through OS-level services independent of app process state. Silent pushes may be deferred or dropped if battery optimization is aggressive. Display notifications always arrive unless blocked by user settings or Do Not Disturb mode overriding channel priorities.

Export existing device tokens and map them to new provider endpoints. Update client SDKs in next app release. Run dual-delivery during transition period to catch stragglers. Invalidate old tokens post-migration. Communicate downtime windows if switching requires backend cutover. Validate delivery parity before decommissioning legacy infrastructure.

Duplicate tokens from reinstallations or backup restores create multiple registrations per device. Implement token deduplication logic server-side using stable device identifiers. Clean stale tokens regularly via feedback APIs. Idempotency keys prevent accidental resends during retries. Audit registration flows for race conditions during concurrent app launches.

Use silent pushes for background sync, content pre-fetching, or triggering in-app updates without user interruption. Reserve visible notifications for time-sensitive alerts, messages, or actionable events requiring immediate attention. Silent pushes consume less battery but have lower delivery guarantees. Combine both types strategically based on urgency and user context.