Blog

How to Set Up Multi-Channel Notifications in Your AWS Stack

Seth CarneySeth CarneySeptember 09, 2021
notifications-aws-stack-header

If your infrastructure already runs on AWS, Amazon SES and Amazon SNS can deliver your email, push, and SMS notifications. What they don't do is decide which notification goes to whom. Here's an example architecture for the service that does, a Node.js implementation, and the limits you'll work around.

Why use AWS services for multi-channel notifications?

The main reason to build on AWS is that you're already there: you know the APIs, IAM, and the AWS Management Console. The two AWS services this example uses are Amazon SES and Amazon SNS. Both have pay-per-use pricing, so cost grows with your volume.

Amazon Simple Email Service (Amazon SES) is an API for sending email and managing contact lists. The SES API v2 covers sending email and managing contact lists, plus deliverability features like the dedicated IP addresses SES sends your email from.

Amazon Simple Notification Service (Amazon SNS) is an API for sending messages to applications and people. For notifications, the "people" part is what matters: SNS sends mobile push notifications and SMS. You can publish to a single phone number or device endpoint, or publish once to an SNS topic and reach every subscriber. SMS origination numbers, sender IDs, and country registrations are managed in AWS End User Messaging SMS.

Multi-channel notification system architecture for AWS

SES and SNS provide APIs for sending notifications, but it's still your job to tell them which notifications to send, and to whom.

Here's an example architecture for a notification system on AWS: notifications-aws-stack-1

A common pattern in a service-oriented architecture is to extract notification logic into a standalone service. In our example architecture, the notification service contains a few core pieces of functionality:

  • Templates: most notifications you send follow a standardized format. Templates let you create that format once and then replace placeholders with user information.
  • Error handling: when a notification can't be delivered, whether because the end user is unreachable or the notification APIs are down, you'll likely need to try and resend it.
  • Preferences: you'll need to store user choices for message categories such as account-related notifications or marketing messages.
  • User profiles: you'll want to store user emails and phone numbers.
  • Notification routing: this is the core logic for deciding which notification should be sent based on event type, user preference, user location, and other factors.
  • Tracking: to analyze the effectiveness of your notifications, you'll need to track interactions with individual notifications.

The notification service usually needs to expose an API that other services can connect to. The API can be synchronous, available through an HTTP REST or gRPC endpoint, or asynchronous and based on a message broker, like RabbitMQ.

Beyond the code in the notification service itself, you'll want metrics in a centralized metrics store. Whoever runs the service tracks its status through metrics like the number of notifications sent per hour, or the share of API errors from each provider. If the service has a queue-based API, publish the queue size as a metric too. These metrics tell you whether the service is behaving normally, or whether something needs attention.

While the service connects to third-party sending services (SES and SNS, in our case), you can extend it to support other providers later.

Sample implementation of a notification service

Check out How to Send Emails with Attachments Using Amazon SES and S3

Let's walk through a notification service implementation in code. For this example, we'll use a Node.js web framework called Fastify. It's a lightweight framework that's optimized for speed, which is exactly what we need in an internal REST service.

We'll implement a REST API as our interface to the notification service, but your implementation can have a different structure, such as a gRPC API or a consumer that reads messages off a RabbitMQ queue.

The example uses Fastify 5 and the SES v2 client from the AWS SDK for JavaScript v3. Create a project and install both:

Terminal
mkdir notification-service && cd notification-service
npm init -y
npm pkg set type=module
npm install fastify @aws-sdk/client-sesv2

All of the code below goes in one file, index.js. Start with the imports and an SES client:

JavaScript
// index.js
import Fastify from 'fastify'
import {
  SESv2Client,
  CreateEmailTemplateCommand,
  GetEmailTemplateCommand,
  SendEmailCommand,
  NotFoundException
} from '@aws-sdk/client-sesv2'

const sesClient = new SESv2Client({ region: process.env.AWS_REGION })

The SDK finds your AWS credentials through its default credential provider chain (environment variables, your shared AWS config files, or an IAM role), so they stay out of your code.

Now we'll define an email template. We'll use SES's built-in template functionality, but you could use a library like mustache.js or build your own templating system instead. Our template object contains the fields that SES requires in its API:

