Design an OTP and Notification System
Why sending the SMS inside the API request fails, and how queues, priority lanes, retries with backoff and provider failover make notifications fast and reliable.
A notification system delivers messages such as one-time passwords (OTPs), order alerts and promotional campaigns to users over SMS, email and push notifications. The happy path is a single call to an external provider, which makes the system look simple.
The real design work is in everything around that call: slow providers, traffic spikes, retries, duplicates and security. These notes build the system step by step, with OTP delivery as the main example because it has the strictest latency requirement.
1. Clarify the requirements
- Functional: send three kinds of messages, namely OTPs, transactional alerts (order confirmed, payment received) and promotional campaigns.
- Functional: support several channels: SMS, email and push notifications.
- Functional: generate and verify OTPs, including resend.
- Non-functional: an OTP should reach the user within a few seconds; a promotion can take minutes.
- Non-functional: no message may be lost, and duplicates should be avoided as far as possible.
- Non-functional: the system must absorb large spikes, for example a campaign to millions of users on a sale day.
2. Estimate the scale
Assume 10 million notifications per day in normal operation, which is a little over 100 per second on average. A campaign may push 5 million messages in a few minutes, which is tens of thousands per second for a short time. OTP volume is small in comparison but has the strictest latency requirement. The key insight from these numbers: the workload is spiky, and the smallest category is the most urgent.
3. OTP generation and storage
When a user requests an OTP, the service generates a random six-digit code using a cryptographically secure random generator. It stores a hash of the code, not the code itself, in Redis under a key for that user and purpose, with a TTL of about five minutes. When the TTL expires, Redis deletes the key and the OTP stops working without any cleanup job.
Verification compares the hash of the submitted code with the stored hash, counts failed attempts, and deletes the key after success so the code cannot be reused.
SET otp:login:+9198xxxxxx10 '{"hash":"9f2c...","attempts":0}' EX 300
# Resend -> overwrite the same key (old code becomes invalid), reset the TTL
# Verify -> compare hashes; on success DEL the key
# 3 wrong attempts -> DEL the key and block further tries for a cool-down period4. Synchronous versus asynchronous sending
If the API handler calls the SMS provider and waits for the reply, your latency becomes the provider's latency. When the provider slows down, request threads pile up waiting, and soon your own API stops responding. A failure in an external company has become an outage in your system.
The solution is asynchronous processing. The API validates the request, writes a message to a queue, and immediately returns 202 Accepted. A separate pool of workers reads from the queue and talks to the providers. The queue decouples the two sides: the API stays fast regardless of the provider, and messages wait safely in the queue if workers or providers are slow.
POST /api/v1/notifications
Headers: Idempotency-Key: 7c1e9a52-...
Body: { "userId": 42, "type": "OTP", "channel": "SMS",
"templateId": "login_otp", "params": { "code": "******" } }
Response: 202 Accepted { "notificationId": "ntf_81723" }
POST /api/v1/otp/verify
Body: { "phone": "+9198xxxxxx10", "purpose": "login", "code": "482913" }
Response: 200 OK | 401 Invalid or expired | 429 Too many attemptsServices --> Notification API --+--> [ HIGH queue: OTP ] --> Workers --+
(auth, orders, | +--> [ MEDIUM queue: transactional ] --> Workers --+--> SMS provider A / B
marketing) | +--> [ LOW queue: promotional ] --> Workers --+--> Email provider
v --> Push (APNs / FCM)
Preferences, templates, failed after retries
dedup keys, delivery log |
v
Dead letter queue5. Priority queues
Suppose marketing sends five million promotional messages and they all go into the same queue. An OTP requested a moment later sits behind all of them and arrives after it has expired.
The fix is to separate traffic by priority. OTPs get their own high-priority queue with dedicated workers; transactional messages get a second queue; promotions get a third. A backlog in the promotional queue then has no effect on OTP delivery. This is usually called a priority queue design, and it is the most important idea in this system.
Rate limit each lane as well. Providers impose throughput limits, and you do not want promotions consuming the quota that OTPs need.
6. Retries, backoff and provider failover
External providers fail. When a send attempt fails, the worker retries, but not immediately and not forever. Retrying instantly hammers a provider that is already struggling. Instead, use exponential backoff: wait one second, then two, then four, with a little random jitter so that thousands of workers do not retry at the same moment.
If the provider keeps failing, switch to a second provider. This is failover. A circuit breaker tracks the error rate for each provider and stops sending to one that is clearly unhealthy, then probes it periodically to see if it has recovered. Messages that still fail after all retries go to a dead letter queue for inspection, so nothing is silently dropped.
7. Resend: only the latest OTP is valid
The user pressed Resend and now has two codes. Only the latest one should work. Because the OTP is stored under a single key per user and purpose, generating a new code overwrites the old one. The earlier code no longer matches the stored hash and is rejected. This closes a security gap as well: an attacker gains nothing from intercepting an older message.
Resend should also be rate limited (for example one resend every 30 seconds, five per hour) to protect both your SMS bill and your users.
8. Delivery guarantees and duplicates
Queues typically provide at-least-once delivery: if a worker crashes after calling the provider but before acknowledging the message, the message is delivered again. To avoid sending the same notification twice, each message carries a unique ID, and the worker records that ID in a deduplication store before sending. If the ID is already present, the worker skips it. The same idempotency key on the API protects against clients retrying a request.
Finally, store the status of each notification (queued, sent, delivered, failed) using the provider's delivery callbacks. This gives you an audit trail and lets you measure delivery time per provider.
Interview summary
- Requirements: fast OTP delivery, no message loss, multiple channels, spiky load.
- Asynchronous design: API publishes to a message queue, workers send in the background.
- Priority queues: OTP first, transactional next, promotions last, each with its own workers.
- Reliability: retry with exponential backoff, failover to a second provider, dead letter queue.
- Security: store hashed OTPs with a TTL, only the latest OTP is valid, limit attempts and resends.
Summary
Do not send notifications inside the request. Accept the request, queue it, and let workers deliver it. Keep OTPs in their own high-priority lane, retry with backoff and fail over between providers, make workers idempotent, and store OTPs hashed with a short TTL so that only the most recent code is ever valid.
Puneet Tiwari
Full Stack Developer
