Skip to main content

SQS Handlers

Learn how to create and work with SQS (queue) handlers in Serverless Monolith.

Basic SQS Handler

An SQS handler processes messages from a queue:

import { SQSHandler, SQSEvent } from 'aws-lambda';

export const handler: SQSHandler = async (event: SQSEvent) => {
for (const record of event.Records) {
const message = JSON.parse(record.body);
console.log('Processing message:', message);

// Process the message...
await processMessage(message);
}
};

Defining SQS Functions

Define SQS functions in your functions.yml:

processUserQueue:
handler: handlers/process-user/index.handler
events:
- sqs:
arn:
Fn::GetAtt: [ProcessUserQueue, Arn]
batchSize: 10

sendNotification:
handler: handlers/notification/index.handler
events:
- sqs:
arn:
Fn::GetAtt: [NotificationQueue, Arn]
batchSize: 1

Message Format

SQS messages have the following structure:

interface SQSRecord {
messageId: string;
receiptHandle: string;
body: string; // Your message content (JSON string)
attributes: {
ApproximateReceiveCount: string;
SentTimestamp: string;
SenderId: string;
ApproximateFirstReceiveTimestamp: string;
};
messageAttributes: Record<string, {
stringValue?: string;
dataType: string;
}>;
md5OfBody: string;
eventSource: string;
eventSourceARN: string;
awsRegion: string;
}

Sending Messages

Use the SQS API to send messages during development:

# Send a message via REST API
curl -X POST http://localhost:4005/api/sqs/send \
-H "Content-Type: application/json" \
-d '{
"queueName": "ProcessUserQueue",
"message": {
"userId": "123",
"action": "process"
}
}'

Programmatic Message Sending

import { MonolithServer } from '@serverless-monolith/core';

const server = MonolithServer.create('./monolith.config.ts');
await server.start();

// Send a message
await server.sendSqsMessage('ProcessUserQueue', {
userId: '123',
action: 'process',
});

Batch Processing

Handle multiple messages efficiently:

import { SQSHandler } from 'aws-lambda';

export const handler: SQSHandler = async (event) => {
const results = await Promise.allSettled(
event.Records.map(async (record) => {
const message = JSON.parse(record.body);
return processMessage(message);
})
);

// Log failed messages
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(
`Failed to process message ${event.Records[index].messageId}:`,
result.reason
);
}
});
};

Error Handling and Retries

The SQS emulator supports configurable retries:

const server = MonolithServer.create('./config.ts', {
sqs: {
enabled: true,
retryAttempts: 3,
visibilityTimeout: 30,
},
});

In your handler, throw errors for messages that should be retried:

export const handler: SQSHandler = async (event) => {
for (const record of event.Records) {
const message = JSON.parse(record.body);

try {
await processMessage(message);
} catch (error) {
console.error('Processing failed:', error);
throw error; // Message will be retried
}
}
};

Message Attributes

Access message attributes in your handler:

export const handler: SQSHandler = async (event) => {
for (const record of event.Records) {
// Message body
const body = JSON.parse(record.body);

// Message attributes
const priority = record.messageAttributes['priority']?.stringValue;
const correlationId = record.messageAttributes['correlationId']?.stringValue;

console.log(`Processing ${priority} priority message: ${correlationId}`);
}
};

SQS API Endpoints

The emulator provides these REST endpoints:

EndpointMethodDescription
/api/sqs/queuesGETList available queues
/api/sqs/sendPOSTSend a single message
/api/sqs/batchPOSTSend multiple messages
/api/sqs/logs/:executionId?GETGet SQS execution logs

Send Message Request

{
"queueName": "MyQueue",
"message": { "key": "value" },
"messageAttributes": {
"priority": {
"dataType": "String",
"stringValue": "high"
}
}
}

Batch Send Request

{
"queueName": "MyQueue",
"messages": [
{ "body": { "id": 1 } },
{ "body": { "id": 2 } },
{ "body": { "id": 3 } }
]
}

Testing SQS Handlers

# List queues
curl http://localhost:4005/api/sqs/queues

# Send message
curl -X POST http://localhost:4005/api/sqs/send \
-H "Content-Type: application/json" \
-d '{"queueName": "MyQueue", "message": {"test": true}}'

# View logs
curl http://localhost:4005/api/sqs/logs

Next Steps