JavaScript
const paramsForTemplateCreation = {
  TemplateName: 'MigrationConfirmation',
  TemplateContent: {
    Subject: 'Get ready for your journey, {{name}}!',
    Html: "<h1>Hello {{name}},</h1><p>You are confirmed for the winter migration to <a href='https://en.wikipedia.org/wiki/{{location}}'>{{location}}</a>.</p>",
    Text: 'Dear {{name}},\r\nYou are confirmed for the winter migration to {{location}}.'
  }
}

We'll need to create this template in SES, so we'll add a function that creates a template with the AWS SDK:

JavaScript
async function createTemplate (params) {
  const data = await sesClient.send(new CreateEmailTemplateCommand(params))
  console.log('Template created', data.$metadata.httpStatusCode)
}

SES returns an error if you create a template that already exists, so we check first. We try to get the template by name, and if SES answers with NotFoundException, we create it. Any other error (bad credentials, for example) is rethrown so it doesn't get silently swallowed:

JavaScript
async function createTemplateIfNotExists (params) {
  try {
    await sesClient.send(new GetEmailTemplateCommand({ TemplateName: params.TemplateName }))
  } catch (err) {
    if (!(err instanceof NotFoundException)) throw err
    await createTemplate(params)
  }
}

We won't add many other features to our templating system for now.

Next, let's take care of sending. In the SES API v2, a templated email goes through the same SendEmail operation as any other email, with the template named in its Content:

JavaScript
async function sendTemplatedEmail (params) {
  const data = await sesClient.send(new SendEmailCommand(params))
  console.log('Sent', data.MessageId)
  return data // For unit tests
}

In this function, we pass the parameters we receive to SendEmailCommand. Let's also create a set of placeholder parameters so we can call sendTemplatedEmail when we need to:

JavaScript
const paramsForTemplatedEmail = {
  FromEmailAddress: 'nightjar@example.imap.cc',
  Destination: {
    ToAddresses: ['kingfisher@example.imap.cc']
  },
  Content: {
    Template: {
      TemplateName: 'MigrationConfirmation',
      TemplateData: JSON.stringify({ name: 'Alaric', location: 'Mexico' })
    }
  }
}

New SES accounts start in the SES sandbox, where you can only send to verified email addresses and domains. Verify both addresses (or request production access) before you test.

Now it's time to define the API routes that our services will use to send notifications. We define the main route, /notify, with Fastify's shorthand declaration:

JavaScript
const app = Fastify({ logger: true })

app.post('/notify', async (req, reply) => {
  const { userId, event, params } = req.body
  switch (event) {
    case 'migration-confirmed':
      await sendTemplatedEmail(paramsForTemplatedEmail)
      return 'migration-confirmed email sent'
    default:
      return 'event not configured'
  }
})

Here, we're defining the POST /notify endpoint. Once the application receives a request to the /notify URL, it'll parse out the following elements from the request body:

  • userId: an internal user identifier.
  • event: an event type requiring user notification.
  • params: any additional parameters for building out notification contents.

Based on the event value, we'll need to decide which notification to send. Some products have complex notification routing logic, but we'll start with a single switch statement. A long switch statement becomes unmaintainable as you add events, so this section should eventually be split into multiple functions.

We only have migration-confirmed defined for now, and when that event occurs we want to send an email notification. Other calls to services, like Amazon SNS, would go inside the statement that handles the migration-confirmed event. Because the handler awaits the send, a failed SES call comes back to the caller as a 500 error instead of a false "sent" message.

