Blog

Notification routing and preferences: a developer’s guide

Troy GoodeTroy GoodeNovember 18, 2021
routing-and-preferences-header

A routing and preferences service decides, for every notification, which channel and provider to use and whether the user wants it at all. You build it from four pieces: channels and providers behind your own abstraction layer, routing rules with fallbacks, granular user preferences that the router checks on every send, and the compliance rules for each channel. For the requirements side of the project, see our guide to building a user notification system. For delivery, see scalability and reliability.

Notifications serve a range of purposes, from delivering news to providing crucial security alerts that require immediate attention. A reliable notification system both enables valuable interactions between an organization and its customers and prospects and also drives user engagement. These systems combine software engineering with the art of marketing to the right people at the right time.

Building a service capable of dynamically routing notifications and managing preferences is vital to any notification system. But if you’ve never built a system like this, it might be difficult to figure out what the requirements are and where the edge cases lie.

Multi-channel support: a necessity

Let’s say that you’ve built a web-based application. The first channel that you’ll use to connect with your users is likely email because of how ubiquitous it is. However, with the diversification of channels and depending on your use case, email might not be the most efficient notification channel for you.

To engage with your users more effectively, you’ll want to support channels across a broad range of systems not limited to any one application or device. It’s vital to understand not only which channels are most relevant for you but also for your users. If you opt to use Telegram and your users don’t have it, it won’t be a very useful channel to interact with them. Multi-channel support is also vital because while you might pick appropriate channels today, you won’t know which channels you will need to support in the future. Typically, the more appropriate channels you support, the higher the chances of intersecting with applications your users actually use now and in the future.

Choosing notification channels and providers

You’ll have to select relevant channels and appropriate providers for each channel. For example, two core providers for mobile push notifications are Apple Push Notification Service (APNs) and Firebase Cloud Messaging (FCM). APNs only supports Apple devices while Firebase supports both Android and iOS as well as web apps.

In the world of email providers, SendGrid, Mailgun, and Postmark are all popular but there are hundreds more. All email APIs differ in what they offer, both in supported functionality and API flexibility. Providers differ in whether they handle transactional email, marketing email, or both. SendGrid and Brevo (formerly Sendinblue), for example, offer both. If your company opts for a provider that can handle both, you’ll still want to separate the traffic sources, by using different email addresses or domains, to aid email deliverability. If you only have one domain for sending both types of emails and the domain gets flagged as spam, your critical transactional emails will also be affected. Whichever provider you choose, you’ll still want to meticulously verify your DKIM, SPF, and DMARC checks, and domain and IP blacklisting using your own tools or a site like Mail-Tester.

Making requests and receiving responses also differs with each email API provider. Attachments are one example: Mailgun takes each file as an attachment parameter on the send request, while the Amazon SES v2 API takes an Attachments array on the message. (If your files live in S3, here’s how to send email attachments from AWS S3 with Courier.)

There are minute variances in formatting HTTPS requests. Per-message size limits differ too: the Amazon SES v2 API allows 40 MB per message and Postmark allows 10 MB (50 MB for a whole batch request), both counted after base64 encoding. There are also differences between the rate limits for requests.

In terms of API responses, Amazon SES provides a message identifier when an email is sent successfully through the API, but, for example, SendGrid returns an empty response in that situation. The HTTP response codes also differ slightly depending on the provider. For example, AWS SES uses the response code 200 for successful email send operations, while Brevo (formerly Sendinblue) uses 201, and SendGrid uses 202.

No matter which provider you end up choosing, don’t build your application solely to fit their logic and specifications. If you do so, it will be much more difficult to change providers in the future as you’ll have to overhaul your backend. It’s crucial to invest in a layer of abstraction based on your own paradigm.

Dynamically routing notifications between channels

How do you determine which channels to use and when? Having email, SMS, and mobile push available doesn’t mean that you should use all of them simultaneously, since doing so carries a high risk of annoying your users. This is where you begin to formulate an algorithm to route messages between the different channels and the different providers within each channel. The algorithm needs to be robust to handle delivery failures and other errors. For example, if the user hasn’t engaged with a push notification after a day, do you resend it or use email instead?

