Amazon SQS

Has Demo

Simple Queue Service - Decouple and scale microservices

💵 Cost: SQS has a generous Free Tier of 1 million requests/month forever (not just 12 months). Beyond that, Standard queues cost $0.40/million requests. Empty queues cost nothing. See our Costs & Cleanup Guide for deletion steps.

What is SQS?

Amazon Simple Queue Service (SQS) is a fully managed message queue. It lets you send, store, and receive messages between software components without losing messages, even if parts of your system are temporarily unavailable.

When to Use SQS

Use SQS when you need to process work asynchronously. Instead of making users wait for slow operations (sending emails, processing images, generating reports), put tasks in a queue and process them in the background.

Why Use Message Queues?

Plain Text
Without Queue (Synchronous):
User Request → Process Image → Send Email → Update DB → Response
                    ↓
            User waits for ALL steps (slow!)

With Queue (Asynchronous):
User Request → Add to Queue → Response (fast!)
                    ↓
            Worker picks up → Process Image
                           → Send Email
                           → Update DB

SQS Concepts

ConceptDescription
QueueContainer for messages
MessageData you want to process (up to 256KB)
ProducerComponent that sends messages to the queue
ConsumerComponent that receives and processes messages
Visibility TimeoutTime a message is hidden after being read
Dead Letter QueueQueue for messages that fail processing repeatedly

Standard vs FIFO Queues

FeatureStandard QueueFIFO Queue
ThroughputNearly unlimited300 msg/sec (3,000 with batching)
OrderingBest-effort (may be out of order)Strictly preserved
DuplicatesPossible (at-least-once)Never (exactly-once)
Use CaseGeneral processing, high volumeOrder-sensitive operations

Create a Queue

Terminal
$aws sqs create-queue --queue-name my-app-tasks
{
    "QueueUrl": "https://sqs.ap-southeast-1.amazonaws.com/123456789/my-app-tasks"
}

Send a Message (Producer)

TypeScript
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs"

const sqs = new SQSClient({ region: process.env.AWS_REGION })

export async function queueTask(task: {
  type: string
  payload: Record<string, unknown>
}) {
  const command = new SendMessageCommand({
    QueueUrl: process.env.SQS_QUEUE_URL,
    MessageBody: JSON.stringify(task),
    MessageAttributes: {
      TaskType: {
        DataType: "String",
        StringValue: task.type
      }
    }
  })

  const response = await sqs.send(command)
  return response.MessageId
}

// Usage in API route
await queueTask({
  type: "SEND_EMAIL",
  payload: { to: "user@example.com", template: "welcome" }
})

Receive Messages (Consumer)

TypeScript
import {
  ReceiveMessageCommand,
  DeleteMessageCommand
} from "@aws-sdk/client-sqs"

export async function processQueue() {
  const receiveCommand = new ReceiveMessageCommand({
    QueueUrl: process.env.SQS_QUEUE_URL,
    MaxNumberOfMessages: 10,
    WaitTimeSeconds: 20,  // Long polling
    MessageAttributeNames: ["All"]
  })

  const response = await sqs.send(receiveCommand)

  for (const message of response.Messages ?? []) {
    try {
      const task = JSON.parse(message.Body!)

      // Process the task
      await handleTask(task)

      // Delete message after successful processing
      await sqs.send(new DeleteMessageCommand({
        QueueUrl: process.env.SQS_QUEUE_URL,
        ReceiptHandle: message.ReceiptHandle
      }))
    } catch (error) {
      console.error("Failed to process message:", error)
      // Message will become visible again after visibility timeout
    }
  }
}

Always Delete After Processing

If you do not delete a message after processing, it will reappear in the queue after the visibility timeout expires. This can cause duplicate processing.

SQS Pricing

ComponentCost
First 1M requests/monthFree
Standard Queue requests$0.40 per million
FIFO Queue requests$0.50 per million

Cost Optimization

Use batch operations (SendMessageBatch, ReceiveMessage with MaxNumberOfMessages) to reduce API calls. Long polling (WaitTimeSeconds) also reduces empty receives.

AWS Deployment Guide — Built with Next.js