Beyond the /notify endpoint above, we can create additional endpoints as needed. For example, here are a few endpoints that your notification service will need (we'll leave implementation up to you):

JavaScript
app.post('/subscriber', async (req, reply) => {
  const { userId, email, phoneNum } = req.body
  // handle new subscribers
  return 'handling of new subscribers not yet implemented'
})

app.delete('/subscriber/:userId', async (req, reply) => {
  const userId = req.params.userId
  // unsubscribe user identified by userId from all emails
  return 'handling of unsubscribes not yet implemented'
})

app.put('/subscriber/:userId/preferences', async (req, reply) => {
  const { preferences } = req.body
  // handle subscription preferences
  return 'handling of preferences not yet implemented'
})

Finally, we make sure the template exists and tell our Fastify backend to listen on port 3000:

JavaScript
await createTemplateIfNotExists(paramsForTemplateCreation)
await app.listen({ port: 3000 })

Let's start the app and try it out:

Terminal
AWS_REGION=us-east-1 node index.js

Fastify's logger prints the address it's listening on:

Text
{"level":30,"time":1793646955091,"pid":16999,"hostname":"notification-service","msg":"Server listening at http://127.0.0.1:3000"}

Now we'll send a POST request to the /notify endpoint. We'll use cURL for this, but you can also use an app like Postman:

Terminal
curl -X POST \
   -H 'Content-Type: application/json' \
   -H 'Accept: application/json' \
   -d '{"userId": 123, "event": "migration-confirmed"}' \
   localhost:3000/notify

We can see the notification email land in our inbox shortly after calling the endpoint:

notifications-aws-stack-2 Email notification in our test inbox.

Nice work! You now have a working notification service on AWS.

Limitations to AWS notification solutions

Before you jump into the design and implementation phases for your AWS-backed notification service, consider the following limitations to AWS services.

AWS services are "raw"

Think of SES and SNS as services with APIs that closely resemble the underlying delivery protocols. Both leave you to build most features that aren't core to sending.

Attachments are one example. The SES API v2 SendEmail operation accepts an Attachments list on simple and templated emails, so you no longer have to build multipart MIME messages by hand. Getting each file out of storage and onto the right send is still your code.

Contact management is another area where SES needs extra work. If you use SES contact lists, you'll build the logic for adding and removing contacts on each list and keeping them in sync with your own user records.

SNS is limited in the same way. It retries a failed delivery, then discards the message unless you've attached a dead-letter queue to the subscription.

Error-checking is laborious

Another side of AWS's "rawness" is error-checking. You need to catch email bounces and undelivered push notifications and act on them yourself.

SES helps on the email side. Its account-level suppression list is on by default for accounts created after November 25, 2019, and SES stops sending to addresses that hard bounced or complained. Your application doesn't learn about those addresses, though, until you set up bounce and complaint notifications and update your own records.

On SNS, the dead-letter queue you attach is an Amazon Simple Queue Service (SQS) queue, so you'll write a consumer (or attach a Lambda function) that reads failed messages from it.

When you get a failed delivery, you'll need to decide whether to try the notification again (and schedule it in your notification service accordingly), or send it through an alternative notification method (a different channel or provider). You'll also need to track which push targets and email addresses are consistently unresponsive and remove them from future sends.

You can build error-handling functionality with SNS and SES, since both services expose the details for each error case. But you'll be building and maintaining it yourself.

You'll need to build a templating engine

While you can readily implement basic email and notification templates using SES templates or tools like mustache.js, complex templates, like elaborate HTML emails, are another story.

You'll need to test your templates to make sure they work as expected on all supported devices and clients. Email formatting is difficult to get right, so we recommend budgeting extra time to develop and test your templates.

How Courier works with your AWS stack

Courier is an API for multi-channel notifications. Courier runs on AWS and connects to Amazon SES and Amazon SNS (for push and SMS) as providers, so you keep sending through your own AWS accounts without building the extra layer on top.

Here's how you might send an email and SMS notification with the Courier Node.js SDK:

JavaScript
import Courier from "@trycourier/courier";

const courier = new Courier({ apiKey: process.env.COURIER_API_KEY });

// Send one template over email and SMS
const { requestId } = await courier.send.message({
  message: {
    to: {
      user_id: "<USER_ID>", // usually your system's user ID
      email: "kingfisher@example.imap.cc",
      phone_number: "+15552283890",
    },
    template: "<TEMPLATE_ID>", // the template's ID from Design Studio
    data: { name: "Alaric", location: "Mexico" }, // variables for the template
    routing: { method: "all", channels: ["email", "sms"] },
  },
});

Courier calls SES and SNS for you and takes on a lot of the work above:

  • Design Studio: a visual editor for templates, so you can create and edit them without redeploying code. Adding a new notification to your product takes less engineering work.
  • Automated handling of unsubscribes: Courier blocks sends to users who opted out of a topic and records the reason in the message logs. See preferences.
  • Multi-provider: down the line, you may want to switch away from SNS or SES, or add another provider for international SMS. Courier integrates with 50+ providers, all through the same API, and a routing strategy change switches providers on every template that uses it.

Conclusion

SES and SNS handle delivery. The notification service around them (templates, preferences, routing, and error handling) is the part you build and keep running. If you'd rather not own that layer, Courier connects to the same SES and SNS accounts and handles it for you.

The Developer plan includes 10,000 messages a month free.

Sign up for free today!