Design a notification service

Learn how to design a scalable, reliable notification system that handles millions of SMS, email, and push notifications daily with rate limiting, retries, and deduplication.

intermediate10 min readBy CureBugs EditorialUpdated 5 Nov 2026

Notification systems are the unsung heroes of modern distributed applications. Whether it is a critical OTP for logging into your bank, a shipping update for your food delivery, or a promotional alert about a flash sale, notifications drive user engagement and retention. Designing a notification service might seem as simple as calling a third-party API, but at scale, it becomes a complex beast. You have to handle sudden spikes in traffic, respect strict third-party rate limits, ensure critical messages are never lost, and guarantee that users aren't spammed with duplicate alerts.

Requirements (functional and non-functional)

Before diving into the architecture, we must clearly define what our system will and will not do. In an interview, always clarify the scope to avoid building a system that is either too simple or over-engineered.

Functional Requirements

  • Multiple Channels: The system must support sending notifications via SMS, Email, and Push Notifications (iOS/Android).
  • Internal API: Expose an API for other internal microservices (e.g., Order Service, Auth Service) to trigger notifications.
  • User Preferences: Users must be able to opt-in or opt-out of specific channels and categories (e.g., opt-out of promotional emails, but keep transactional SMS).
  • Templating: The system should support dynamic templates (e.g., "Hi {name}, your OTP is {otp}") rather than hardcoded strings.

Non-Functional Requirements

  • High Availability: The system must be highly available (99.99% uptime). If the notification service goes down, users cannot receive OTPs to log in.
  • Scalability: Must handle millions of notifications daily, with the ability to absorb massive spikes during marketing campaigns or breaking news.
  • Reliability (At-least-once delivery): Critical notifications (like OTPs or order confirmations) must not be lost.
  • Low Latency: Transactional messages must be delivered to the third-party provider in under 2 seconds.
  • Rate Limiting: The system must not spam users and must strictly adhere to the rate limits imposed by third-party providers.

Capacity estimates

Let's assume we are building this for a popular Indian e-commerce or fintech app with a massive user base.

  • Users: 100 million Daily Active Users (DAU).
  • Volume: On average, a user receives 10 notifications per day across all channels. This translates to 1 billion notifications per day.
  • Throughput (QPS): 1,000,000,000 / 86,400 seconds ≈ 11,500 QPS on average.
  • Peak Throughput: Traffic is rarely uniform. Assuming a 3x multiplier for peak hours (e.g., evening shopping hours or a bulk marketing blast), peak throughput is around 34,500 QPS.
  • Storage (Logs): We need to store notification metadata (status, timestamps, user_id, channel) for 1 year for customer support, compliance, and analytics.
    • Size per record: ~500 bytes.
    • Records per year: 1 billion/day * 365 days = 365 billion records.
    • Total storage: 365 billion * 500 bytes ≈ 182.5 TB of data per year.
  • Bandwidth: 11,500 requests/sec * 500 bytes ≈ 5.75 MB/s ingress bandwidth, which is easily manageable.

API design

Our service will expose RESTful APIs for internal services to trigger notifications and for the client apps to update user preferences.

1. Send Notification API

POST /v1/notifications/send

Headers:

  • Authorization: Bearer token (Service-to-Service auth)
  • Idempotency-Key: UUID (To prevent duplicate processing on retries)

Request Body:

json
{
  "user_id": "u_987654321",
  "channel": "SMS",
  "category": "TRANSACTIONAL",
  "template_id": "tmpl_otp_login_01",
  "payload": {
    "name": "Rahul",
    "otp_code": "456789"
  },
  "priority": "HIGH"
}

Response: 202 Accepted (We return 202 because the processing is asynchronous. We return a notification_id for tracking).

2. Update User Preferences

PUT /v1/users/{user_id}/preferences

Request Body:

json
{
  "sms_opt_in": true,
  "email_opt_in": false,
  "push_opt_in": true,
  "muted_categories": ["PROMOTIONAL", "NEWSLETTER"]
}

Response: 200 OK

Data model

Choosing the right database is critical, especially when dealing with 182 TB of logs. We need different databases for different access patterns.

ComponentTechnology ChoiceJustification
User PreferencesPostgreSQL / MySQLRelational data, ACID compliance for user settings, low write volume, high read volume (easily cached).
TemplatesPostgreSQLSmall dataset, rarely changes, requires structured querying.
Notification LogsCassandra / DynamoDBExtremely high write throughput (11k+ QPS), horizontal scalability, time-series nature (query by user_id or timestamp).
Rate Limiting & CacheRedisIn-memory speed, atomic operations (INCR, EXPIRE) for sliding windows and deduplication.
Message QueueKafkaHigh throughput, persistence, replayability, consumer groups for fan-out.

Key Tables

Notification_Logs (Cassandra)

  • notification_id (UUID, Partition Key)
  • user_id (String, Indexed for support queries)
  • channel (String)
  • status (Enum: PENDING, SENT, FAILED, DELIVERED)
  • provider_response (String)
  • created_at (Timestamp, Clustering Key)

High-level architecture

Here is the end-to-end flow of how a notification moves from an internal service to the user's device.

Step-by-step Execution:

  1. An internal service (e.g., Auth Service) calls the API Gateway to send an OTP.
  2. The API Gateway routes the request to the Notification Service.
  3. The Notification Service validates the payload and checks the Idempotency-Key in Redis to ensure it's not a duplicate request.
  4. It fetches the user's contact info and preferences from the cache/DB. If the user has opted out of this category, the request is dropped.
  5. It checks the Rate Limiter (Redis) to ensure the user isn't being spammed.
  6. If all checks pass, the service constructs the final message using the requested template and publishes an event to Kafka.
  7. Dedicated Workers (SMS, Email, Push) consume messages from Kafka at their own pace.
  8. The Workers call the respective third-party APIs (Twilio, SendGrid, APNS).
  9. Upon receiving a response from the provider, the Workers update the Notification Logs DB with the final status.

Deep dives

1. Prioritization and Queueing Strategy

The Problem: Imagine the marketing team decides to send a "Big Billion Days" promotional SMS to 50 million users. If these 50 million messages are dumped into the same Kafka topic used for OTPs, the queue will be backed up for hours. A user trying to log in will not receive their OTP in time, leading to a terrible user experience and lost revenue.

The Solution: We must decouple transactional and promotional traffic using separate Kafka topics and dedicated worker pools.

  • sms_transactional_topic: High priority, strict latency SLA (< 2 seconds). We assign a large pool of fast workers to this topic.
  • sms_promotional_topic: Low priority, relaxed latency SLA (can take hours). We assign a smaller pool of workers that respects the third-party provider's rate limits to avoid getting our account suspended.

By isolating the queues, a massive marketing blast will never impact the delivery of critical transactional messages.

2. Reliability, Retries, and Idempotency

The Problem: Network calls fail. Twilio might experience an outage, or a worker might crash mid-processing. We need to guarantee at-least-once delivery without accidentally sending the same OTP five times.

The Solution: First, we implement Exponential Backoff with Jitter for retries. If a worker fails to send an SMS, it pushes the message to a retry_topic with a delay. If it fails 3 times, it is moved to a Dead Letter Queue (DLQ) for manual inspection.

Second, to prevent duplicate sends (e.g., if a worker sends the SMS, but crashes before committing the Kafka offset), we use Idempotency Keys. We store the notification_id in Redis with an expiration time. Before a worker calls the third-party API, it checks Redis. If the key exists, it skips the API call.

Here is how you might implement a simple idempotency check in your workers:

import redis

