📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Design a notification system that sends email, SMS and push notifications for many product teams. Users have channel preferences and quiet hours, providers fail and throttle, and some messages (password resets) are urgent while others (marketing) are not. Walk me through the API, the pipeline, retries, deduplication and rate limits.

A full multi-channel notification platform design: requirements, capacity estimate, send API with idempotency keys, templating and preference checks, priority queues per channel, provider adapters with retries, failover and throttling, deduplication, delivery tracking, Spam Act consent, mapped to Azure Service Bus, Communication Services and Notification Hubs.

Senior SystemDesign Advanced azure-communication-services azure-service-bus idempotency notifications retries system-design

🎯 Key points

  • Clarify channels, priorities (transactional vs marketing), preferences, quiet hours; estimate 50M/day ≈ 580/s with 10× campaign bursts
  • Async API: POST returns 202 with an id; idempotency key per event + recipient + channel
  • Pipeline: ingest → preference/consent check → render template → per-channel, per-priority queues → provider workers
  • Preferences cached with invalidation on change and re-checked at send time, so an unsubscribe applies to messages already queued
  • Per-user frequency caps and digests: collapse several low-priority notifications into one, pick the user's preferred channel
  • Retries with exponential backoff + jitter; dead-letter after N; failover to a second provider for critical messages; throttle to provider limits
  • Delivery tracking: status per attempt (queued, sent, delivered, bounced, failed) from provider webhooks via Event Grid, keyed by notification id
  • Spam Act 2003: consent, sender identification, unsubscribe honoured within five working days

⏱ 30-second answer

A notification system is an asynchronous pipeline, not an API that calls Twilio. Callers POST an event with an idempotency key and get 202 Accepted. The pipeline checks preferences, consent and quiet hours, renders the template, then puts the message on a queue per channel and priority, so a 5-million-email marketing blast can never delay a password reset SMS. Channel workers call providers (Azure Communication Services, Notification Hubs) with retries, backoff, throttling to provider limits and failover to a second provider for critical messages. Every attempt is recorded for delivery status and support. The trade-off is at-least-once delivery: duplicates are prevented by deduplicating on the key before sending, but a provider timeout can still cause a rare double send, which is better than losing a reset code.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"I'd clarify the channels, email, SMS and push, and the two very different classes of message: transactional, like password resets and order confirmations, which must arrive within seconds, and marketing, which can wait minutes but comes in huge bursts. I'd ask about preferences and quiet hours, whether we need delivery receipts, and the volume. Say 50 million notifications a day: that's about 580 a second on average, but a campaign can push 5 million emails in an hour, so I design for bursts of ten times that.

The API is asynchronous: product teams POST /notifications with a template id, recipient, data and an idempotency key, and get 202 with a notification id. Ingest writes to Service Bus. A preference service checks consent, channel choice and quiet hours, a renderer fills the template, and then the message goes to a queue per channel and priority. That separation is the key decision. For example, at [company] we [had a single queue, and a marketing send delayed password resets by 40 minutes]; splitting queues and giving transactional traffic dedicated workers brought reset delivery back to [under 5 seconds at p95].

Channel workers call providers: Azure Communication Services for email and SMS, Notification Hubs for push. They throttle to the provider's rate, back off on 429 with jitter, retry transient failures, and dead-letter after a handful of attempts. For critical messages I keep a second provider and fail over on sustained errors. Every attempt goes into a delivery log keyed by notification id, so support can answer 'did the customer get it?'

The mistake I see is treating it as synchronous: the order API calls the SMS provider inline, and when the provider is slow, checkout is slow. A notification platform is a set of queues with good manners: towards users, providers and the teams that share it."


Requirements

Type Requirement Assumption
Functional Send email, SMS, push from a template Teams own templates; versioned
Functional Preferences, consent, quiet hours, unsubscribe Transactional bypasses quiet hours, marketing doesn't
Functional Delivery status per notification From provider callbacks
Non-functional Transactional p95 < 10 s end to end Dedicated capacity
Non-functional Marketing: 5M within an hour Throttled by provider limits
Non-functional No loss; duplicates rare At-least-once + dedup

Capacity estimate

Quantity Arithmetic Result
Average rate 50M Γ· 86,400 β‰ˆ 580/s
Campaign burst 5M Γ· 3,600 β‰ˆ 1,400/s extra
Delivery log rows/year 50M Γ— 365 Γ— ~1.3 attempts β‰ˆ 24 billion
Log storage/year 24B Γ— 300 B β‰ˆ 7 TB β†’ hot 30 days, then archive

High-level design

