Building an Asynchronous Notification System Using AWS SNS, SQS, and SES
Explore how to build a scalable event-driven notification system using AWS SNS, SQS, and SES. Learn how these services work together to process events asynchronously and deliver reliable email notifications using Java Spring Boot.
Building an Asynchronous Notification System Using AWS SNS, SQS, and SES
Introduction
In modern applications, sending notifications is an important requirement. Consider an e-commerce application where customers need to receive emails whenever an order is placed, payment is completed, or a product is shipped.
If the main application handles all notification operations directly, it can increase response time and create unnecessary dependencies.
To solve this problem, we can use an event-driven architecture with three AWS services:
- Amazon SNS: Distributes messages to multiple subscribers.
- Amazon SQS: Stores messages and enables asynchronous processing.
- Amazon SES: Sends transactional email notifications.
In this article, we will explore how these services work together to build a scalable notification system.
1. Understanding the Architecture
Let's consider an order management application.
Whenever a customer places an order, the application publishes an event to an SNS topic. SNS distributes that event to multiple SQS queues, where independent consumers process the messages.
The email consumer retrieves the message from SQS and uses SES to send an email to the customer.
Architecture Workflow
- Customer places an order.
- Order Service saves the order details.
- Order Service publishes an event to SNS.
- SNS distributes the event to subscribed SQS queues.
- Email Consumer receives the message from SQS.
- Amazon SES sends an email to the customer.
- The consumer deletes the message after successful processing.
Architecture Diagram
text
Order Service | v SNS Topic | +---------+---------+ | | v v Email Queue Warehouse Queue | v Email Consumer | v Amazon SES | v Customer Email
2. AWS Services Involved
Amazon SNS
Amazon SNS is a publish/subscribe messaging service.
It allows applications to publish messages to a topic and distribute them to multiple subscribers.
For example, an order event might look like this:
json
{ "eventType": "ORDER_PLACED", "orderId": "ORD1001", "customerEmail": "customer@example.com", "amount": 2500, "status": "CONFIRMED"}
SNS distributes this event to subscribed SQS queues.
Amazon SQS
Amazon SQS is a managed message queuing service that enables asynchronous communication between application components.
We can create separate queues for different activities:
-
OrderEmailQueue
-
WarehouseQueue
-
OrderAuditQueue
Each queue can have its own consumer, allowing independent processing.
Amazon SES
Amazon SES is a cloud-based email service used to send transactional emails.
In our application, SES sends order confirmations, payment receipts, and shipping notifications to customers.
3. Implementing with Java Spring Boot
Let's look at a simple implementation using AWS SDK for Java 2.x.
Maven Dependencies
xml
<dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>sns</artifactId></dependency>
<dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>sqs</artifactId></dependency>
<dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>sesv2</artifactId></dependency>
Publishing an Event Using SNS
java
@Servicepublic class OrderEventPublisher {
private final SnsClient snsClient;
@Value("${aws.sns.topic-arn}") private String topicArn;
public OrderEventPublisher(SnsClient snsClient) { this.snsClient = snsClient; }
public void publishEvent(String message) {
PublishRequest request = PublishRequest.builder() .topicArn(topicArn) .message(message) .build();
snsClient.publish(request); }}
Whenever an order is created, the application publishes an event to SNS.
Consuming Messages Using SQS
A background worker retrieves messages from the email queue.
java
@Servicepublic class OrderEmailConsumer {
private final SqsClient sqsClient; private final EmailService emailService;
@Value("${aws.sqs.email-queue-url}") private String queueUrl;
public OrderEmailConsumer( SqsClient sqsClient, EmailService emailService) { this.sqsClient = sqsClient; this.emailService = emailService; }
@Scheduled(fixedDelay = 5000) public void consumeMessages() {
ReceiveMessageResponse response = sqsClient.receiveMessage( ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(10) .waitTimeSeconds(20) .build() );
for (Message message : response.messages()) { try { emailService.processOrderEmail( message.body() );
sqsClient.deleteMessage( DeleteMessageRequest.builder() .queueUrl(queueUrl) .receiptHandle( message.receiptHandle() ) .build() );
} catch (Exception e) { // Log the failure and allow retry. } } }}
Sending Emails Using SES
The Email Service uses Amazon SES to deliver notifications.
java
@Servicepublic class EmailService {
private final SesV2Client sesClient;
public EmailService(SesV2Client sesClient) { this.sesClient = sesClient; }
public void sendEmail( String recipient, String subject, String body) {
SendEmailRequest request = SendEmailRequest.builder() .fromEmailAddress("noreply@example.com") .destination( Destination.builder() .toAddresses(recipient) .build() ) .content( EmailContent.builder() .simple( Message.builder() .subject( Content.builder() .data(subject) .build() ) .body( Body.builder() .text( Content.builder() .data(body) .build() ) .build() ) .build() ) .build() ) .build();
sesClient.sendEmail(request); }}
The sender email address must be verified in Amazon SES.
4. Benefits of This Architecture
Using SNS, SQS, and SES together provides several advantages:
- Loose coupling: Application components communicate through events.
- Scalability: Multiple consumers can process messages independently.
- Reliability: SQS retains messages until they are processed or expire.
- Fault tolerance: Dead Letter Queues help handle failed messages.
- Performance: The main application does not wait for email delivery.
- Flexibility: New subscribers can be added without modifying the publisher.
5. Real-World Use Cases
This architecture can be implemented in several types of applications:
- E-commerce: Order confirmations, payment receipts, and shipping updates.
- Banking: Transaction alerts and payment notifications.
- Healthcare: Appointment confirmations and reminders.
- Monitoring: Application failure and infrastructure alerts.
6. Best Practices
For production applications, consider the following:
- Configure Dead Letter Queues for failed messages.
- Implement idempotency to prevent duplicate notifications.
- Use IAM roles instead of hardcoded AWS credentials.
- Monitor queue metrics using Amazon CloudWatch.
- Configure appropriate SQS visibility timeouts and retry policies.
- Monitor SES delivery, bounce, and complaint metrics.
Conclusion
Amazon SNS, SQS, and SES provide a simple yet powerful foundation for building event-driven applications.
SNS distributes events, SQS handles asynchronous message processing, and SES delivers email notifications.
By combining these services, we can build scalable, loosely coupled, and reliable notification systems without making the main application responsible for every notification task.
This architecture is a practical example of how AWS managed services can simplify application development and improve system reliability.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article