Build a Multi-Channel Push and In-App Messaging Platform
System DesignModel answerLast updated
Design a scalable messaging backend for a consumer mobile app that delivers push and in-app messages, honors user preferences, and stays reliable and legally compliant across regions.
You are asked to design the backend for a messaging platform that serves a large consumer mobile app with millions of daily active users. The platform sends mobile push messages (iOS and Android) and in-app inbox messages, and it must handle two kinds of traffic: event-driven messages (for example, "someone replied to you") and audience-targeted campaigns (for example, "a new feature is available in your country").
The platform must support:
- User-controlled settings: which channels and categories are allowed, plus quiet hours.
- Audience segmentation and targeting.
- Duplicate suppression, per-user frequency limits, and idempotent submission.
- Retries with backoff when delivery fails.
- Scheduled sends and batching or digests.
- A/B experiments on message variants.
- Localized content.
In your answer, cover:
- Requirements and assumptions you would confirm first.
- Back-of-the-envelope capacity numbers (traffic, storage, connections).
- Public and internal APIs.
- The data model.
- The event pipeline, processing workers, and delivery workers, including how they integrate with Apple and Google push services.
- Scaling to millions of DAUs and running across multiple regions, including the consistency versus availability trade-offs.
- Monitoring and alerting.
- Privacy and legal compliance (GDPR, CCPA).
- Failure handling.
- A staged rollout plan.
Be explicit about trade-offs and justify the choices you make.
Hints
Hint 1
Separate the two traffic types early: event-driven messages are latency-sensitive while campaigns are high-volume and tolerant of delay. Think about how to keep a giant campaign from starving the urgent traffic.
Hint 2
Delivery inside the pipeline will be at-least-once, so think about where duplicates can appear (producer retries, consumer replays, provider retries) and put an idempotency or dedup mechanism at each of those points.
Hint 3
Treat the policy checks as an ordered chain per user: preferences and opt-outs, dedup, frequency caps, quiet hours, experiment assignment, then rendering. Partitioning by user ID makes most of that state local.
Hint 4
Decide which things must be strongly consistent (opt-outs, deletions) and which can favor availability (counters, delivery timing), and say so explicitly.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify requirements
Functional
- Two traffic classes: event-triggered (transactional) and segment-targeted (campaign).
- Channels: APNs, FCM, and an in-app inbox, behind one abstraction so email or SMS can be added later.
- Preferences per category and channel, plus quiet hours in the user's timezone.
- Scheduling (absolute or "9am local"), digests, dedup, frequency caps, A/B variants, localization.
Non-functional
- Transactional p99 under about 5 seconds end to end. Campaigns can take minutes to fan out.
- At-least-once inside the system, effectively-once to the user via idempotency.
- Availability 99.95% or better. A late message is better than a stalled pipeline, with one exception: opt-outs and deletions must never be violated.
- Multi-region, GDPR/CCPA compliant.
2. Capacity estimates
Assume 200M DAU, 500M registered users, about 1B device tokens.
- About 10 candidate messages per DAU per day gives 2B/day, roughly 23K/s average. With campaign blasts and evening spikes at about 10x, plan for about 250K/s evaluated.
- Preferences, caps, and dedup drop about half, leaving about 120K/s actual sends.
- Notification log: 2B x 500 B is about 1 TB/day, so about 30 TB for 30 days hot (about 90 TB replicated).
- Preferences: about 500 GB. Device tokens: about 250 GB. Both fit a sharded KV store with a cache.
- Push providers use HTTP/2 multiplexing, so a few thousand requests per second per connection means on the order of 100+ persistent connections per region, spread across worker pods.
3. APIs
POST /v1/notificationswithidempotency_key, recipient, category, template, params, priority, TTL, optional collapse key and send time. Returns 202 with a notification ID.POST /v1/campaignswith segment, variants and weights, schedule (absolute or local time), throttle, TTL; plus start, pause, cancel actions.GET/PUT /v1/users/{id}/preferences.POST /v1/devicesandDELETE /v1/devices/{token}for token lifecycle.GET /v1/users/{id}/inbox?cursor=....POST /v1/eventsfor delivered, opened, dismissed receipts.
Producers must supply an idempotency key. The server dedups on (producer, key) for 24 to 48 hours and returns the original ID on replays.
4. Data model
- Notification request (wide-column, partitioned by user): ID, idempotency key, category, template, variant, status, timestamps, TTL.
- Delivery attempt: notification, device, channel, attempt number, provider response.
- Preferences (sharded KV plus cache): per-category channel flags, quiet hours with timezone, global opt-out, version.
- Devices: user to list of (platform, token, locale, app version, last seen, valid).
- Templates: versioned, per locale, with a fallback chain.
- Segments: definitions plus materialized compressed bitmaps (for example Roaring) in blob storage.
- Counters (Redis): frequency caps and dedup keys with TTLs.
- Experiments: variant is
hash(user_id, experiment_id) mod 100, so it is deterministic and needs no storage lookup.
5. Architecture
Producers call an ingest API that writes to Kafka topics split by priority. The campaign service expands segments and feeds the same pipeline at a throttled rate. Stateless policy workers, partitioned by user hash, run the chain: idempotency, preferences, semantic dedup, frequency caps, quiet hours, experiment assignment, then render and localize. Output goes to per-channel send topics (APNs, FCM, inbox), consumed by channel workers that talk to providers. Provider feedback (receipts, invalid tokens) returns through Kafka to analytics and token cleanup. A scheduler holds deferred items.
Key choices:
- Separate priority topics so a huge campaign cannot delay urgent messages.
- User-hash partitioning gives per-user ordering and keeps caps and dedup local.
- Per-channel topics isolate provider outages: an APNs incident does not back up FCM.
6. Deep dives
Idempotency and dedup, in three layers
- Ingest: an atomic set-if-absent on the idempotency key with a 48h TTL.
- Semantic: hash of (user, category, entity) within a window, so 20 likes become one "X and 19 others" message.
- Delivery: reuse the notification ID as the provider collapse key, and have the client dedup by ID.
Rate limiting
- Per-user caps by category and globally (for example at most 3 marketing pushes a day), via atomic Redis scripts.
- Per-campaign token bucket, and per-provider limits to protect quotas.
Retries
- Retry only transient errors (5xx, timeouts, throttling) with exponential backoff and jitter, bounded by TTL. Honor provider retry-after hints.
- Permanent errors (unregistered token) mark the token invalid and are not retried. Exhausted messages go to a dead-letter queue.
Quiet hours and scheduling
- Low-priority items inside quiet hours are deferred to the window end, or dropped if that exceeds TTL.
- Deferred items live in minute-granularity buckets. "9am local" campaigns expand into per-timezone buckets drained at a smoothed rate to avoid top-of-hour spikes.
Digests: accumulate low-priority items per user for a short window (for example 15 minutes) and merge them.
Segmentation: offline segments precomputed into bitmaps and streamed in shards at launch. Real-time segments query an online feature store.
Experiments: deterministic variant assignment, a holdout that receives nothing (to measure true lift, not just open rate), and assignment logged at send time for metric joins.
Localization: render using device locale with a fallback chain (for example pt-BR, pt, en), ICU message format for plurals, and a default-language fallback when a translation is missing.
7. Scale, regions, consistency
- Regional clusters, with users homed to a region. Cross-region replication for preferences and tokens.
- Strong consistency for opt-outs, deletions, and global unsubscribe (write to the home region, replicate synchronously or check a authoritative flag at send time).
- Availability-first for counters and dedup: tolerate small over-sends during a partition rather than blocking. Cap windows are approximate by design.
- Fail over a region by rerouting producers; idempotency keys make replays safe.
8. Monitoring
Track end-to-end latency percentiles per priority, Kafka consumer lag, send success and provider error rates, invalid-token rate, dedup and cap drop rates, DLQ depth, and open/delivery ratios. Alert on lag growth, error spikes per provider, and sudden changes in drop rates (a sign of a misconfigured rule).
9. Compliance
- Store consent and preference history with timestamps; honor opt-outs immediately.
- Support export and deletion: delete tokens, inbox, and logs keyed by user, and propagate to analytics and backups within the legal window.
- Minimize PII in payloads and logs, encrypt at rest, and apply region-aware retention.
- Respect do-not-sell and marketing-consent flags in segment building.
10. Rollout
- Shadow mode: run the pipeline and evaluate policies without sending, compare with the legacy system.
- Internal users, then 1% of one region, with kill switches per channel and campaign.
- Ramp by region and traffic class, transactional first, campaigns last.
- Load-test to 2x projected peak and run provider-outage drills before full cutover.
Common mistakes
- One shared queue for all traffic, letting campaigns starve urgent messages.
- Assuming exactly-once delivery instead of designing for at-least-once plus idempotency.
- Retrying permanent provider errors, or ignoring invalid-token cleanup.
- Treating opt-outs as eventually consistent.
- Sending "9am local" campaigns all at once and hitting provider limits.
- Measuring experiments by opens only, with no holdout.