You can begin constructing the algorithm using basic criteria. For example, if there is no phone number, eliminate SMS as an option for that user. If the user chose a delivery time in their preferences, send at that time. If the user is present or active in the app, consider sending an in-app notification instead of an email. Finally, and especially important, get your user’s preferences for how and when they want to be contacted and integrate these preferences into your routing service.

Adding user preferences to your system

Once you’ve got your channels, providers, and routing algorithm figured out, you need to think about providing users with granular control over notification preferences instead of a binary opt-in/opt-out switch.

Consider this: if you only allow opting in to or out of all notifications at once, your users might unsubscribe from all your communications because they find one specific notification annoying. As a result, you will lose out on valuable user engagement.

With granular control over preferences, a user identifies exactly how and when they hear from you. If a user doesn’t like email but wants SMS messages (not common, but possible!), they can adjust their preferences and keep the SMS line of communication open. Every enabled notification channel is another opportunity to engage the user in a way that’s productive for them. From the end user’s perspective, it’s empowering to control how and when they are contacted.

Note that for some notifications, the user’s preferences should be ignored. For instance, two-factor authentication should go to SMS or mobile push regardless of the user’s preference for email. The possibility to override the default logic should be incorporated into your algorithm while you are designing your routing engine.

If you want to take user engagement further, allow users to opt-in/opt-out of specific channels, frequency, timing and topics. You can allow them to set up their preferences based on time of day, frequency per period, or to specify more than one email address. You can give them the option to receive transactional, digest emails, daily newsletters, or only the critical ones. You can also allow them to redirect their notifications to another address, for example if the user is out of office.

Granular preferences also extend past your engineering work and the user’s experience. Granularity of consent is becoming part of privacy compliance laws in Europe and in the state of California and might follow elsewhere in the future. Separately, granular preferences are an extremely advantageous analytical tool for the marketing team to improve brand strategy and personalization efforts. Is there a particular channel or topic that seems to be more popular? That information can be highly helpful to pivot in line with your users and grow your company.

Tips for future-proof maintenance

When you’re starting with notifications for a new product, there is nothing wrong with sticking to one channel and one provider. The most important principle to keep in mind is to design your notification system so that you can expand it in the future. You should leave the door open to include more providers when you need them.

Don’t assume that API paradigms are the same for each provider or notification type. For example, you want to send an email, and if delivery fails to send a push notification instead. But you won’t get a 400 HTTP response from the email provider in case of failure. The provider will retry your email over a couple of days. Instead, you’ll want to include webhooks or queues to notify you of the failure, and you’ll need to track the state of the message here. If you make blanket assumptions about how API calls work or how errors are returned, you’ll have trouble adapting to a different paradigm in the future. Instead, you can add a layer of abstraction on top of the API.

It’s also invaluable to centralize the way you call the provider APIs. If you spread out calls to an API throughout your code base, it will be more difficult to integrate other channels or API providers in the future. Let’s say you’re starting with email and AWS SES as the provider. In two years’ time, you might decide to integrate mobile push notifications as well. What might that look like? The incurred technical debt will include scouring the code base for all instances of calls to the AWS SES API before you can integrate mobile push as an additional channel. But with centralized calls, you’ll have more consistent, cleaner, and reusable code as you grow.

How many notification channels should you have?

Typically, having three or four channels that are relevant to your product is an ideal scenario for a mature product. When you intersect channels with the preferences and availability of users, you create higher levels of complexity for your algorithm. Offering many channels for notifications might become too complex to maintain. But offering too few channels might harm your chances of interacting with users since some channels might not be viable for all users. For instance, you might decide to offer email and push notifications. But if a user didn’t download your product, your interaction with them is limited only to email.

Best technologies for routing and preferences engines

It ultimately pays to choose technologies that will be a good fit for your routing and preferences needs. There will be a great deal of asynchronous programming, as the routing service will often be waiting to receive responses for each function. You’ll want to pick a language or a framework that allows you to respond to async events at scale.