Product services ──POST /notifications (idempotency key)──► Ingest API ──► Service Bus topic "notifications"
                                                                       β”‚
                                         Preference + consent + quiet hours (cache) + template render
                                                                       β”‚
             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
             β–Ό                          β–Ό                         β–Ό                       β–Ό
   email-transactional         email-marketing              sms-transactional        push-*
             β”‚                          β”‚                         β”‚                       β”‚
     Email workers (throttled) ──► ACS Email        SMS workers ──► ACS SMS / fallback   Push ──► Notification Hubs
             β”‚                                                                                 (APNs, FCM)
             β–Ό
   Delivery log (Azure SQL / Cosmos DB, TTL)  ◄── provider status webhooks (Event Grid)

Decisions and alternatives

Decision Choice Alternative Why
Transport Service Bus queues per channel/priority One queue with priority field Brokers don't reorder by priority; separate queues isolate bursts
Dedup Key store (Redis/SQL unique index) before send Service Bus duplicate detection only Broker dedup has a time window and only covers enqueue
Delivery At-least-once Exactly-once Not achievable across an external provider
Templates Stored, versioned, rendered centrally Callers send HTML Consistent branding, unsubscribe links, localisation

Production example

A platform sending [40 million] messages a day across [12] product teams kept password-reset SMS at p95 4 s during a 6-million-email Black Friday campaign, because the marketing queue was throttled to the provider's limit while transactional queues had dedicated workers. Provider failover moved SMS to the backup provider within 2 minutes during a primary outage.

πŸ” What the interviewer is checking

Checks that the candidate designs an asynchronous, isolated pipeline that handles failures and user preferences correctly.

Green flags

  • Separates transactional from marketing traffic with separate queues and capacity
  • Uses idempotency keys and explains why exactly-once isn't possible
  • Classifies errors, backs off, dead-letters and fails over
  • Mentions consent, unsubscribe and quiet hours with time zones

Red flags

  • Synchronous provider calls from business code
  • One queue with a priority field
  • Retries everything forever
  • No delivery tracking or support story

πŸ“š Learn in depth

1. Why queues per channel and priority

Queues are FIFO. If marketing and transactional share one, a burst of 5 million marketing emails sits in front of every reset code. Message brokers like Service Bus don't reorder by a priority property, so priority is modelled as separate queues with separate consumers and capacity.

email-transactional  ──► 20 workers, no throttle beyond provider limit
email-marketing      ──► 10 workers, token bucket at 60% of provider limit
sms-transactional    ──► 10 workers, failover enabled

2. Exactly-once is impossible, so design for at-least-once

The worker calls the provider, then records success. If it crashes or times out in between, the message is redelivered and sent again. You narrow the window:

  1. Check the dedup store for (idempotencyKey, channel); skip if already Sent.
  2. Pass your notification id to providers that support idempotency or client references.
  3. Record Sending before the call and Sent after, so retries can see an in-flight attempt.

For reset codes a rare duplicate is acceptable; a lost one is not.

3. Retries, backoff and dead-lettering

Classify errors: transient (timeouts, 5xx, 429) β†’ retry with exponential backoff and jitter (1 s, 2 s, 4 s, … capped), honour Retry-After; permanent (invalid number, hard bounce, unregistered device token) β†’ don't retry, mark the address invalid and stop sending to it. After N attempts, dead-letter with the reason and alert. Use Service Bus scheduled messages (ScheduledEnqueueTime) for long backoffs rather than holding a lock.

A circuit breaker per provider stops hammering a failing provider; for transactional SMS the breaker opening triggers failover to a second provider.

4. Preferences, consent and quiet hours

Preferences are read on every message, so cache them (HybridCache) and invalidate on change. Quiet hours need the user's time zone; Australia has several, and daylight saving differs by state, so store an IANA zone like Australia/Perth and use TimeZoneInfo.FindSystemTimeZoneById. Messages hitting quiet hours are rescheduled, not dropped.

Under the Spam Act 2003, commercial electronic messages need consent, must identify the sender and must include a functional unsubscribe that is honoured within five working days. Transactional messages are generally not commercial but mixing marketing content into them can make them so. Check current ACMA rules for SMS sender IDs before choosing alphanumeric sender names.

5. Provider throttling

Each provider and account has rate limits. Workers share a token bucket per provider account (Redis, or a single partitioned consumer) so 30 pods don't collectively exceed it. On 429, pause the whole channel briefly rather than letting every worker retry.

6. Delivery tracking

Providers report delivered, bounced, failed via webhooks (ACS publishes to Event Grid). Store status transitions against the notification id. Keep 30 days hot and archive to Blob Storage; delivery logs contain personal information, so apply retention and access controls under the Privacy Act.

7. AWS mapping

SQS/SNS for queues and fan-out, Amazon SES for email, SNS or End User Messaging for SMS, Pinpoint-style push via SNS mobile push, DynamoDB for the delivery log.

