Full answer
Flow
- Producer calls POST /notifications with { userId, type, data, idempotencyKey }. Return 202 Accepted quickly.
- The service checks the idempotency key (unique constraint), loads preferences (channels per notification type, language, quiet hours, opt-outs), and creates one delivery record per channel.
- Each delivery goes to a channel queue (email, sms, push). Separate queues stop a slow SMS provider from delaying email.
- A channel worker renders the template, calls the provider, and updates the record (queued, sent, delivered, failed).
- Providers send delivery receipts and bounces by webhook, which update the status and the suppression list.
Reliability
- At-least-once delivery means duplicates are possible, so use provider idempotency keys where they exist and a unique key on (notificationId, channel).
- Retry transient errors with backoff and jitter, give up after N attempts, and move to a dead letter queue. Do not retry permanent errors (invalid number, hard bounce).
- Provider fallback: when provider A fails or times out, try provider B. Use a circuit breaker so you stop calling a provider that is down.
- Rate limits per provider and per user (do not send 50 pushes in a minute). Batch low priority messages into a digest.
Compliance and quality
- Respect opt-out and legal rules (unsubscribe links, consent, quiet hours in the user's time zone). Critical alerts (security, payment) bypass marketing preferences but not legal blocks.
- Store minimal personal data, mask it in logs, and keep an audit trail.
- Templates with versioning and tests, and a sandbox mode for staging.
Metrics: queue age per channel, send success rate per provider, time to deliver, bounce and complaint rates.
javascript
// Teaching sketch: the decision logic of a notification service, with fake providers and a fake clock.
const preferences = {
asha: { channels: { security: ['push', 'email'], marketing: ['email'] }, quietHours: [22, 7], timezoneOffsetHours: 0 },
ravi: { channels: { security: ['sms'], marketing: [] }, quietHours: [22, 7], timezoneOffsetHours: 0 },
};
const seen = new Set(); // idempotency keys
const log = [];
const providers = {
push: async () => { throw Object.assign(new Error('push provider down'), { transient: true }); },
email: async (to) => `email sent to ${to}`,
sms: async (to) => `sms sent to ${to}`,
};
const fallbackFor = { push: 'email' }; // if push fails, try email
function inQuietHours(user, hour) {
const [from, to] = user.quietHours;
return from > to ? (hour >= from || hour < to) : (hour >= from && hour < to);
}
async function notify({ userId, type, key, hour }) {
if (seen.has(key)) return log.push(`${key}: duplicate ignored`);
seen.add(key);
const user = preferences[userId];
const channels = user.channels[type];
if (!channels.length) return log.push(`${key}: user opted out of ${type}`);
if (type === 'marketing' && inQuietHours(user, hour)) return log.push(`${key}: held until quiet hours end`);
for (const channel of channels) {
let used = channel;
try {
log.push(`${key}: ${await providers[channel](userId)}`);
} catch (err) {
const fallback = fallbackFor[channel];
if (err.transient && fallback) {
used = fallback;
log.push(`${key}: ${channel} failed, fallback -> ${await providers[fallback](userId)}`);
} else log.push(`${key}: ${channel} failed for good`);
}
}
}
(async () => {
await notify({ userId: 'asha', type: 'security', key: 'n1', hour: 12 });
await notify({ userId: 'asha', type: 'security', key: 'n1', hour: 12 }); // same key again
await notify({ userId: 'asha', type: 'marketing', key: 'n2', hour: 23 }); // quiet hours
await notify({ userId: 'asha', type: 'marketing', key: 'n3', hour: 10 });
await notify({ userId: 'ravi', type: 'marketing', key: 'n4', hour: 10 }); // opted out
await notify({ userId: 'ravi', type: 'security', key: 'n5', hour: 3 }); // security ignores quiet hours
console.log(log.join('\n'));
})();This is a teaching sketch of the decisions (idempotency, opt-out, quiet hours, fallback). Queues, templates and real providers are not included. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): n1: push failed, fallback -> email sent to asha n1: email sent to asha n1: duplicate ignored n2: held until quiet hours end n3: email sent to asha n4: user opted out of marketing n5: sms sent to ravi
Key points
- Publish events, then resolve preferences and channels in the service.
- An idempotency key and unique records stop duplicates.
- One queue per channel isolates slow providers.
- Retry transient errors, fall back to another provider, dead letter the rest.
- Respect opt-outs and quiet hours.
Common mistakes
- Sending synchronously inside the request that triggered the event.
- No idempotency key, so a retry sends the message twice.
- One shared queue for all channels.
- Ignoring unsubscribes and time zones.
- Retrying permanent failures such as an invalid number.
Follow-ups
- How would you send a daily digest instead of many messages?
- How do delivery receipts update the status?
- How do you prevent a notification storm after an outage?
Tips
- Walk through the flow in five steps.
- Name idempotency and fallback.
- Mention quiet hours and opt-outs.