The routing service also involves considerable state tracking, as most of the routing will depend on waiting on a response for each notification before changing state. The routing service will also need to be re-activated every time it receives a response from a provider and will need to determine if the notification was sent successfully or if it has to pursue next steps. See the example below of how a notification function’s state might be tracked.

an example of notification state tracking

When we wrote this in 2021, Courier used AWS Lambda. Since our usage tended to come in bursts, serverless technology let us adjust and scale for changes in demand throughout each day as well as handle asynchronous operations efficiently.

Don’t forget: compliance in notification routing

When creating your own routing and preferences service, you will need to ensure that whichever channels you implement are fully compliant with applicable laws. For example, there are legal mandates on how users may be contacted or how they can unsubscribe from contact.

For commercial email messages, the CAN-SPAM Act of 2003 is a federal United States law that spells out distinct rules and gives recipients a way to stop all contact. Penalties can cost as much as $53,088 per email in violation, according to the FTC. This law also outlines requirements such as not using misleading header information or subject lines, identifying ads, and telling recipients how they can opt out of all future email from you. The opt-out process itself is strictly regulated.

For SMS, the United States Telephone Consumer Protection Act (TCPA) of 1991 sets forth rules against telemarketing and SMS marketing. Under this law, businesses cannot send messages to a recipient without their consent. This consent needs to be explicit and documented. The consent is also twofold: recipients need to consent to receiving SMS marketing messages and they need to consent to receiving them on their mobile device. Carrier rules (the CTIA Messaging Principles and Best Practices) add disclosure requirements on top: tell recipients what they’re subscribing to, how many messages to expect, where your terms and privacy policy live, and how to opt out.

In California especially, the California Consumer Privacy Act (CCPA) of 2018 provides additional rights for California residents only. These rights include the right to know which information a company has collected about them and how it’s used as well as the right to delete it or to opt-out of the sale of this information. Information that qualifies under the consumers’ right-to-know includes names, email addresses, products purchased, browsing history, geolocation information, fingerprints, and anything else that can be used to infer preferences. Should a consumer request this information, the company has to share what it collected, where it came from, and who it was shared with. The California Privacy Rights Act (CPRA), passed in 2020, amended the CCPA. The CPRA provides further consumer rights to limit the use and disclosure of their personal information.

Other countries have their own compliance laws for businesses reaching out to leads and customers. Canada has its Anti-Spam Legislation (CASL). The European Union has the General Data Protection Regulation (GDPR) which now also covers granularity of consent. The United Kingdom has its own regulations along with the GDPR, the Privacy and Electronic Communications Regulations (PECR) and Data Protection Act.

Compliance itself needs to be built into your code. Providers, like SendGrid, don’t know what you’re sending. It’s up to you to make sure your notifications follow every compliance law that applies to the channels you choose.

How Courier handles routing and preferences

If you’d rather not build this yourself, Courier handles both at send time. Routing works in two steps: Courier picks channels from the route’s channel list, then picks providers inside each channel in priority order. With the single method, it tries each option in order and stops at the first that delivers, so a user with no push token still gets the email. It skips a provider that can’t reach the recipient, such as an SMS provider for a user with no phone number, and retries transient errors like rate limits before moving on. You save a route as a routing strategy or pass one on the send.

Preferences resolve at send time too. You map a template to a subscription topic, and Courier layers the topic’s default, any tenant defaults, and the user’s own choices. A topic set to REQUIRED always delivers, which covers the two-factor case above. An opted-out topic blocks the send, and a user who picked their own channels for a topic gets those channels instead. To let users make those choices, add a preference center to your app.

Conclusion

Building a notification system into a product is not for everyone. The process is time-consuming, complex, and expensive. The level of notification customizability and routing options you decide to implement will ultimately dictate a preference for either maximizing user engagement or optimizing cost. If your product hasn’t found product-market fit yet, focus on finding early customers and getting their feedback. If you’re an established company with a proven customer base, you’ll have concerns about more complex routing logic, future-proofing, and compliance, which means more functionality and higher maintenance costs.

Once routing and preferences are in place, you’ll want to see what your notifications are doing in production. See what notification observability is and how to monitor it.