Designing a Notification System That Can Handle 10 Million Users
You have 10 million users.
At 10:00 AM, your marketing manager clicks “Send” on a flash-sale campaign.
Ten million users are now waiting for a notification.
Your backend has to deliver millions of push notifications, emails, and in-app messages without taking down your core APIs, overwhelming your database, or getting throttled by Firebase, Twilio, or SendGrid.
And here’s the problem: you can’t simply loop over 10 million users and call an API.
That works at small scale.
At 10 million users, it becomes a distributed systems problem.
Now you have to think about Kafka, backpressure, retries, rate limits, idempotency, consumer lag, provider failures, and traffic spikes.
So how would you actually design a notification system that can survive this?
Let’s build one using Java, Spring Boot, Kafka, Redis, and MySQL — and more importantly, let’s understand the engineering decisions behind it.
1. Laying Down the Ground Rules (Requirements)
Before writing a line of code, we need to be brutally honest about what this system does and what it doesn’t do. This is often where candidates trip up in interviews — they rush to draw Kafka on a whiteboard without defining the problem.
Functional Requirements
We need to:
- Send Push Notifications (iOS/Android), Email, SMS, and In-app messages.
- Support scheduling (send this campaign at 10:00 AM tomorrow).
- Respect user preferences (a user can opt out of marketing emails but receive security alerts).
- Support templates (so we aren’t storing raw text in the database).
- Track delivery status (did it actually reach the phone?).
- Retry failures automatically, especially for transient network issues.
- Support priority (OTP vs. Marketing).
Non-Functional Requirements
This is where the engineering pain lives.
- High Availability: If the notification system is down, user registration (which needs OTPs) fails. This is a tier-1 service for critical flows.
- Latency: For OTPs, the latency must be sub-second. For marketing blasts, it can be minutes.
- Reliability & Delivery Semantics: We cannot lose OTPs. But we also can’t send an OTP twice if the user already received it. For marketing, losing a few is annoying but acceptable. This drives our consistency decisions later.
- Backpressure: The SMS provider only allows 10,000 texts per second. Our system might generate 100,000 texts per second. We need to buffer them.
- Isolation: A tenant trying to send a poorly designed marketing blast should not block OTP delivery for the entire system.
2. The Math Problem (Capacity Estimation)
Average traffic is a lie. A notification system lives and dies by its peaks.
The Baseline:
Let’s say, on average, a user triggers 5 notifications per day (1 marketing push, 1 email, 2 in-app, 1 SMS/OTP).
- Daily Volume: 10M users * 5 = 50 million notifications/day.
- Average TPS: 50M / 86,400 seconds ≈ 578 TPS. That’s trivial for a well-built Spring Boot app.
The Peak (The Campaign):
Now, what happens at 10:00 AM when that marketing blast goes out?
- We need to send 10 million push notifications. Ideally, we want this done in under 5 minutes.
- Burst TPS: 10M / 300 seconds = 33,333 TPS.
This is an order of magnitude difference. On top of this, if you are an OTT platform or a sports app, you have “goal alerts” or “wicket alerts” during live events. When a goal is scored, you might send 5 million pushes in 10 seconds. That’s 500,000 TPS.
Storage:
If we store every notification row (50M/day) with an average size of 1KB, that’s 50GB/day, or about 18TB/year. That’s a hefty Postgres database if you keep it all on disk forever. We’ll need an archiving strategy quickly.
Kafka Throughput:
Kafka handles this easily on the write side (a few brokers can handle millions of messages/sec). The bottleneck will always be the consumers calling external providers.
3. The Architecture: Don’t Block the Request Thread
The first instinct some developers have is to build a REST API that, when called, immediately calls FCM, Twilio, or SendGrid.
Never do this for bulk traffic.
If you call FCM synchronously on the HTTP request thread:
- You hold the Tomcat thread hostage for 100–500ms (network latency).
- Your connection pool to FCM becomes saturated.
- If FCM is down, your API is down. A retry mechanism on the client side just makes the user wait longer.
The Core Concept: The Queue
The request path should only do three things:
- Validate.
- Persist the intent (write to DB).
- Publish an event to Kafka.
After that, the HTTP thread is free. The system is now asynchronous.
Here is the logical flow:
- Client/Admin Panel hits the Notification API.
- Notification API stores the notification in MySQL (Status: PENDING) and fires an event to a notification.events Kafka topic.
- Channel Workers (Push Worker, Email Worker) consume from Kafka.
- Workers call the respective Provider Adapters (FCM, SendGrid).
- Providers send the actual notification.
- Workers update the DB status (Status: SENT or FAILED).
Why Kafka instead of RabbitMQ or raw SQS? Because of throughput, replayability, and consumer group management. If we need to replay 10 million messages because our SendGrid adapter had a bug, Kafka makes this manageable. Also, at 33k TPS, we need a log-based broker that handles high volume without choking.
4. The Java Implementation (Spring Boot)
Let’s look at the code. We want to be pragmatic, not over-engineered.
The Model
We use Java records to keep our DTOs immutable and clean.
<button data-code="public record Notification(
String notificationId,
String userId,
NotificationType type, // OTP, MARKETING, SECURITY
Channel channel, // PUSH, EMAIL, SMS, IN_APP
String templateId,
Map data,
String idempotencyKey // crucial, we'll come back to this
) {}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public record Notification(
String notificationId,
String userId,
NotificationType type, // OTP, MARKETING, SECURITY
Channel channel, // PUSH, EMAIL, SMS, IN_APP
String templateId,
Map<String, Object> data,
String idempotencyKey // crucial, we'll come back to this
) {}
public record Notification(
String notificationId,
String userId,
NotificationType type, // OTP, MARKETING, SECURITY
Channel channel, // PUSH, EMAIL, SMS, IN_APP
String templateId,
Map<String, Object> data,
String idempotencyKey // crucial, we'll come back to this
) {}
The Producer
We don’t want to inject KafkaTemplate everywhere. We wrap it in a NotificationEventPublisher.
<button data-code="@Service
public class NotificationService {
private final NotificationRepository repository;
private final KafkaTemplate kafkaTemplate;
public void send(NotificationRequest request) {
// 1. Build domain object
Notification notification = new Notification(
UUID.randomUUID().toString(),
request.userId(),
request.type(),
request.channel(),
request.templateId(),
request.data(),
request.idempotencyKey() != null ? request.idempotencyKey() : UUID.randomUUID().toString()
);
// 2. Save to DB (state machine)
repository.save(notification);
// 3. Publish to Kafka
kafkaTemplate.send("notification.events", notification.userId(), notification);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
@Service
public class NotificationService {
private final NotificationRepository repository;
private final KafkaTemplate<String, Notification> kafkaTemplate;
public void send(NotificationRequest request) {
// 1. Build domain object
Notification notification = new Notification(
UUID.randomUUID().toString(),
request.userId(),
request.type(),
request.channel(),
request.templateId(),
request.data(),
request.idempotencyKey() != null ? request.idempotencyKey() : UUID.randomUUID().toString()
);
// 2. Save to DB (state machine)
repository.save(notification);
// 3. Publish to Kafka
kafkaTemplate.send("notification.events", notification.userId(), notification);
}
}
@Service
public class NotificationService {
private final NotificationRepository repository;
private final KafkaTemplate<String, Notification> kafkaTemplate;
public void send(NotificationRequest request) {
// 1. Build domain object
Notification notification = new Notification(
UUID.randomUUID().toString(),
request.userId(),
request.type(),
request.channel(),
request.templateId(),
request.data(),
request.idempotencyKey() != null ? request.idempotencyKey() : UUID.randomUUID().toString()
);
// 2. Save to DB (state machine)
repository.save(notification);
// 3. Publish to Kafka
kafkaTemplate.send("notification.events", notification.userId(), notification);
}
}
Notice the partition key: we are using notification.userId().
Why partition by User ID?
Ordering matters for notifications. If a user initiates a “reset password” flow, we need the “Password Reset Email” to arrive before the “Password Reset Success” email. If these land in different partitions, parallel consumers might process them out of order. Partitioning by userId guarantees that all notifications for a specific user are processed sequentially by that partition’s consumer.
5. Kafka Deep Dive: The Devil is in the Partitioning
Partitioning by userId solves ordering, but it creates a “Hot Partition” problem.
If you partition by userId, and you send a “Breaking News” blast to 10 million users, Kafka distributes the load perfectly across your 32 partitions. Great.
But what if you are a banking app and user SuperTrader123 generates 50,000 trade notifications in an hour? That single partition handling SuperTrader123 is now lagging, while other partitions are idle. One heavy user can block the processing for all other users unlucky enough to share that partition.
The Trade-off
For most notification systems (especially consumer apps), partition by userId is the right call because per-user volume is low, but per-user ordering is high value.
For B2B systems where a single tenant can generate millions of events, you might partition by tenantId or a composite key (tenantId + userId). But be prepared for hot tenants.
At-Least-Once and The Double-Send Problem
Kafka guarantees at-least-once delivery by default.
Here is the nightmare scenario:
- Consumer reads a message (offset 100).
- Consumer calls FCM.
- FCM successfully sends the push notification to the phone.
- The consumer crashes (OOM, pod killed during deployment) before it commits offset 100 to Kafka.
- Kafka rebalances. A new consumer takes over the partition.
- It re-reads offset 100.
- It calls FCM again.
- The user gets the exact same notification twice.
“Exactly-once” delivery across Kafka + Database + External HTTP APIs (FCM/Twilio) is impossible. You cannot have an atomic transaction that includes an external side effect like an SMS being physically sent.
We have to use Idempotency.
Solving the Double-Send with Redis
When we consume the message, we try to acquire a lock in Redis.
@KafkaListener(topics = "notification.events", groupId = "push-worker")
public void consume(Notification notification) {
// Use SETNX to ensure atomicity
Boolean isNew = redisTemplate.opsForValue()
.setIfAbsent(notification.idempotencyKey(), "PROCESSING", Duration.ofHours(24));
if (Boolean.FALSE.equals(isNew)) {
// We have already processed this exact event. Skip.
return;
}
provider.send(notification);
}
@KafkaListener(topics = "notification.events", groupId = "push-worker")
public void consume(Notification notification) {
// Use SETNX to ensure atomicity
Boolean isNew = redisTemplate.opsForValue()
.setIfAbsent(notification.idempotencyKey(), "PROCESSING", Duration.ofHours(24));
if (Boolean.FALSE.equals(isNew)) {
// We have already processed this exact event. Skip.
return;
}
provider.send(notification);
}
If the consumer crashes after sending but before committing, the new consumer checks Redis, sees the idempotency key exists, and skips the send. This gives us Effectively-Once delivery.
6. The Provider Layer: Always Abstract External APIs
Never let your business logic import com.google.firebase.messaging or com.twilio.
Always code against an interface.
<button data-code="public interface NotificationProvider {
ProviderResult send(T notification);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public interface NotificationProvider<T extends Notification> {
ProviderResult send(T notification);
}
public interface NotificationProvider<T extends Notification> {
ProviderResult send(T notification);
}
Then implement:
<button data-code="@Component
public class FirebasePushProvider implements NotificationProvider {
@Override
public ProviderResult send(Notification notification) {
try {
// Build FCM message
// Call FCM API
return ProviderResult.success();
} catch (FirebaseMessagingException e) {
if (e.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED) {
// Device token is dead. Permanent failure. Do not retry.
return ProviderResult.failedNonRetryable();
}
// Network blip. Retry.
return ProviderResult.failedRetryable();
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
@Component
public class FirebasePushProvider implements NotificationProvider<Notification> {
@Override
public ProviderResult send(Notification notification) {
try {
// Build FCM message
// Call FCM API
return ProviderResult.success();
} catch (FirebaseMessagingException e) {
if (e.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED) {
// Device token is dead. Permanent failure. Do not retry.
return ProviderResult.failedNonRetryable();
}
// Network blip. Retry.
return ProviderResult.failedRetryable();
}
}
}
@Component
public class FirebasePushProvider implements NotificationProvider<Notification> {
@Override
public ProviderResult send(Notification notification) {
try {
// Build FCM message
// Call FCM API
return ProviderResult.success();
} catch (FirebaseMessagingException e) {
if (e.getMessagingErrorCode() == MessagingErrorCode.UNREGISTERED) {
// Device token is dead. Permanent failure. Do not retry.
return ProviderResult.failedNonRetryable();
}
// Network blip. Retry.
return ProviderResult.failedRetryable();
}
}
}
This abstraction allows you to:
- Unit test without mocking complex SDKs.
- Swap out SendGrid for Mailchimp by just changing the @Component annotation.
- Add fallback logic (if FCM returns 500 for an hour, route to a different provider).
7. The Art of Retrying
Blindly retrying is a recipe for disaster. When FCM starts timing out, the push-worker consumer group gets stuck. Retrying immediately just hammers the struggling API harder, making the outage worse.
The Strategy:
- Classify the Error:
- Non-Retryable (HTTP 400, Invalid Token, Invalid Email): Log it, mark as FAILED, move on. Don’t clog the queue.
- Retryable (HTTP 500, Timeout, 429 Rate Limit): This needs to be retried.
- Exponential Backoff with Jitter:
Don’t retry every 1 second. Retry in 10s, 30s, 1min, 5min. - The Retry Topic:
If a message fails, don’t hang the main consumer. Publish it to a notification.retry topic. A separate consumer group reads from notification.retry. It consumes a message, pauses (sleeps) based on the retry count, and tries again.
- If it succeeds: Done.
- If it fails after 5 attempts: Publish to notification.dlq (Dead Letter Queue) for manual inspection
8. Database Design: The Write-Heavy Beast
If you try to run UPDATE queries on a massive table while doing high-volume inserts, your database will collapse.
Schema:
- notifications (Partitioned by created_at):
- id (UUID)
- user_id
- channel
- status (PENDING, SENT, FAILED, BLOCKED)
- created_at
- notification_templates:
- id
- channel
- body
- language
- notification_preferences:
- user_id
- channel
- enabled
The Heavy Hitter: Delivery Logs
You can’t update 10 million rows individually. That’s insane.
When a campaign is sent, a “Campaign Worker” creates a batch task. The campaign worker doesn’t write 10 million rows to MySQL instantly (that would take forever and spike the DB). It streams them directly to Kafka. The Channel Workers consume from Kafka, send the push, and only then update a counter in Redis, or write a lightweight event to a delivery_logs table in batches.
We should avoid storing the delivery_logs in the main notifications table. Move older data (older than 30 days) to cold storage (S3/Snowflake). MySQL should only serve recent, mutable state.
9. Redis: The Speed Layer (And Nothing More)
Redis is the glue that makes this system fast, but I would never use it as the primary data store for notifications.
Where I use Redis:
- Idempotency Keys: As shown above. SETNX with a 24-hour TTL.
- Rate Limiting: Tracking FCM rate limits. If FCM allows 500k requests/min, we use a Redis INCR to track our current throughput.
- User Preferences: We don’t want to hit MySQL for every OTP to check if the user has disabled SMS. We cache user:{id}:prefs in Redis. If Redis is down, we fall back to the DB (and the system slows down, but doesn’t crash).
10. Handling Provider Throttling (Backpressure)
Your Kafka can hold 5 million messages easily. Your consumer can read 10,000 messages/sec. But your SMS provider (Twilio) might only allow 1,000 messages/sec.
If the consumer reads 10k messages and starts calling Twilio at 10k/sec, Twilio returns 429 errors. You have now created a “retry storm” where the system is spending all its resources failing.
The Solution: Buffer and Thrrottle
- Slow Down the Consumer: Use spring.kafka.listener.concurrency to limit threads.
- Rate Limiter: Use a library like Bucket4j or Guava RateLimiter in the adapter.
// In the TwilioAdapter
private final RateLimiter rateLimiter = RateLimiter.create(1000); // 1000 TPS
@Override
public ProviderResult send(Notification notification) {
rateLimiter.acquire(); // Blocks if we are going too fast
// ... call Twilio
}
// In the TwilioAdapter
private final RateLimiter rateLimiter = RateLimiter.create(1000); // 1000 TPS
@Override
public ProviderResult send(Notification notification) {
rateLimiter.acquire(); // Blocks if we are going too fast
// ... call Twilio
}
If the provider is slow, rateLimiter.acquire() blocks the consumer thread. If all threads are blocked, Kafka stops polling. This is natural backpressure. The messages wait in Kafka (which is fine — it’s a buffer) until the provider is ready to accept them.
11. Priority: Don’t Let Marketing Kill OTPs
We have 5 million marketing pushes queued in Kafka. A user tries to log in and needs an OTP. If the OTP goes to the back of the line, the user waits 20 minutes and gives up.
The Solution: Separate Topics/Pipelines
- notification.critical: High priority (OTP, Security). Small volume, dedicated consumer group with high concurrency.
- notification.transactional: Standard order confirmations.
- notification.marketing: Bulk campaigns.
The marketing consumer group can be slow or paused without affecting the critical group. This is “isolation.”
12. Scheduling
How do we handle “Send this tomorrow at 10:00 AM”?
Option A: Quartz/Cron with Database Polling
Write a scheduler that every 5 seconds queries MySQL: SELECT * FROM notifications WHERE status = ‘SCHEDULED’ AND scheduled_at <= NOW().
Problem: This scales poorly at 10M users. Scanning a massive table every 5 seconds is terrible.
Option B: Redis Sorted Sets
When a notification is scheduled, add it to a Redis Sorted Set with the timestamp as the score.
A background scheduler polls the Redis sorted set for items with score <= NOW(). When found, it publishes them to Kafka.
This is elegant and O(log N) complexity. However, Redis is memory-expensive, and if Redis loses data (without persistence), scheduled notifications vanish.
Option C: Kafka + Delayed Topics (or a Scheduler Service)
A dedicated scheduler service accepts the request, stores it in a scheduled_notifications table, and sets a timer. When the timer fires, it pushes the event to Kafka. This is the most robust for large scale, keeping the heavy lifting in Kafka and a lightweight scheduler just handling the delay.
13. What Breaks First? (Failure Scenarios)
When you present a design, the interviewer will immediately ask: “What happens if X fails?”
- Kafka is down: The API cannot write to Kafka. We must either fail fast (503 error to the client) or, if it’s critical, spill events to a local log/DB queue for later replay. Usually, fail fast and let the source system retry.
- Redis is down: The consumer must not crash. It should skip the idempotency check (or fall back to a local hash) and continue, accepting the risk of duplicate sends rather than a total system outage.
- FCM is slow: Consumer lag increases. We scale up the number of Kafka consumers for that group to parallelize the connection wait times.
- Database is a bottleneck: Check if we are doing too many unique constraint checks. Ensure we are batching updates.
14. Observability: Looking Under the Hood
When the system is moving millions of notifications, “it works on my machine” doesn’t apply. You need logs and metrics.
- Kafka Consumer Lag: This is the most important metric. If lag > threshold, the system is falling behind.
- Provider Success Rate: (SENT / (SENT + FAILED)). A sudden drop indicates a provider outage.
- DLQ Depth: If the dead-letter queue is growing, you have a persistent bug (e.g., invalid tokens not being cleaned up).
- Latency Percentiles: p50 vs p99 for OTP notifications. p99 matters most.
Use Micrometer with Prometheus and Grafana. Ensure every Notification event gets a correlationId passed down from the source request so you can trace it from the API request to the FCM callback.
15. How I’d Explain This in an Interview
If I have 45 minutes to design this, here is the narrative:
- Clarify Scope: “Are we talking purely system-generated notifications, or user-to-user chat notifications? 10M users, okay. What’s the peak scenario? A campaign? Let’s design for 50k TPS peak.”
- High Level: “We need to decouple the notification generation from the delivery. I’ll use a REST API to ingest, persist the intent to MySQL, and then immediately return success. We publish the event to Kafka to handle the fan-out.”
- Deep Dive on Kafka: “Why Kafka? We need a buffer that can handle spikes. We partition by User ID to preserve per-user ordering and prevent race conditions.”
- Delivery Guarantees: “External APIs make exactly-once impossible. We implement effectively-once using idempotency keys stored in Redis.”
- The Dirty Details: “We need retry queues and DLQs. We need to classify errors — don’t retry a ‘bad token’ error. We need to rate-limit our consumers to respect provider limits.”
- Priority: “Marketing email can be delayed by 10 minutes without user impact. OTP cannot. I’ll isolate critical notifications on a separate Kafka topic with dedicated workers.”
- Scaling: “The first bottleneck will be the providers, not Kafka or the App. We scale horizontally by adding consumers. The second bottleneck will be MySQL write volume, which we solve by batching and partitioning.”
The important part isn’t reciting specific APIs; it’s demonstrating an understanding of backpressure, idempotency, and failure isolation.
Final Architecture
Here is the evolved final state:


