Developer Quick-Start: A guide to implementing scalable and reliable asynchronous tasks, notifications, and reminders in NestJS using AWS SNS and SQS for decoupling and background processing. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.
Project Overview and Goals
In modern applications, performing tasks asynchronously is crucial for maintaining responsiveness and scalability. Operations like sending email notifications, processing uploaded files, generating reports, or sending scheduled reminders shouldn't block the main application thread or delay user responses.
This guide demonstrates how to build a system using NestJS that offloads such tasks to a background worker process facilitated by AWS SNS and SQS.
What We Will Build:
- A NestJS application capable of publishing messages (events or commands) to an AWS SNS topic.
- An AWS SQS queue subscribed to the SNS topic, acting as a durable buffer for messages.
- A NestJS-based consumer service that polls the SQS queue, processes messages reliably, and stores processed message information in a simple SQLite database for idempotency/tracking.
- API endpoints to trigger message publishing.
Problem Solved:
- Decoupling: Separates the task initiation (e.g., user signup, reminder creation) from the task execution (e.g., sending a welcome email, dispatching the reminder notification).
- Scalability: SQS queues can handle large volumes of messages, and consumer instances can be scaled independently based on queue depth.
- Reliability: SQS ensures messages are stored durably until successfully processed. SNS provides reliable fan-out capabilities if multiple consumers need the same message.
- Improved Performance: Prevents long-running tasks from impacting the performance of user-facing APIs.
Technologies Involved:
- NestJS: A progressive Node.js framework for building efficient, reliable, and scalable server-side applications using TypeScript. Chosen for its modular architecture, dependency injection, and excellent TypeScript support.
- AWS SNS (Simple Notification Service): A managed pub/sub messaging service. Used here to publish events/messages to a central topic.
- AWS SQS (Simple Queue Service): A managed message queuing service. Used to subscribe to the SNS topic and reliably buffer messages for processing by our consumer.
- AWS SDK for JavaScript v3: Used within the NestJS application to interact with SNS and SQS APIs.
- TypeORM & SQLite: An ORM (Object-Relational Mapper) and a simple file-based database used for persisting processed message IDs to ensure idempotency.
sqs-consumer: A Node.js library simplifying the process of polling and processing messages from an SQS queue.
System Architecture:
graph LR
A[Client / API Request] --> B(NestJS API / Publisher);
B -- Publish Message --> C{AWS SNS Topic};
C -- Fan-out --> D[AWS SQS Queue];
E(NestJS Consumer Service) -- Polls Queue --> D;
E -- Processes Message --> F[(SQLite Database)];
E -- Deletes Message --> D;
style B fill:#f9f,stroke:#333,stroke-width:2px
style E fill:#f9f,stroke:#333,stroke-width:2px
style C fill:#FF9900,stroke:#333,stroke-width:2px
style D fill:#FF9900,stroke:#333,stroke-width:2px
style F fill:#ccf,stroke:#333,stroke-width:2px
- Flow: A request triggers the NestJS Publisher, which sends a message to SNS. SNS fans it out to the subscribed SQS Queue. The NestJS Consumer polls the queue, retrieves a message, processes it (optionally interacting with a database), and finally deletes the message from the queue upon successful processing.
Prerequisites:
- Node.js (LTS version recommended) and npm/yarn installed.
- An AWS account with IAM user credentials (Access Key ID, Secret Access Key) configured with permissions for SNS (Publish) and SQS (ReceiveMessage, DeleteMessage, GetQueueAttributes).
- AWS CLI installed and configured (optional, but helpful for verification).
- Basic understanding of TypeScript and NestJS concepts (Modules, Services, Controllers).
- Docker (optional, for containerized development/deployment).
1. Setting up the Project
Let's bootstrap our NestJS project and install the necessary dependencies.
Step 1: Create a New NestJS Project
Open your terminal and run the NestJS CLI command:
npx @nestjs/cli new nestjs-sns-sqs-reminders
Choose your preferred package manager (npm or yarn). When prompted, navigate into the newly created directory:
cd nestjs-sns-sqs-reminders
Step 2: Install Dependencies
We need several packages for AWS integration, database interaction, configuration, and SQS polling:
npm install @aws-sdk/client-sns @aws-sdk/client-sqs
npm install sqs-consumer
npm install @nestjs/typeorm typeorm sqlite3
npm install @nestjs/config uuid dotenv
npm install --save-dev @types/uuid
Step 3: Project Structure
NestJS promotes a modular structure. We'll create dedicated modules for SNS publishing and SQS consuming
logic. Your src directory might eventually look something like this:
src/
βββ app.controller.ts
βββ app.module.ts
βββ app.service.ts
βββ main.ts
βββ config/ # Configuration setup (optional, but good practice)
β βββ configuration.ts
βββ database/ # Database related files
β βββ entities/
β β βββ processed-message.entity.ts
β βββ daos/
β βββ processed-message.dao.ts
βββ sns/ # SNS Publisher module
β βββ sns.module.ts
β βββ sns.publisher.service.ts
β βββ sns.controller.ts # Example controller to trigger publishing
βββ sqs/ # SQS Consumer module
βββ sqs.module.ts
βββ sqs.consumer.service.ts
βββ utils/
βββ constants.ts # Shared constants like MessageSourceType
We'll create these files as we go.
2. AWS Setup: Creating SNS Topic and SQS Queue
Before writing code, we need the necessary AWS resources.
Step 1: Create an SQS Queue
- Log in to the AWS Management Console.
- Navigate to the Simple Queue Service (SQS) console.
- Click Create queue.
- Type: Choose Standard. Standard queues offer higher throughput and at-least-once delivery, suitable for many reminder/task scenarios. FIFO queues guarantee order and exactly-once processing but have lower throughput limits.
- Name: Enter a descriptive name, e.g., nestjs-reminders-queue.
- Configuration: Review default settings like Visibility timeout (e.g., 30 seconds β how long a message is hidden after being received before it becomes visible again if not deleted) and Message retention period (e.g., 4 days). Adjust if needed.
- Access policy: We will configure this in the next step via the SNS subscription, so leave the basic setting for now.
- Click Create queue.
- Important: Once created, note down the Queue URL and the ARN from the queue details page. You'll need these for your .env file and the SNS subscription.
Step 2: Create an SNS Topic
- Navigate to the Simple Notification Service (SNS) console.
- Click Topics in the left navigation pane.
- Click Create topic.
- Type: Choose Standard. Matches the SQS queue type.
- Name: Enter a descriptive name, e.g., nestjs-tasks-topic.
- Leave other settings as default for now.
- Click Create topic.
- Important: Note down the Topic ARN.
Step 3: Subscribe SQS Queue to SNS Topic
- Go to the details page of the SNS Topic you just created (nestjs-tasks-topic).
- Scroll down to the Subscriptions tab and click Create subscription.
- Topic ARN: Should be pre-filled.
- Protocol: Select Amazon SQS.
- Endpoint: Paste the ARN of the SQS queue (nestjs-reminders-queue) you created earlier.
- Enable raw message delivery: It's often simpler to enable this. If enabled, the exact message you publish to SNS is delivered to SQS without SNS metadata wrapping. If disabled (default), the SQS message body will be a JSON structure containing the SNS message details. We'll assume raw delivery is enabled for simplicity in the primary consumer code path shown in this guide.
- Click Create subscription.
Step 4: Grant SNS Permission to Send to SQS (Crucial!)
SQS needs to allow the SNS topic to send messages to it.
- Go back to the SQS Console and select your queue (nestjs-reminders-queue).
- Go to the Access policy tab and click Edit.
- Use the Policy generator or manually add a statement to the existing policy's Statement array. The goal is to add a statement like this (replace placeholders):
{
""Sid"": ""AllowSNSPublishToSQS"",
""Effect"": ""Allow"",
""Principal"": {
""Service"": ""sns.amazonaws.com""
},
""Action"": ""SQS:SendMessage"",
""Resource"": ""YOUR_SQS_QUEUE_ARN"",
""Condition"": {
""ArnEquals"": {
""aws:SourceArn"": ""YOUR_SNS_TOPIC_ARN""
}
}
}
- Ensure the final policy JSON is valid. Replace YOUR\_SQS\_QUEUE\_ARN with your actual Queue ARN and YOUR\_SNS\_TOPIC\_ARN with your actual Topic ARN.
- Click Save.
- Why this policy? It explicitly grants the SNS service (sns.amazonaws.com) permission to perform the SQS:SendMessage action on your specific SQS queue resource, but only if the message originates from your specific SNS topic. This follows the principle of least privilege.
3. Environment Configuration
Securely manage your AWS credentials and resource identifiers using environment variables.
Step 1: Create .env File
In the root directory of your project, create a file named .env:
.env
# .env
# AWS Credentials - Use IAM user keys, NOT root keys
AWS_ACCESS_KEY_ID=YOUR_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=YOUR_AWS_SECRET_ACCESS_KEY
AWS_REGION=us-east-1 # Or your preferred AWS region
# AWS Resource Identifiers
SNS_TOPIC_ARN=YOUR_SNS_TOPIC_ARN # ARN copied from SNS console
SQS_QUEUE_URL=YOUR_SQS_QUEUE_URL # URL copied from SQS console
- Replace placeholders with the actual values obtained from your IAM user configuration and the AWS console (SNS Topic ARN, SQS Queue URL).
- Security: Add .env to your .gitignore file immediately to prevent committing credentials.
Step 2: Load Environment Variables using ConfigModule
NestJS provides a ConfigModule to load and manage environment variables. Modify your main
application module (src/app.module.ts):
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- isGlobal: true makes the ConfigService injectable in any module without needing to import ConfigModule everywhere.
- envFilePath: '.env' explicitly tells the module where to find your variables.
4. Database Setup (SQLite & TypeORM)
We'll use a simple SQLite database via TypeORM to keep track of processed message IDs. This helps prevent processing the same message multiple times if errors occur or if SQS delivers a message more than once (which can happen with Standard queues).
Step 1: Define the Entity
Create an entity representing a processed message record.
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index } from 'typeorm';
@Entity({ name: 'processed_messages' })
export class ProcessedMessage {
@PrimaryGeneratedColumn()
id: number;
@Index({ unique: true })
@Column({ type: 'varchar', length: 255 })
messageId: string;
@Column({ type: 'text' })
messageBody: string;
@Column({ type: 'varchar', length: 50, nullable: true })
sourceType?: string;
@CreateDateColumn()
processedAt: Date;
}
- We add a unique index on messageId to leverage the database for enforcing idempotency.
Step 2: Create the Data Access Object (DAO)
Create a service to handle database interactions for this entity.
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, QueryFailedError } from 'typeorm';
import { ProcessedMessage } from '../entities/processed-message.entity';
@Injectable()
export class ProcessedMessageDao {
private readonly logger = new Logger(ProcessedMessageDao.name);
constructor(
@InjectRepository(ProcessedMessage)
private readonly repository: Repository<ProcessedMessage>,
) {}
async recordMessageProcessed(
messageId: string,
messageBody: string,
sourceType?: string,
): Promise<ProcessedMessage | null> {
try {
const newMessage = this.repository.create({
messageId,
messageBody,
sourceType,
});
return await this.repository.save(newMessage);
} catch (error) {
if (error instanceof QueryFailedError && error.driverError?.code === 'SQLITE_CONSTRAINT') {
this.logger.warn(`Message ID ${messageId} has already been processed.`);
return null;
}
this.logger.error(`Failed to save processed message ${messageId}: ${error.message}`, error.stack);
throw error;
}
}
async hasBeenProcessed(messageId: string): Promise<boolean> {
const count = await this.repository.count({ where: { messageId } });
return count > 0;
}
}
- The recordMessageProcessed method attempts to save the record. If it fails due to the unique constraint on messageId, it means the message was already processed, and it returns null. Other errors are re-thrown.
- hasBeenProcessed provides a direct check.
Step 3: Configure TypeORM Module
Update src/app.module.ts to configure TypeORM and make the ProcessedMessage entity
and DAO available.
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ProcessedMessage } from './database/entities/processed-message.entity';
import { ProcessedMessageDao } from './database/daos/processed-message.dao';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'sqlite',
database: 'processed_messages.db',
entities: [ProcessedMessage],
synchronize: true,
logging: configService.get<string>('NODE_ENV') !== 'production',
}),
inject: [ConfigService],
}),
TypeOrmModule.forFeature([ProcessedMessage]),
],
controllers: [AppController],
providers: [AppService, ProcessedMessageDao],
exports: [ProcessedMessageDao],
})
export class AppModule {}
- We use forRootAsync to potentially inject ConfigService if needed for database configuration (though not strictly necessary for this simple SQLite setup).
- synchronize: true is convenient for development as it automatically creates/updates the database schema based on your entities. IMPORTANT: Set this to false in production and use TypeORM migrations to manage schema changes safely.
- TypeOrmModule.forFeature([ProcessedMessage]) makes the Repository<ProcessedMessage> injectable.
- We provide and export ProcessedMessageDao so it can be used by the SQS consumer later.
Note on Production Databases: While SQLite is excellent for tutorials and local development, the idempotency pattern demonstrated here is production-ready. However, SQLite itself has limitations regarding concurrency and scalability under heavy load. For production environments handling significant traffic, consider using more robust database systems like PostgreSQL, MySQL, or managed NoSQL services like AWS DynamoDB.
5. SNS Publisher Implementation
This module will handle publishing messages to our SNS topic.
Step 1: Create SNS Publisher Service
This service encapsulates the logic for interacting with the AWS SNS client.
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SNSClient, PublishCommand, PublishCommandInput } from '@aws-sdk/client-sns';
import { v4 as uuid } from 'uuid';
@Injectable()
export class SnsPublisherService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(SnsPublisherService.name);
private snsClient: SNSClient;
private topicArn: string;
constructor(private configService: ConfigService) {}
onModuleInit() {
const region = this.configService.get<string>('AWS_REGION');
this.topicArn = this.configService.get<string>('SNS_TOPIC_ARN');
if (!region || !this.topicArn) {
throw new Error('AWS Region or SNS Topic ARN not configured in environment variables.');
}
this.snsClient = new SNSClient({
region: region,
credentials: {
accessKeyId: this.configService.get<string>('AWS_ACCESS_KEY_ID'),
secretAccessKey: this.configService.get<string>('AWS_SECRET_ACCESS_KEY'),
},
});
this.logger.log('SNS Client Initialized');
}
async publish<T>(message: T, messageGroupId?: string): Promise<string | undefined> {
const messageBody = typeof message === 'string' ? message : JSON.stringify(message);
const params: PublishCommandInput = {
TopicArn: this.topicArn,
Message: messageBody,
};
try {
const command = new PublishCommand(params);
const response = await this.snsClient.send(command);
this.logger.log(`Message published to SNS Topic ${this.topicArn}. Message ID: ${response.MessageId}`);
return response.MessageId;
} catch (error) {
this.logger.error(`Error publishing message to SNS Topic ${this.topicArn}: ${error.message}`, error.stack);
throw error;
}
}
onModuleDestroy() {
this.snsClient?.destroy();
this.logger.log('SNS Client Destroyed');
}
}
- The service initializes the SNSClient using credentials and region from ConfigService.
- The publish method takes a message (object or string), stringifies it if necessary, and sends it using PublishCommand.
- It includes commented-out logic for MessageGroupId and MessageDeduplicationId which are primarily for FIFO topics/queues but demonstrates their usage. Adjust or remove based on your topic type.
- Basic logging and error handling are included.
- OnModuleInit ensures the client is ready, OnModuleDestroy cleans up resources.
Step 2: Create Example Controller (Optional)
Create a simple controller to trigger the publisher via an HTTP request.
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { SnsPublisherService } from './sns.publisher.service';
interface PublishMessageDto {
message: any;
type: 'reminder' | 'notification' | 'task';
}
@Controller('messages')
export class SnsController {
constructor(private readonly snsPublisherService: SnsPublisherService) {}
@Post('publish')
@HttpCode(HttpStatus.ACCEPTED)
async publishMessage(@Body() body: PublishMessageDto) {
const messageId = await this.snsPublisherService.publish(body);
return {
status: 'Message submitted for publishing',
messageId: messageId,
};
}
}
- This provides a /messages/publish endpoint to test sending messages.
- It uses HttpStatus.ACCEPTED (202) as publishing is an asynchronous operation trigger.
Step 3: Create SNS Module
Define the module to encapsulate the SNS components.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { SnsPublisherService } from './sns.publisher.service';
import { SnsController } from './sns.controller';
@Module({
imports: [ConfigModule],
controllers: [SnsController],
providers: [SnsPublisherService],
exports: [SnsPublisherService],
})
export class SnsModule {}
Step 4: Import SNS Module into AppModule
Add SnsModule to the imports array in src/app.module.ts.
import { SnsModule } from './sns/sns.module';
import { SqsModule } from './sqs/sqs.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { ProcessedMessage } from './database/entities/processed-message.entity';
import { ProcessedMessageDao } from './database/daos/processed-message.dao';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env' }),
TypeOrmModule.forRootAsync({ }),
TypeOrmModule.forFeature([ProcessedMessage]),
SnsModule,
],
controllers: [AppController],
providers: [AppService, ProcessedMessageDao],
exports: [ProcessedMessageDao],
})
export class AppModule {}
6. SQS Consumer Implementation
This module will poll the SQS queue, process messages, and ensure idempotency using the database.
Step 1: Define Constants (Optional)
It can be helpful to define constants for message source types.
export enum MessageSourceType {
SQS = 'SQS',
SNS = 'SNS',
UNKNOWN = 'UNKNOWN',
}
Step 2: Create SQS Consumer Service
This service uses the sqs-consumer library to handle polling, processing, and deleting messages.
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SQSClient, Message, DeleteMessageCommand } from '@aws-sdk/client-sqs';
import { Consumer } from 'sqs-consumer';
import { ProcessedMessageDao } from '../database/daos/processed-message.dao';
import { MessageSourceType } from './utils/constants';
@Injectable()
export class SqsConsumerService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(SqsConsumerService.name);
private consumer: Consumer;
private sqsClient: SQSClient;
private queueUrl: string;
constructor(
private configService: ConfigService,
private processedMessageDao: ProcessedMessageDao,
) {}
onModuleInit() {
const region = this.configService.get<string>('AWS_REGION');
this.queueUrl = this.configService.get<string>('SQS_QUEUE_URL');
if (!region || !this.queueUrl) {
throw new Error('AWS Region or SQS Queue URL not configured.');
}
this.sqsClient = new SQSClient({
region: region,
credentials: {
accessKeyId: this.configService.get<string>('AWS_ACCESS_KEY_ID'),
secretAccessKey: this.configService.get<string>('AWS_SECRET_ACCESS_KEY'),
},
});
this.initializeConsumer();
this.consumer.start();
this.logger.log(`SQS Consumer started polling queue: ${this.queueUrl}`);
}
private initializeConsumer() {
this.consumer = Consumer.create({
queueUrl: this.queueUrl,
sqs: this.sqsClient,
handleMessage: async (message: Message) => {
await this.processMessage(message);
},
batchSize: 10,
visibilityTimeout: 60,
waitTimeSeconds: 10,
shouldDeleteMessages: false,
});
this.consumer.on('error', (err, message) => {
this.logger.error(`SQS Consumer error: ${err.message}`, { messageId: message?.MessageId });
});
this.consumer.on('processing_error', (err, message) => {
this.logger.error(`SQS Consumer processing error: ${err.message}`, { messageId: message?.MessageId });
});
this.consumer.on('timeout_error', (err, message) => {
this.logger.error(`SQS Consumer message visibility timeout error: ${err.message}`, { messageId: message?.MessageId });
});
this.consumer.on('stopped', () => {
this.logger.log('SQS Consumer stopped.');
});
}
private async processMessage(message: Message): Promise<void> {
this.logger.debug(`Received message: ${message.MessageId}`);
if (!message.MessageId || !message.Body || !message.ReceiptHandle) {
this.logger.error('Received malformed message, skipping.', message);
return;
}
const messageId = message.MessageId;
const messageBody = message.Body;
const receiptHandle = message.ReceiptHandle;
try {
const alreadyProcessed = await this.processedMessageDao.hasBeenProcessed(messageId);
if (alreadyProcessed) {
this.logger.warn(`Message ${messageId} already processed. Deleting from queue.`);
await this.deleteMessageFromQueue(receiptHandle);
return;
}
let payload: any;
let sourceType = MessageSourceType.UNKNOWN;
try {
payload = JSON.parse(messageBody);
if (payload.Type === 'Notification' && payload.TopicArn && payload.Message) {
sourceType = MessageSourceType.SNS;
try {
payload = JSON.parse(payload.Message);
} catch (innerParseError) {
this.logger.warn(`Could not JSON parse inner SNS message for ${messageId}. Processing inner content as raw string.`);
payload = payload.Message;
}
} else {
sourceType = MessageSourceType.SQS;
}
} catch (parseError) {
this.logger.warn(`Message ${messageId} body is not valid JSON. Processing as raw string.`);
payload = messageBody;
sourceType = MessageSourceType.SQS;
}
this.logger.log(`Processing message ${messageId} of type ${sourceType}`);
if (payload?.type === 'reminder') {
this.logger.log(`Handling reminder: ${payload.message}`);
} else if (payload?.type === 'notification') {
this.logger.log(`Handling notification: ${payload.message}`);
} else {
this.logger.log(`Handling generic task:`, payload);
}
await new Promise(resolve => setTimeout(resolve, 500));
const recorded = await this.processedMessageDao.recordMessageProcessed(messageId, messageBody, sourceType);
if (recorded === null) {
this.logger.warn(`Message ${messageId} was processed concurrently. Skipping delete.`);
return;
}
this.logger.log(`Successfully processed and recorded message ${messageId}.`);
await this.deleteMessageFromQueue(receiptHandle);
this.logger.debug(`Deleted message ${messageId} from queue.`);
} catch (error) {
this.logger.error(`Failed to process message ${messageId}: ${error.message}`, error.stack);
}
}
private async deleteMessageFromQueue(receiptHandle: string): Promise<void> {
try {
const deleteCommand = new DeleteMessageCommand({
QueueUrl: this.queueUrl,
ReceiptHandle: receiptHandle,
});
await this.sqsClient.send(deleteCommand);
} catch (error) {
this.logger.error(`Failed to delete message with receipt handle ${receiptHandle.substring(0, 10)}... from queue ${this.queueUrl}: ${error.message}`, error.stack);
}
}
onModuleDestroy() {
this.consumer?.stop();
this.sqsClient?.destroy();
this.logger.log('SQS Consumer and Client Destroyed');
}
}
- The service initializes sqs-consumer with the SQS client and configuration.
- shouldDeleteMessages: false is crucial; we manually delete messages only after successful processing and recording.
- handleMessage calls processMessage.
- processMessage implements the core logic:
- Idempotency check using ProcessedMessageDao. If already processed, delete and return.
- Parse the message body, attempting to handle raw vs. non-raw SNS delivery.
- Placeholder for your actual business logic.
- Record the message ID in the database using ProcessedMessageDao. If it returns null (concurrent processing), return without deleting.
- Delete the message from SQS using deleteMessageFromQueue.
- Error handling is included for consumer events and within processMessage. Failed processing prevents deletion, allowing SQS retries (and eventually DLQ if configured).
- deleteMessageFromQueue encapsulates the DeleteMessageCommand.
- OnModuleDestroy stops the consumer gracefully.
Step 3: Create SQS Module
Define the module for SQS components.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ProcessedMessage } from '../database/entities/processed-message.entity';
import { ProcessedMessageDao } from '../database/daos/processed-message.dao';
import { SqsConsumerService } from './sqs.consumer.service';
@Module({
imports: [
ConfigModule,
TypeOrmModule.forFeature([ProcessedMessage]),
],
providers: [SqsConsumerService, ProcessedMessageDao],
exports: [SqsConsumerService],
})
export class SqsModule {}
- This module imports TypeOrmModule.forFeature to make the ProcessedMessage repository available for injection into ProcessedMessageDao.
- It provides both the SqsConsumerService and the ProcessedMessageDao.
Step 4: Import SQS Module into AppModule
Finally, add SqsModule to the imports array in src/app.module.ts. Ensure
ProcessedMessageDao is provided/exported correctly (it's provided in AppModule and
exported, and also provided in SqsModule - providing it in SqsModule is sufficient
if it's only used there, or keep it exported from AppModule if used elsewhere too. Let's adjust
AppModule slightly assuming DAO is primarily used by SQS).
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ProcessedMessage } from './database/entities/processed-message.entity';
import { SnsModule } from './sns/sns.module';
import { SqsModule } from './sqs/sqs.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'sqlite',
database: 'processed_messages.db',
entities: [ProcessedMessage],
synchronize: configService.get<string>('NODE_ENV') !== 'production',
logging: configService.get<string>('NODE_ENV') !== 'production',
}),
inject: [ConfigService],
}),
SnsModule,
SqsModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
- We added SqsModule to the imports.
- Removed ProcessedMessageDao from AppModule's providers/exports and TypeOrmModule.forFeature from its imports, as SqsModule now handles providing the DAO and importing the necessary feature module.
- Adjusted synchronize default to be safer.
7. Running and Testing
- Start the Application:
npm run start:dev
This will start the NestJS application, initialize the SNS client, configure TypeORM (and create the SQLite
file/table if synchronize: true), and start the SQS consumer polling.
- Trigger Message Publishing: Use a tool like
curl, Postman, or Insomnia to send a POST request to the example endpoint (if you createdSnsController):
curl -X POST http://localhost:3000/messages/publish \
-H "Content-Type: application/json" \
-d '{
"message": "Send welcome email to user@example.com",
"type": "notification",
"userId": "user-123"
}'
You should receive a 202 Accepted response with a message ID.
- Observe Logs:
- Check the NestJS application logs. You should see:
- Log message from SnsPublisherService indicating successful publishing to SNS.
- Log messages from SqsConsumerService indicating:
- Receipt of the message from SQS.
- Processing the message (your business logic logs).
- Recording the message ID in the database (ProcessedMessageDao).
- Deleting the message from SQS.
- Verify Idempotency:
- Send the exact same POST request again.
- Observe the logs. This time, the SqsConsumerService should log a warning like "Message X already processed. Deleting from queue." and it should not execute your business logic again. It should still delete the duplicate message from the queue.
- Check Database:
- Use a SQLite browser tool to inspect the processed\_messages.db file. You should see entries for each successfully processed unique message ID.
8. Further Considerations and Best Practices
- Dead Letter Queues (DLQ): Configure a DLQ on your SQS queue. Messages that fail processing repeatedly (exceeding the maxReceiveCount) will be sent to the DLQ for investigation, preventing them from blocking the main queue indefinitely.
- Error Handling & Retries: Implement more robust error handling within your processMessage logic. Decide which errors are transient (and should be retried by letting the message visibility timeout expire) and which are permanent (and should potentially lead to moving the message to the DLQ immediately or logging a critical error). The sqs-consumer library has options for handling processing errors.
- Monitoring & Alerting: Set up AWS CloudWatch Alarms based on SQS metrics (e.g., ApproximateNumberOfMessagesVisible, ApproximateAgeOfOldestMessage) and DLQ metrics (ApproximateNumberOfMessagesVisible on the DLQ). Monitor application logs for errors (especially message deletion failures).
- Configuration Management: For production, use a more robust configuration system than just .env (e.g., AWS Systems Manager Parameter Store, AWS Secrets Manager, or environment variables injected by your deployment platform).
- Structured Logging: Use JSON-based logging for easier parsing and analysis in log aggregation tools (like CloudWatch Logs Insights, Datadog, Splunk).
- FIFO Queues: If strict ordering or exactly-once processing (within the bounds of SQS FIFO guarantees) is required, use SNS FIFO topics and SQS FIFO queues. Remember to provide MessageGroupId and potentially MessageDeduplicationId when publishing. Idempotency checks are still recommended even with FIFO.
- Scalability: Monitor queue depth and CPU/Memory utilization of your consumer instances. Scale the number of consumer instances (e.g., in ECS, Kubernetes, or EC2 Auto Scaling Groups) based on these metrics. sqs-consumer's batchSize also affects concurrency within a single instance.
- Security: Follow the principle of least privilege for IAM permissions. Ensure your AWS credentials are handled securely (never hardcode them, use IAM roles for EC2/ECS/Lambda where possible).
- TypeORM Migrations: Disable synchronize: true in production and use TypeORM migrations to manage database schema changes safely and controllably.
- Testing: Write unit tests for your services (Publisher, Consumer, DAO) and integration tests that mock AWS services or use tools like localstack to simulate the AWS environment locally.
This guide provides a solid foundation for building reliable asynchronous processing systems with NestJS and AWS. Remember to adapt the patterns and implement robust error handling and monitoring for your specific production needs.
Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)
If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.
curl -X POST https://api.sendsmsnokyc.com/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms"],
"body": "Your verification code is 482910"
}'
- Instant onboarding: No KYC paperwork or sales queues β grab an API key and fund with crypto (BTC/USDT) or card.
- Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
- Transparent global pricing: Compare exact per-country termination rates on our live pricing page.
Ship Global SMS in One API Call
Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.
Explore SMSRoute Developers β