def is_duplicate(redis_client, notification_id):
    # SETNX (Set if Not eXists) ensures atomic check-and-set
    # EX 86400 sets the key to expire in 24 hours
    result = redis_client.set(f"idemp:{notification_id}", "1", nx=True, ex=86400)
    return result is None

3. Rate Limiting and Throttling

The Problem: We face two distinct rate-limiting challenges. First, we must not annoy our users (e.g., max 3 promotional emails per week). Second, third-party providers enforce strict API limits (e.g., SendGrid might allow exactly 10,000 requests per second; exceeding this results in 429 Too Many Requests or account suspension).

The Solution: We implement a multi-layered rate limiting strategy.

  • User-level Limiting: Implemented in the Notification Service before pushing to Kafka. We use a Sliding Window algorithm in Redis. If a user has already received 3 promotional messages this week, the 4th request is silently dropped and logged.
  • Provider-level Throttling: Implemented in the Workers after pulling from Kafka. We use a Token Bucket algorithm. The workers collectively share a distributed token bucket in Redis. Before calling SendGrid, a worker must acquire a token. If the bucket is empty, the worker pauses or pushes the message back to the queue with a delay. This ensures we perfectly smooth out traffic spikes and never breach our provider SLA.

Bottlenecks and trade-offs

No system is perfect. Here are the realistic trade-offs we made:

  • At-least-once vs Exactly-once: We guarantee at-least-once delivery. Achieving true exactly-once delivery in a distributed system interacting with external APIs is mathematically impossible without two-phase commits supported by the provider. We trade off the rare possibility of a user receiving a duplicate notification for system availability and performance.
  • Database Growth: Storing 182 TB of logs per year in Cassandra is expensive. Trade-off: We only keep 30 days of logs in hot storage (Cassandra). We run a daily Apache Spark job to archive older logs to AWS S3 (Cold Storage) in Parquet format. This drastically reduces costs while keeping recent logs fast to query for customer support.
  • Third-Party Dependency: If Twilio goes down globally, our SMS workers will fail. To mitigate this, we implement the Circuit Breaker pattern. If Twilio fails continuously, the circuit opens, and we automatically failover to a backup provider like MSG91 or Plivo.

Questions an interviewer will ask next

Q: How do you handle a massive spike, like sending a "Breaking News" push notification to 50 million users instantly? Answer: You cannot make 50 million API calls to the Notification Service. Instead, use the Fan-out pattern. The internal service sends a single BULK_NOTIFICATION event. A dedicated Fan-out Worker reads this event, queries the user database in paginated chunks, and publishes millions of individual messages directly into the Kafka topics.

Q: How do you track open rates and click rates for emails? Answer: For open rates, embed a tracking pixel (a 1x1 transparent image) with a unique URL in the HTML email. When the user's client loads the image, it hits our Analytics Service. For click rates, wrap all links in the email with a redirect service (e.g., click.ourdomain.com/track?id=123), which logs the click before redirecting the user to the actual destination.

Q: What if a user reads a message on Push, can we cancel the pending Email notification? Answer: Yes, this is called cross-channel deduplication. When the user opens the Push notification, the client app fires a READ event to our system. We store this state in Redis. When the Email worker picks up the delayed email task, it checks Redis. Seeing the READ state, it drops the email task, saving money and preventing user annoyance.

Mock interview

Now design it with an interviewer in the room

Reading a design is the easy part. In the round you have to drive it yourself: ask the right questions, sketch it, and defend each choice when the interviewer pushes back.

  • Starts from this exact problem, on a shared whiteboard
  • Follow-ups on scale, failure and trade-offs
  • A scored report that quotes your answers and says what to fix
Run this as a mock design round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
Case studies•intermediate

Design a flash sale (10,000 phones, a million buyers)

16 min read
Case studies•intermediate

Design a web crawler

11 min read
Case studies•intermediate

Design Twitter's home timeline

11 min read
Case studies•intermediate

Design a distributed rate limiter

10 min read