Try it yourself

  1. Build the worker below against the Service Bus emulator; kill it mid-send and confirm the message is redelivered and the dedup check prevents a second send.
  2. Enqueue 100,000 marketing and 100 transactional messages and measure transactional latency with one queue vs two.
  3. Add a fake provider that returns 429 30% of the time; verify backoff with jitter in logs.
  4. Compute quiet hours for Australia/Adelaide across a daylight saving change with TimeZoneInfo.
  5. Chart dead-letter counts per reason in Application Insights.

πŸ’» Code

A channel worker: dedup, preference check, send with classification of errors, and rescheduling for quiet hours.

namespace Notifications;

public sealed record NotificationMessage(Guid Id, string IdempotencyKey, string UserId, string Channel, string Priority, string TemplateId, IReadOnlyDictionary<string, string> Data);

public enum SendOutcome { Sent, TransientFailure, PermanentFailure }

public interface IChannelProvider { Task<SendOutcome> SendAsync(NotificationMessage message, CancellationToken ct); }
public interface IDedupStore
{
    Task<bool> TryBeginAsync(string key, string channel, CancellationToken ct); // false if already sent or in flight
    Task MarkSentAsync(string key, string channel, CancellationToken ct);
    Task ReleaseAsync(string key, string channel, CancellationToken ct);       // allow a retry after a transient failure
}
public interface IPreferenceService { Task<DateTimeOffset?> DeferUntilAsync(NotificationMessage m, CancellationToken ct); } // null = send now; DateTimeOffset.MaxValue = opted out

public sealed class ChannelWorker(IChannelProvider provider, IDedupStore dedup, IPreferenceService preferences, ILogger<ChannelWorker> log)
{
    public async Task<WorkerResult> HandleAsync(NotificationMessage m, CancellationToken ct)
    {
        var deferUntil = await preferences.DeferUntilAsync(m, ct);
        if (deferUntil == DateTimeOffset.MaxValue) return WorkerResult.Complete("opted-out");
        if (deferUntil is { } at) return WorkerResult.Reschedule(at);         // quiet hours: reschedule, never drop

        if (!await dedup.TryBeginAsync(m.IdempotencyKey, m.Channel, ct))
            return WorkerResult.Complete("duplicate");                      // at-least-once delivery from the broker

        var outcome = await provider.SendAsync(m, ct);
        switch (outcome)
        {
            case SendOutcome.Sent:
                await dedup.MarkSentAsync(m.IdempotencyKey, m.Channel, ct);
                return WorkerResult.Complete("sent");
            case SendOutcome.TransientFailure:
                await dedup.ReleaseAsync(m.IdempotencyKey, m.Channel, ct);
                return WorkerResult.Retry();                                  // broker redelivers with backoff
            default:
                log.LogWarning("Permanent failure for {NotificationId} on {Channel}", m.Id, m.Channel);
                await dedup.MarkSentAsync(m.IdempotencyKey, m.Channel, ct);    // don't retry a bad address
                return WorkerResult.DeadLetter("permanent-failure");
        }
    }
}

public sealed record WorkerResult(string Action, string? Reason = null, DateTimeOffset? At = null)
{
    public static WorkerResult Complete(string reason) => new("complete", reason);
    public static WorkerResult Retry() => new("retry");
    public static WorkerResult Reschedule(DateTimeOffset at) => new("reschedule", At: at);
    public static WorkerResult DeadLetter(string reason) => new("dead-letter", reason);
}
// Program.cs (worker host): resilience for the provider HTTP client
using Microsoft.Extensions.Http.Resilience;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHttpClient("sms-provider")
    .AddStandardResilienceHandler(o =>
    {
        o.Retry.MaxRetryAttempts = 3;                 // exponential backoff with jitter by default
        o.CircuitBreaker.FailureRatio = 0.5;          // open β†’ trigger failover to the backup provider
        o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(15);
    });
builder.Build().Run();

⚠ Common mistakes

  • Mistake: Sending notifications synchronously from the business API. Why it is wrong: provider latency and outages become checkout latency and outages. Instead: publish an event and return; the notification pipeline is asynchronous.
  • Mistake: One queue for every channel and priority. Why it is wrong: a marketing burst delays password resets for tens of minutes. Instead: separate queues and worker pools per channel and priority.
  • Mistake: Promising exactly-once delivery. Why it is wrong: a timeout after the provider accepted the message makes it impossible to know whether it was sent. Instead: at-least-once with dedup keys, and pass a client reference to providers that support it.
  • Mistake: Retrying every failure. Why it is wrong: invalid numbers and hard bounces never succeed, waste money and hurt sender reputation. Instead: classify transient vs permanent and suppress bad addresses.
  • Mistake: Each worker retrying immediately on 429. Why it is wrong: the retry storm keeps the account throttled. Instead: shared token bucket per provider, honour Retry-After, pause the channel.
  • Mistake: Storing quiet hours as UTC offsets. Why it is wrong: daylight saving differs between Australian states, so offsets drift twice a year. Instead: store IANA time zones and convert per message.
  • Mistake: Ignoring Spam Act obligations. Why it is wrong: commercial messages without consent or a working unsubscribe breach the law and attract ACMA penalties. Instead: consent records, sender identification and unsubscribe handled centrally by the platform.

