Customer notification systems: fan-out, preferences, retries and duplicate suppression
Design an event-driven notification platform for a bank: planning notifications from domain events, respecting preferences and quiet hours, fanning out to e-mail, SMS and push through per-channel queues, retrying safely, suppressing duplicates and recording delivery evidence.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.SimpleEmailV2, AWSSDK.SimpleNotificationService, AWSSDK.SQS 4.x) · CDK v2 (Amazon.CDK.Lib 2.277.0) · Terraform AWS provider v6 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain why notifications are a platform with its own architecture, not a call to an e-mail API inside each service.
- Design the flow from domain event to notification plan to per-channel delivery, with queues between each stage.
- Model preferences, categories and quiet hours so security alerts are never silenced while marketing respects consent.
- Build duplicate suppression with a deterministic key, and retries with exponential backoff and jitter.
- Handle bounces, complaints, delivery receipts and provider outages, and keep delivery evidence.
- Choose between SES, SNS and AWS End User Messaging for each channel, with their sandbox and cost sharp edges.
- Write the notification architecture using the 15-section template.
Prerequisites
- Payment processing (events such as
PaymentSettled) - SQS in depth, retry strategies and dead-letter queues and redrive
- Idempotency in .NET
- Module 8 notification project (
labs/m08-notification-system) builds the delivery pipeline; this lesson designs the platform around it - Tools: .NET 10 SDK or Docker; AWS CLI v2 (optional)
Why this matters in banking
A customer's phone buzzes: "A payment of GBP 4,800 to a new payee has been made from your account." If it is real and they did not make it, this message is a security control: the customer is the last line of defence. If it arrives 20 minutes late, twice, or not at all, the control has failed.
Banks send many kinds of messages with very different stakes:
| Category | Example | Failure consequence |
|---|---|---|
| Security | New payee, password change, card frozen | Fraud goes unnoticed |
| Transactional | Payment received, statement ready | Customer calls the contact centre |
| Service | Planned maintenance, branch closure | Mild annoyance |
| Marketing | Savings offer | Complaints, consent problems, regulatory risk |
Four design mistakes recur:
- Each service sends its own messages. Preferences, templates, retries and duplicate rules are implemented five times, badly.
- Marketing and security share a path. A marketing opt-out accidentally silences fraud alerts, or a campaign delays an urgent message.
- Retry without deduplication. A timeout triggers a retry; the customer receives four copies of an OTP.
- Sensitive content in the message. Balances in SMS, or one-time links that never expire.
Educational content, not legal advice
Rules on marketing consent, electronic communications, mandatory notices, sender registration and message content differ by country and channel (in the UK, for example, electronic marketing rules sit alongside UK GDPR ⚠ VERIFY). Your compliance and legal teams decide which messages are mandatory, what they must say and when consent is required. This lesson shows where those decisions plug into the architecture.
The idea in plain language
Think of three stages:
- Decide whether, what and where to notify. Input: a business event (
PaymentSettled,PayeeAdded). Output: zero or more notification intents ("send templatepayee-addedby push to customer C, urgent"). - Deliver each intent through a channel adapter (e-mail, SMS, push), with retries.
- Record what happened (queued, sent, delivered, bounced) as evidence.
Putting a queue between each stage gives you independent scaling, retry and failure handling per channel. A slow SMS provider cannot block e-mail.
Analogy: the bank's post room. Incoming events are letters to be sent. The sorting desk (planner) decides which letters go out, by which carrier, according to each customer's instructions and urgency. Each carrier has its own tray (queue). A record clerk logs every dispatch and every return. If a carrier is on strike, only that tray backs up.
Notification flow
What problem the AWS services solve
| Service | Role | Limits and sharp edges |
|---|---|---|
| Amazon EventBridge | Receives domain events and routes by pattern | At-least-once delivery; events can arrive twice |
| Amazon SNS (standard topics) | Fan-out of intents to channel queues with subscription filter policies | Standard topics do not guarantee order; messages up to a size quota ⚠ VERIFY |
| Amazon SQS | Buffers per channel; visibility timeout, DLQ, redrive | At-least-once on standard queues; FIFO adds dedup and ordering but lower throughput limits ⚠ VERIFY |
| AWS Lambda | Sender workers triggered by SQS | Set partial batch response; reserved concurrency protects providers from overload |
| Amazon SES | E-mail sending with DKIM, bounce and complaint feedback | New accounts start in a sandbox: you can only send to verified addresses until you request production access; sending quotas apply ⚠ VERIFY |
| Amazon SNS SMS / AWS End User Messaging SMS | SMS to phones | Country-specific registration and sender ID rules; new accounts begin in an SMS sandbox with verified destinations and a low spend limit ⚠ VERIFY |
| Amazon SNS mobile push | Push through APNs and FCM | You manage device tokens, which become invalid over time |
| Amazon DynamoDB | Preferences, dedupe keys with TTL, delivery status | Item design for access by customer; TTL deletion is not immediate |
| Amazon Pinpoint | The engagement service reached end of support in 2026 ⚠ VERIFY exact date | SMS and voice capabilities continue as AWS End User Messaging; do not design new work on Pinpoint campaigns or journeys |
| Amazon CloudWatch | Metrics, alarms, delivery-status logs | Alarm on queue age, DLQ depth, bounce and complaint rates |
Honest limitation: AWS provides the pipes, not the content governance or sender reputation. A high complaint rate harms your SES reputation and can pause sending, so marketing and transactional traffic should use separate configuration sets (and often separate identities or accounts).
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure Communication Services (email, SMS) | SES (email), SNS or End User Messaging (SMS) | Separate services per channel; no single unified API |
| Azure Notification Hubs | SNS mobile push | Both abstract APNs and FCM; you still own device token lifecycle |
| Azure Event Grid | EventBridge | Rules with pattern matching route to targets |
| Azure Service Bus topics and subscriptions with filters | SNS topic with filter policies plus SQS queues | Fan-out is SNS; the queue gives buffering and DLQ |
| Azure Functions with Service Bus trigger | Lambda with SQS event source mapping | Batch size, visibility timeout and partial batch response are mapping settings |
| SendGrid via Azure Marketplace | SES (or a third-party provider) | Banks often use specialist providers for deliverability; the architecture should allow swapping |
Architecture
Sequence: a security notification
Security-boundary view
| Concern | Control |
|---|---|
| Who can trigger a notification | Only the planner consumes domain events; services cannot call senders directly |
| Contact details | Stored in the customer service; the planner fetches at plan time and never copies into long-lived queues where avoidable (pass customerId and resolve at send time) |
| Message content | Templates stored and versioned in the platform; services pass parameters, not free text |
| Provider credentials | IAM roles for SES and SNS; third-party provider keys in Secrets Manager |
| Delivery evidence | Append-only status records and provider event logs retained per policy ⚠ VERIFY |
| Abuse | Per-customer and per-destination rate limits, especially for OTP and SMS |
Step-by-step implementation
Define categories and rules (sections 1 and 2)
| Category | Can the customer opt out? | Delivery rules |
|---|---|---|
| Security | No (they can choose the channel, but at least one channel is always used) | Immediate; ignore quiet hours; multiple channels allowed |
| Transactional | Per channel, with defaults on | Respect quiet hours except for failures and large amounts |
| Service | Per channel | Batch where possible |
| Marketing | Opt-in only, recorded consent ⚠ VERIFY legal basis | Never during quiet hours; honour unsubscribe immediately |
Which categories are mandatory and what content they need is a compliance decision. Record each rule with its owner.
Model preferences (section 9)
Per customer: per category and channel enable flags, quiet hours with a time zone, language, contact verification state, and consentVersion for marketing. Store in DynamoDB keyed by customerId. Preferences change rarely, so cache them for a short time in the planner.
Write the planner (section 10)
The planner is a pure decision function: (event, preferences, now) → intents. Keep it free of AWS calls so it is trivial to test (see Complete code). Surround it with an adapter that consumes events, loads preferences, claims dedupe keys and publishes intents.
Suppress duplicates (section 11)
Build a deterministic key: hash of eventId, customerId, channel and templateId. Claim it with a DynamoDB conditional put and a TTL (for example 48 hours). If the claim fails, drop the intent. This is needed twice: EventBridge can redeliver an event, and a sender Lambda can crash after the provider accepted the message.
Fan out and retry (section 10 and 12)
Publish intents to an SNS topic with a channel message attribute. Per-channel SQS queues subscribe with filter policies. Sender Lambdas read in small batches with ReportBatchItemFailures. On a retryable error (throttling, 5xx) return the message for retry with exponential backoff and full jitter by extending the visibility timeout. After N receives it goes to the DLQ, with an alarm. Cap concurrency so you do not overwhelm a provider (Module 8 retry lesson).
Record delivery evidence (section 14 and 15)
Write a status item per intent: queued, sent (provider message id), delivered, bounced, complained, failed. Subscribe to SES event destinations (delivery, bounce, complaint) and SMS delivery-status feedback to update the record. Honour hard bounces and complaints by suppressing future sends to that address.
Plan failure and fallback (section 11)
| Failure | Response |
|---|---|
| Push token invalid | Mark device inactive; fall back to e-mail for security category |
| SES throttled | Retry with backoff; queue depth alarm; do not drop security messages |
| SMS provider outage | Fail over to push or e-mail for security; delay transactional |
| Planner bug sends too many | Per-customer rate limit in the planner; kill switch per template |
| DLQ fills | Page on-call; inspect; fix; redrive |
AWS Console instructions
- Console → Amazon SES → Configuration → Identities → Create identity. Choose Email address, use a mailbox you control, and confirm the verification link. This is the only way to send from the sandbox.
- SES → Configuration sets → Create set
hl-m14-transactional; add an event destination to SNS forDelivery,Bounce,Complaint. - Console → SNS → Topics → Create topic (Standard)
hl-m14-notification-intents; add two SQS subscriptions with filter policies on thechannelattribute. - Console → SQS: open each queue and review the DLQ and visibility timeout settings.
- SES mailbox simulator: use
success@simulator.amazonses.comandbounce@simulator.amazonses.comas recipients to test delivery and bounce events without hurting your sending reputation.
AWS CLI
# Create the intent topic and a filtered e-mail queue (fictional names, course tags).
TOPIC_ARN=$(aws sns create-topic --name hl-m14-notification-intents \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m14-l8 Key=Environment,Value=learn Key=Owner,Value=learner \
--query TopicArn --output text --profile learn-sandbox --region us-east-1)
aws sqs create-queue --queue-name hl-m14-notify-email --profile learn-sandbox --region us-east-1
# After subscribing the queue (and allowing the topic to send to it), publish an intent with a channel attribute.
aws sns publish --topic-arn "$TOPIC_ARN" \
--message '{"intentId":"INT-0001","customerId":"CUS-00000042","template":"payee-added","channel":"email","urgent":true}' \
--message-attributes '{"channel":{"DataType":"String","StringValue":"email"}}' \
--profile learn-sandbox --region us-east-1
# Send a test e-mail to the SES simulator (works from the sandbox; replace the verified sender).
aws sesv2 send-email \
--from-email-address "<your-verified-address>" \
--destination 'ToAddresses=success@simulator.amazonses.com' \
--content 'Simple={Subject={Data="Harbourline test"},Body={Text={Data="Fictional test message."}}}' \
--configuration-set-name hl-m14-transactional \
--profile learn-sandbox --region us-east-1SMS is design-only in this lesson: the sandbox, registration and spend-limit rules vary by country, and a mistake costs real money. Read the current requirements before enabling it ⚠ VERIFY.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.SNS;
using Amazon.CDK.AWS.SNS.Subscriptions;
using Amazon.CDK.AWS.SQS;
using Constructs;
public sealed class NotificationFanOutStack : Stack
{
public NotificationFanOutStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
var topic = new Topic(this, "Intents", new TopicProps { TopicName = "hl-m14-notification-intents" });
foreach (var channel in new[] { "email", "sms", "push" })
{
var dlq = new Queue(this, $"{channel}Dlq", new QueueProps
{
QueueName = $"hl-m14-notify-{channel}-dlq",
RetentionPeriod = Duration.Days(14),
Encryption = QueueEncryption.SQS_MANAGED,
});
var queue = new Queue(this, $"{channel}Queue", new QueueProps
{
QueueName = $"hl-m14-notify-{channel}",
VisibilityTimeout = Duration.Seconds(60),
Encryption = QueueEncryption.SQS_MANAGED,
DeadLetterQueue = new DeadLetterQueue { Queue = dlq, MaxReceiveCount = 5 },
});
topic.AddSubscription(new SqsSubscription(queue, new SqsSubscriptionProps
{
RawMessageDelivery = true,
FilterPolicy = new Dictionary<string, SubscriptionFilter>
{
["channel"] = SubscriptionFilter.StringFilter(new StringConditions { Allowlist = [channel] }),
},
}));
}
}
}Complete code
The planner and the dedupe key are pure C# with no AWS dependency, so they run in a unit test in milliseconds.
using System.Security.Cryptography;
using System.Text;
namespace Harbourline.Notifications;
public enum Category { Security, Transactional, Service, Marketing }
public enum Channel { Push, Email, Sms }
public sealed record DomainEvent(string EventId, string Type, string CustomerId, Category Category, decimal? Amount, bool Urgent);
public sealed record ChannelPreference(bool Enabled, bool Verified);
public sealed record CustomerPreferences(
string CustomerId,
IReadOnlyDictionary<Channel, ChannelPreference> Channels,
IReadOnlySet<Category> OptedOutCategories,
TimeOnly QuietStart,
TimeOnly QuietEnd,
string TimeZoneId);
public sealed record NotificationIntent(string Template, Channel Channel, string CustomerId, string DedupeKey, bool Urgent);
public static class NotificationPlanner
{
// Preference order when several channels could carry a message.
private static readonly Channel[] Order = [Channel.Push, Channel.Email, Channel.Sms];
public static IReadOnlyList<NotificationIntent> Plan(DomainEvent e, CustomerPreferences p, DateTimeOffset now)
{
// Security notifications cannot be opted out: marketing consent flags do not apply to them.
var canOptOut = e.Category != Category.Security;
if (canOptOut && p.OptedOutCategories.Contains(e.Category))
{
return [];
}
var usable = Order
.Where(c => p.Channels.TryGetValue(c, out var pref) && pref.Enabled && pref.Verified)
.ToList();
if (usable.Count == 0)
{
return []; // Nothing usable. A security event here should raise an alert elsewhere (see tests).
}
// Quiet hours apply to everything except security and urgent transactional messages.
var bypassQuiet = e.Category == Category.Security || e.Urgent;
if (!bypassQuiet && InQuietHours(p, now))
{
return [];
}
// Security: send on the first two usable channels. Everything else: first usable channel only.
var chosen = e.Category == Category.Security ? usable.Take(2) : usable.Take(1);
return chosen
.Select(c => new NotificationIntent(e.Type, c, e.CustomerId, DedupeKey(e.EventId, e.CustomerId, c, e.Type), e.Urgent || e.Category == Category.Security))
.ToList();
}
public static string DedupeKey(string eventId, string customerId, Channel channel, string template)
{
var raw = $"{eventId}|{customerId}|{channel}|{template}";
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(raw)));
}
private static bool InQuietHours(CustomerPreferences p, DateTimeOffset now)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById(p.TimeZoneId);
var local = TimeOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, zone).DateTime);
// A window like 22:00 to 07:00 crosses midnight.
return p.QuietStart <= p.QuietEnd
? local >= p.QuietStart && local < p.QuietEnd
: local >= p.QuietStart || local < p.QuietEnd;
}
}using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
namespace Harbourline.Notifications;
public sealed class DynamoDbDedupe(IAmazonDynamoDB dynamo, string table, TimeProvider clock)
{
/// <summary>Returns true if this caller owns the key (first time), false if it was already claimed.</summary>
public async Task<bool> TryClaimAsync(string dedupeKey, CancellationToken ct)
{
try
{
await dynamo.PutItemAsync(new PutItemRequest
{
TableName = table,
Item = new Dictionary<string, AttributeValue>
{
["pk"] = new() { S = dedupeKey },
["expiresAt"] = new() { N = clock.GetUtcNow().AddHours(48).ToUnixTimeSeconds().ToString() },
},
ConditionExpression = "attribute_not_exists(pk)",
}, ct);
return true;
}
catch (ConditionalCheckFailedException)
{
return false;
}
}
}Code explained line by line
DomainEventcarries the category and urgency, set by the producing service, not by the notification platform. The planner never reads the event body.CustomerPreferencesstores channel flags, opted-out categories, quiet hours and a time zone ID. NoteVerified: an unverified phone number must never receive a message.Planfirst applies the opt-out rule: customers can opt out of every category exceptSecurity. A security event ignores the opted-out set.- It builds the list of usable channels in preference order (push, then e-mail, then SMS) from the enabled and verified flags. An empty list means nothing can be sent.
- Quiet hours do not apply to security or urgent messages. For others,
InQuietHoursconverts the instant to the customer's local time and handles windows that cross midnight (22:00 to 07:00). - Security events go to the first two usable channels for redundancy; other events use only the first, avoiding spam.
DedupeKeyhashes the event id, customer, channel and template into a stable key. The same event replayed produces the same keys, so a duplicate intent is recognisable.DynamoDbDedupe.TryClaimAsyncclaims the key with a conditional put and a TTL 48 hours ahead.truemeans "you own it, go ahead";falsemeans a duplicate and the caller drops it.
Security considerations
⚠ Learning shortcut — not for production
The planner trusts that Category is set correctly by the producing service and that preferences are current. In production, validate category assignments against a registry of event types (a marketing event must not be able to claim Security), alert when a security event produces zero intents, authenticate every event source, rate-limit per customer and per destination, and keep a kill switch per template. For one-time passcodes, prefer app-based authentication to SMS where possible, and apply strict throttling to prevent SMS pumping (fraudulent traffic that generates SMS costs) ⚠ VERIFY current guidance.
- Content rules: do not include full account numbers, balances or card numbers in SMS or e-mail. Prefer "a payment was made, open the app to review". Links to the app should be short-lived and not carry personal data in the URL.
- Spoofing: configure DKIM, SPF and DMARC for the sending domain so customers can trust genuine messages and phishers are harder to pass off. Tell customers what the bank will never ask for.
- Contact data: treat phone numbers and addresses as personal data; encrypt, restrict access, and resolve them at send time.
- Suppression: honour hard bounces and complaints automatically; honour unsubscribe immediately for marketing.
- Audit: keep evidence that a security notification was sent and, where available, delivered, for disputes ⚠ VERIFY retention.
- Least privilege: sender roles may only call the provider API for their channel and read their own queue.
- Cost abuse: SMS and voice have per-message costs; cap spend with provider limits and alarms.
Banking use case
Harbourline (fictional) sends about 3 million messages on a typical day.
- A customer adds a new payee. The accounts service emits
PayeeAdded(categorySecurity). The planner finds push and e-mail usable and sends both. Push is delivered in a second. The customer taps "This wasn't me", which triggers a fraud case and a temporary hold. The security notification is the control. - At 02:30,
PaymentSettledfor a salary credit of GBP 2,100 arrives. The customer's quiet hours are 22:00 to 07:00 and the event is not urgent, so nothing is sent; the customer sees it in the app. A GBP 40 payment failure would also wait. - EventBridge redelivers a
PaymentSettledevent. The dedupe claim fails and no second notification is sent. - The SMS provider has a 30-minute outage. SMS queue age alarms fire; security messages continue through push and e-mail; transactional SMS wait in the queue and send after recovery within their validity window.
- A marketing campaign for 800,000 customers is scheduled. It goes through a separate queue and configuration set and is rate-limited, so it cannot delay security messages.
Common mistakes
- Services sending directly → inconsistent preferences and duplicates → one platform behind an event interface.
- Using the same queue for marketing and security → campaigns delay alerts → separate paths and rate limits.
- Retrying without a dedupe key → repeated messages → deterministic key claimed before sending.
- Unverified contact details → messages to the wrong person (a data breach) → only send to verified channels.
- Putting balances and links with secrets in SMS → leaks via lock-screen and screenshots → minimal content.
- No bounce and complaint handling → reputation damage and provider suspension → process feedback events and suppress.
- Time zones ignored → messages at 03:00 → store the customer's zone and test midnight-crossing windows.
- No alarm on queue age → delays unnoticed → alarm on
ApproximateAgeOfOldestMessageand DLQ depth.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
SES MessageRejected: Email address is not verified | Account in sandbox and recipient or sender unverified | Verify both, or request production access |
SES Throttling: Maximum sending rate exceeded | Over the account send rate | Back off with jitter; lower worker concurrency; request a quota increase ⚠ VERIFY |
| Messages not reaching a queue from SNS | Queue policy missing or filter policy mismatch | Allow sns.amazonaws.com for the topic ARN; check channel attribute type is String |
RawMessageDelivery messages missing attributes | Raw delivery changes the envelope | Read attributes from SQS message attributes, not the SNS wrapper |
| Duplicate notifications | Dedupe key built differently across services, or no claim | Compute the key in one library; claim before sending |
| SMS silently not delivered | Registration or sender ID rules for the destination country | Check origination identity requirements and delivery-status logs ⚠ VERIFY |
| Push fails with invalid token | App reinstall or token rotation | Handle the invalid-token error by disabling the endpoint and falling back |
| Messages arrive hours late | Queue backed up or Lambda throttled | Check queue age, reserved concurrency and provider limits |
Cost and cleanup
Label: 🟢 free for design and the local code. At lab volumes SNS, SQS, Lambda and DynamoDB are within free allowances or cost cents ⚠ VERIFY. SES sandbox sending is cheap (per thousand messages) but not zero. SMS costs money per message and spend limits default to small values for new accounts ⚠ VERIFY, so this lesson keeps SMS design-only. Real production cost drivers are message volume by channel (SMS far above e-mail and push), Lambda invocations and logging volume.
# Delete topic, queues, and any SES configuration you created.
aws sns delete-topic --topic-arn "$TOPIC_ARN" --profile learn-sandbox --region us-east-1
for q in hl-m14-notify-email hl-m14-notify-sms hl-m14-notify-push; do
url=$(aws sqs get-queue-url --queue-name $q --query QueueUrl --output text --profile learn-sandbox --region us-east-1 2>/dev/null) \
&& aws sqs delete-queue --queue-url "$url" --profile learn-sandbox --region us-east-1
done
aws sesv2 delete-configuration-set --configuration-set-name hl-m14-transactional --profile learn-sandbox --region us-east-1
# Remove the verified e-mail identity if you created one for the lab.
aws sesv2 delete-email-identity --email-identity "<your-verified-address>" --profile learn-sandbox --region us-east-1
# Confirm nothing tagged for the course remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--profile learn-sandbox --region us-east-1Exercises
- 🟢 Guided: write unit tests for
NotificationPlanner.Plan: a marketing event for an opted-out customer yields no intents; a security event for an opted-out customer still yields two intents; a transactional event at 23:30 local time for a customer with 22:00 to 07:00 quiet hours yields none; the same event marked urgent yields one. - 🟡 Challenge: add an
IDateProvider-free rule: if a security event has no usable channel, the planner returns a specialNotificationIntentwith templatesecurity-no-channelfor the operations queue. Update the tests and explain why silent loss is unacceptable. - 🔴 Live problem: after a release, customers report receiving the same "payment received" message three times. You have the planner, dedupe code and queue settings. List five possible causes in order of likelihood, the evidence you would collect for each, the immediate mitigation and the permanent fix.
Assignment
Write the 15-section notification architecture in architecture/notifications/: the flow diagram, the category and rules table with owners, the preference data model, the dedupe and retry design, the provider failure and fallback table, the delivery-evidence design, an ADR on "separate paths for security and marketing", and the compliance touchpoints (marketing consent, mandatory notices, data protection, third-party risk for providers). Include the planner with tests.
Solutions
using Harbourline.Notifications;
using Xunit;
public class NotificationPlannerTests
{
private static CustomerPreferences Prefs(params Category[] optedOut) => new(
"CUS-00000042",
new Dictionary<Channel, ChannelPreference>
{
[Channel.Push] = new(true, true),
[Channel.Email] = new(true, true),
[Channel.Sms] = new(false, true),
},
optedOut.ToHashSet(),
new TimeOnly(22, 0), new TimeOnly(7, 0), "Europe/London");
private static readonly DateTimeOffset NightUtc = new(2026, 11, 18, 23, 30, 0, TimeSpan.Zero); // 23:30 in London in November (GMT)
[Fact]
public void Marketing_opt_out_yields_nothing() =>
Assert.Empty(NotificationPlanner.Plan(new("E1", "offer", "CUS-00000042", Category.Marketing, null, false), Prefs(Category.Marketing), NightUtc.AddHours(12)));
[Fact]
public void Security_ignores_opt_out_and_uses_two_channels()
{
var intents = NotificationPlanner.Plan(new("E2", "payee-added", "CUS-00000042", Category.Security, null, false), Prefs(Category.Security), NightUtc);
Assert.Equal(2, intents.Count);
}
[Fact]
public void Quiet_hours_suppress_non_urgent_transactional() =>
Assert.Empty(NotificationPlanner.Plan(new("E3", "payment-settled", "CUS-00000042", Category.Transactional, 40m, false), Prefs(), NightUtc));
[Fact]
public void Urgent_transactional_bypasses_quiet_hours() =>
Assert.Single(NotificationPlanner.Plan(new("E4", "payment-failed", "CUS-00000042", Category.Transactional, 40m, true), Prefs(), NightUtc));
[Fact]
public void Dedupe_key_is_stable_and_channel_specific()
{
var a = NotificationPlanner.DedupeKey("E1", "C1", Channel.Push, "t");
Assert.Equal(a, NotificationPlanner.DedupeKey("E1", "C1", Channel.Push, "t"));
Assert.NotEqual(a, NotificationPlanner.DedupeKey("E1", "C1", Channel.Email, "t"));
}
}Why: November in London is GMT (UTC+0), so 23:30 UTC is 23:30 local and falls inside the 22:00 to 07:00 window that crosses midnight. The test using NightUtc.AddHours(12) is outside quiet hours but irrelevant for the opt-out case. In summer the same UTC time would be 00:30 local, which is why tests should pin their date.
Add before the usable.Count == 0 return: if the event category is Security, return a single intent for an internal "operations" channel (extend the Channel enum with Operations) with template security-no-channel. Why: a security alert that silently disappears because the customer has no verified channel leaves the customer unprotected. Operations can attempt contact by another route and the missing channel is visible on a dashboard. Test that a security event with all channels disabled yields exactly one Operations intent, and that a marketing event with no usable channel still yields none.
Likely causes: (1) EventBridge redelivered the event and the planner has no dedupe claim or a different key per attempt (for example includes a timestamp); (2) the sender Lambda crashes after the provider accepted, so SQS redelivers and the sender has no dedupe; (3) two rules route the same event type to the planner (a new rule added in the release); (4) visibility timeout shorter than processing time, so the message becomes visible while still being processed; (5) a producer now publishes the event three times. Evidence: look at event ids and intent ids in logs, provider message ids per intent, queue receive counts, and the rule list on the bus. Immediate: enable the dedupe claim in the sender too and extend visibility timeout. Permanent: claim at both planning and sending, include an idempotency key in the provider call where supported, and add an integration test that replays each event twice.
Knowledge check
Answer: Planning is cheap and decides policy; delivery depends on slow external providers with different failure modes. Queues let each channel scale, retry and fail independently, so an SMS outage does not block e-mail or planning.
Answer: Security notices are a protective control and are often required. Marketing needs consent. The platform enforces the difference by category, and customers may choose channels for security messages but not turn them all off. The exact legal position needs compliance review.
Answer: The planner computes a deterministic key from the event id, customer, channel and template and claims it with a conditional put. The second delivery fails the claim and is dropped.
Answer: New accounts can send only to verified addresses (and the mailbox simulator) and at low quotas until production access is granted. It prevents abuse by new accounts, so learners must verify their own addresses for tests.
Answer: Depth can be small while one stuck message is hours old, and a healthy busy queue can have large depth but young messages. Age measures what the customer experiences: how late the notification will be.
Interview questions
- How would you design customer notifications for a bank? Events into a planner that applies category and preference rules, intents fanned out by channel into queues, adapters per provider with retry and dedupe, delivery tracking and a separate path for security versus marketing.
- How do you stop duplicate messages? Deterministic dedupe keys claimed with conditional writes, provider idempotency where available, and idempotent consumers at every at-least-once boundary.
- What happens if the SMS provider is down? Messages wait in the SMS queue; alarms fire; security messages use other channels; transactional ones send later if still relevant; the provider failure is part of third-party risk.
- What do you avoid putting in an SMS? Balances, full account or card numbers, long-lived links, or anything useful to an attacker who sees the lock screen.
- How do you handle bounces and complaints? Subscribe to provider feedback events, suppress hard bounces and complainants, and monitor rates because providers may throttle senders with poor reputation.
Certification practice
A bank sends notifications by e-mail, SMS and push. An outage at the SMS provider must not delay e-mail or push. Which architecture best achieves this?
A. One Lambda function that calls all three providers in sequence B. An SNS topic fanning out to separate SQS queues per channel, each with its own consumer and dead-letter queue C. One SQS queue for all channels with one consumer D. Cron jobs on a single EC2 instance
Answer: B. Separate queues isolate failures and allow independent scaling. A and C couple the channels, so one slow provider blocks the rest. D is a single point of failure.
A Lambda function processes SQS messages and sometimes crashes after sending an e-mail but before deleting the message, causing duplicate e-mails. What should the developer do?
A. Increase the Lambda timeout only B. Make the handler idempotent by claiming a deduplication key (such as a DynamoDB conditional write) before sending C. Disable retries by lowering the queue retention D. Switch to a larger batch size
Answer: B. SQS standard queues are at-least-once, so the consumer must tolerate redelivery. A, C and D do not stop duplicates.
A bank's SMS notifications currently include the customer's full balance. Which change best reduces risk?
A. Send balances in bold text B. Remove balance and account details from SMS and direct the customer to view them in the authenticated app C. Encrypt the SMS text with a key stored in the same message D. Send the SMS twice
Answer: B. SMS is not a confidential channel. Minimal content with an authenticated destination reduces exposure. The others do not.
A marketing campaign to 800,000 customers must not delay fraud alerts that use the same providers. What is the best design?
A. Send campaigns and alerts from the same queue in random order B. Use separate queues, concurrency limits and provider configuration (or accounts) for marketing and security, with rate limiting on the campaign path C. Run campaigns only at night with no limits D. Disable fraud alerts during campaigns
Answer: B. Isolation protects the critical path from bulk traffic. A can delay alerts, C can still exhaust shared provider limits, and D is unacceptable.
Completion checklist
- I can draw decide, deliver and record, with queues between stages
- I can explain category rules, quiet hours and why security cannot be opted out
- I wrote and ran planner tests including a midnight-crossing quiet window
- I can explain the dedupe key and where it is claimed
- My architecture keeps SMS design-only unless I understood the cost and registration rules
- I ran the cleanup steps and confirmed nothing tagged
Project=cea-labremains
Key takeaways
- Notifications are a platform: plan once, deliver per channel, record evidence.
- Category decides policy: security cannot be silenced, marketing needs consent.
- At-least-once everywhere means deterministic dedupe keys at the planner and the sender.
- Isolate channels and traffic classes with separate queues, limits and provider configuration.
- Keep messages minimal, resolve contact data late and honour bounces, complaints and unsubscribes.
Further reading
- Amazon SES developer guide
- Amazon SNS message filtering
- Amazon SQS dead-letter queues
- Previous: Fraud-detection integration · Next: Reporting and regulatory reporting architecture · Module overview: Module 14
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Fraud-detection integration: rules, ML scoring and human review
Integrate fraud signals into banking flows without relying on services closed to new customers: layered rules on Kinesis and Lambda, optional ML scoring through SageMaker AI, Bedrock for analyst summaries (never for the decision), a human review queue built from SQS and DynamoDB, and a feedback loop.
Reporting and regulatory reporting architecture
Design a governed reporting pipeline on S3, Glue and Athena where every submitted figure can be reproduced, traced to its sources, approved by a second person and retained immutably, and verify that with a small C# manifest tool.