πŸ› Senior insight: trade-offs

The senior framing is isolation and honesty: isolate traffic classes so the cheap, bulky one can't hurt the urgent one, and be honest that delivery is at-least-once across an external provider. I would also argue to buy most of it: Azure Communication Services and Notification Hubs handle the channel plumbing; the value we build is preferences, templates, priority isolation and tracking.

Option When it fits Cost When not to
Build pipeline on Service Bus + ACS/Notification Hubs Many teams, own preferences and audit Engineering and on-call One product sending a few emails
SaaS (customer engagement platform) Marketing-led, journeys and A/B tests Per-message licence cost, data leaves your tenancy Data residency or cost per message rules it out
Direct provider SDK in each service Prototype, one team Duplication, no central consent More than one team or any marketing

I measure end-to-end latency per priority (enqueue to provider accepted), queue depth and age per channel, provider error rate and 429s, dead-letter counts, and cost per thousand messages.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions idempotency keys Why: Checks how dedup storage works and what happens when two copies arrive at once
    How to answer

    An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.

  2. When: Candidate says failed messages go to a dead-letter queue Why: Checks how poison messages and backlogs are diagnosed and replayed
    How to answer

    First I work out which problem I have:

    • Poison messages: a few messages always fail.
    • A failing dependency: every message fails.
    • Slow consumers: nothing fails, they just can't keep up.

    To tell them apart I use Service Bus metrics (incoming, completed, abandoned, dead-lettered), the DLQ's DeadLetterReason and DeadLetterErrorDescription, DeliveryCount, and traces grouped by exception.

    Poison messages loop when handlers catch and abandon forever, re-publish failures as new messages, or MaxDeliveryCount is huge. The fix: dead-letter permanent failures immediately, fix the handler or data, then resubmit from the DLQ in batches to an idempotent consumer. Scale consumers only up to the downstream's limit. To prevent it: alerts on oldest message age and DLQ count, plus a poison-message test. The trade-off: dead-lettering early keeps the queue flowing, but someone must own the DLQ.

  3. When: Candidate mentions provider rate limits or per-user frequency caps Why: Checks the rate limiting algorithm and shared state across workers
    How to answer

    A rate limiter protects the service and enforces fairness between customers. I'd use a token bucket per API key: capacity = burst, refill rate = plan limit. It allows short bursts but caps the average. Limits sit in layers: per IP at the edge (Front Door WAF), per API key at the gateway or in the API, and per endpoint for expensive operations. With many instances, the bucket lives in Redis, updated by an atomic Lua script in one round trip, sharded by key. Rejections return 429 with Retry-After. When Redis is unavailable I fail open to a local in-memory limiter with the limit divided by instance count, because rejecting all paying traffic is worse than briefly over-admitting. The trade-off is accuracy versus latency and availability: an exact global limit costs a network hop on every request.

πŸ›  Real-world problems: how you handle them

Marketing campaign delays password reset SMS by 40 minutes
Situation
A shared notification service for [a retail group's] apps, [30 million] messages a day on [Azure Service Bus + a single SMS provider], one queue for all messages.
Signals
Support tickets: 'reset code never arrived'; Service Bus active message count at [3 million]; oldest message age [40 minutes]; provider dashboard showed the account throttled with 429s.
Investigation
Application Insights end-to-end transaction view showed reset messages waiting behind a scheduled marketing send. Worker logs showed every pod retrying immediately on 429, keeping the account throttled.
Resolution
Immediate: paused the marketing subscription and drained resets first. Long term: split queues by channel and priority, gave transactional queues dedicated workers, added a shared Redis token bucket per provider account, honoured Retry-After, and added a backup SMS provider behind a circuit breaker.
Prevention
Alerts on oldest-message age per priority queue (transactional > [60 s]); a campaign load test before major sales; ADR on traffic isolation; dashboard of provider 429s.

How to tell it (STAR)

**S:** At [company] our notification service shared one queue, and during a [spring sale] campaign password-reset SMS took [40 minutes] to arrive. **T:** I was asked to fix it before the next campaign in [three weeks]. **A:** I traced it to resets queued behind [3 million] marketing messages, with every worker hammering the provider after 429s. I split queues by channel and priority, gave transactional traffic its own workers, added a shared token bucket per provider and a backup SMS provider. **R:** In the next campaign, which was [twice] as large, reset p95 stayed at [4 seconds] and we had zero throttling incidents.

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me