Polski

Tutorial · AWS SQS · Event-Driven Architecture

Amazon SQS in practice – standard and FIFO queues, long polling, DLQ, idempotency, SNS fan-out and Lambda (Node.js, C#, Python)

We move the pierogi shop's order handling to an Amazon SQS queue – a producer and consumer with AWS SDK v3, long polling, visibility timeout and heartbeats, a dead-letter queue (DLQ), idempotent processing with DynamoDB, batch sends, SNS fan-out and Lambda with partial batch failures. Variants in C# (AWSSDK.SQS) and Python (boto3).

By · · 26 min read

On Friday at 6 p.m. the pierogi shop gets a hundred orders in fifteen minutes. If, after accepting an order, the API synchronously prints a kitchen ticket, issues an invoice and adds loyalty points, then a printer failure stops sales. A queue separates these worlds: the API stores the order, drops a message and answers the customer in milliseconds, while the rest happens in the background, at its own pace and with retries. In this tutorial you build it on Amazon SQS – including the traps that only show up in production.

Prerequisites: an AWS account and AWS CLI v2 (plus jq for the infrastructure script), Node.js 22+, the basics of AWS SDK v3 from the S3 tutorial (clients, credentials). For the variants: .NET 10 SDK or Python 3.10+.

1 MiB
max message size – since August 2025 (previously 256 KiB)
20 s
max long polling – `WaitTimeSeconds`
12 h
max visibility timeout – 30 s by default
14 days
max retention – 4 days by default
Diagram: An order through SNS to many queues – each recipient at its own pace

Standard or FIFO?

StandardFIFO (.fifo)
Deliveryat least once – duplicates possibleexactly once within a 5-minute deduplication window
Orderingbest effort, no guaranteestrict within a MessageGroupId
Throughputpractically unlimited300 calls/s per action without batching (3,000 messages/s with batching); high throughput mode – much more, depending on the region
Price (per 1M requests)about USD 0.40about USD 0.50
Whenkitchen tickets, e-mails, image processingstatus changes of one order, balance operations

Default to a standard queue with idempotent consumers – you need that anyway, because even FIFO will not save you from a duplicate when the consumer processes a message but fails to delete it. Use FIFO where ordering matters to the business, and choose MessageGroupId so that there are many groups (e.g. the order id rather than one constant value – otherwise the whole queue is processed by a single thread).

Step 1. The project and infrastructure

npm install @aws-sdk/client-sqs @aws-sdk/client-sns @aws-sdk/client-dynamodb zod
npm install -D typescript tsx vitest @types/node @types/aws-lambda

Project configuration

package.json
{
  "name": "pierogi-sqs",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=22.12" },
  "scripts": {
    "worker": "tsx --env-file-if-exists=.env src/kitchen-worker.ts",
    "publish:demo": "tsx --env-file-if-exists=.env src/publish-demo.ts",
    "build": "tsc -p tsconfig.build.json",
    "typecheck": "tsc --noEmit",
    "test": "vitest run"
  },
  "dependencies": {
    "@aws-sdk/client-dynamodb": "^3.1178.0",
    "@aws-sdk/client-sns": "^3.1178.0",
    "@aws-sdk/client-sqs": "^3.1178.0",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/aws-lambda": "^8.10.164",
    "@types/node": "^24.19.4",
    "tsx": "^4.23.15",
    "typescript": "^7.0.2",
    "vitest": "^5.1.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "nodenext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["src", "test"]
}
tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": { "noEmit": false, "rootDir": "src", "outDir": "dist" },
  "include": ["src"]
}
.env.example
AWS_REGION=eu-central-1
ORDERS_QUEUE_URL=https://sqs.eu-central-1.amazonaws.com/123456789012/orders-kitchen
ORDER_EVENTS_TOPIC_ARN=arn:aws:sns:eu-central-1:123456789012:order-placed
IDEMPOTENCY_TABLE=processed-messages
# Local development with LocalStack: AWS_ENDPOINT_URL=http://localhost:4566
src/config.ts
import { z } from 'zod';

const EnvSchema = z.object({
  AWS_REGION: z.string().default('eu-central-1'),
  ORDERS_QUEUE_URL: z.url(),
  ORDER_EVENTS_TOPIC_ARN: z.string().startsWith('arn:aws:sns:'),
  IDEMPOTENCY_TABLE: z.string().default('processed-messages'),
});

export type Config = z.infer<typeof EnvSchema>;
export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => EnvSchema.parse(env);

The infrastructure is created by one AWS CLI script (in a real project move it to Terraform, CDK or CloudFormation):

Queues, DLQ, SNS, idempotency table and permissions

infra/create-queues.sh
#!/usr/bin/env bash
# Creates the queues, the SNS fan-out and the idempotency table for the pierogi shop.
set -euo pipefail
export AWS_REGION=${AWS_REGION:-eu-central-1}

# 1. Dead-letter queue first. Keep messages there longer than in the source queue:
#    a standard queue keeps the original enqueue timestamp after redrive.
DLQ_URL=$(aws sqs create-queue --queue-name orders-kitchen-dlq \
  --attributes MessageRetentionPeriod=1209600 --query QueueUrl --output text)
DLQ_ARN=$(aws sqs get-queue-attributes --queue-url "$DLQ_URL" \
  --attribute-names QueueArn --query Attributes.QueueArn --output text)

# 2. Main queue: long polling by default, 60 s visibility, DLQ after 5 failed receives.
ATTRS=$(mktemp)
cat > "$ATTRS" <<JSON
{
  "VisibilityTimeout": "60",
  "ReceiveMessageWaitTimeSeconds": "20",
  "MessageRetentionPeriod": "345600",
  "SqsManagedSseEnabled": "true",
  "RedrivePolicy": "{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":\"5\"}"
}
JSON
QUEUE_URL=$(aws sqs create-queue --queue-name orders-kitchen --attributes "file://$ATTRS" --query QueueUrl --output text)
QUEUE_ARN=$(aws sqs get-queue-attributes --queue-url "$QUEUE_URL" \
  --attribute-names QueueArn --query Attributes.QueueArn --output text)

# 3. FIFO queue for per-order status changes (ordered within MessageGroupId = orderId).
aws sqs create-queue --queue-name order-status.fifo \
  --attributes FifoQueue=true,ContentBasedDeduplication=false >/dev/null

# 4. SNS topic -> queue (fan-out). Raw delivery = the queue gets our JSON, not an SNS envelope.
TOPIC_ARN=$(aws sns create-topic --name order-placed --query TopicArn --output text)
POLICY=$(sed -e "s|QUEUE_ARN|$QUEUE_ARN|" -e "s|TOPIC_ARN|$TOPIC_ARN|" infra/queue-policy-sns.json | jq -c .)
aws sqs set-queue-attributes --queue-url "$QUEUE_URL" --attributes "$(jq -nc --arg p "$POLICY" '{Policy: $p}')"
aws sns subscribe --topic-arn "$TOPIC_ARN" --protocol sqs --notification-endpoint "$QUEUE_ARN" \
  --attributes "$(jq -nc --arg f "$(jq -c . infra/filter-policy.json)" '{RawMessageDelivery: "true", FilterPolicy: $f}')"

# 5. Idempotency table with TTL.
aws dynamodb create-table --table-name processed-messages \
  --attribute-definitions AttributeName=pk,AttributeType=S --key-schema AttributeName=pk,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST >/dev/null
aws dynamodb wait table-exists --table-name processed-messages
aws dynamodb update-time-to-live --table-name processed-messages \
  --time-to-live-specification Enabled=true,AttributeName=expiresAt >/dev/null

echo "ORDERS_QUEUE_URL=$QUEUE_URL"
echo "ORDER_EVENTS_TOPIC_ARN=$TOPIC_ARN"
infra/queue-policy-sns.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowOrderPlacedTopic",
      "Effect": "Allow",
      "Principal": { "Service": "sns.amazonaws.com" },
      "Action": "sqs:SendMessage",
      "Resource": "QUEUE_ARN",
      "Condition": { "ArnEquals": { "aws:SourceArn": "TOPIC_ARN" } }
    }
  ]
}
infra/filter-policy.json
{
  "type": ["order.placed"],
  "channel": ["web", "phone", "pyszne"]
}
infra/iam-worker-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ConsumeKitchenQueue",
      "Effect": "Allow",
      "Action": ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:ChangeMessageVisibility", "sqs:GetQueueAttributes"],
      "Resource": "arn:aws:sqs:eu-central-1:123456789012:orders-kitchen"
    },
    {
      "Sid": "Idempotency",
      "Effect": "Allow",
      "Action": "dynamodb:PutItem",
      "Resource": "arn:aws:dynamodb:eu-central-1:123456789012:table/processed-messages"
    }
  ]
}
  • DLQ first, with longer retention than the source queue – in a standard queue a message moved to the DLQ keeps its original enqueue time, so with the same retention it could expire before anyone looks at it.
  • maxReceiveCount: 5 – after five receives without a delete the message moves to the DLQ. Too low (1–2) sends messages that failed on a transient outage to the DLQ; too high keeps "poison" messages clogging the queue.
  • ReceiveMessageWaitTimeSeconds: 20 enables long polling for all consumers, including those that forget to set WaitTimeSeconds.
  • SqsManagedSseEnabled encrypts messages with an SQS-managed key. With your own KMS key, producers and consumers also need kms:GenerateDataKey / kms:Decrypt.
  • The queue policy allows only a specific SNS topic to send to it (the aws:SourceArn condition), and RawMessageDelivery means the queue receives our JSON, not an SNS envelope.

Step 2. The producer: message format, FIFO and batches

Producer (Node.js, C#, Python)

src/messages.ts
import { z } from 'zod';

// A versioned envelope: consumers can reject or migrate unknown versions explicitly.
export const OrderPlacedSchema = z.object({
  type: z.literal('order.placed'),
  version: z.literal(1),
  id: z.uuid(), // event id = idempotency key
  occurredAt: z.iso.datetime(),
  data: z.object({
    orderId: z.string(),
    channel: z.enum(['web', 'phone', 'pyszne']),
    items: z.array(z.object({ dish: z.string(), quantity: z.number().int().positive() })).min(1),
  }),
});

export type OrderPlaced = z.infer<typeof OrderPlacedSchema>;
src/producer.ts
import { randomUUID } from 'node:crypto';
import { SendMessageBatchCommand, SendMessageCommand, type SQSClient } from '@aws-sdk/client-sqs';
import type { OrderPlaced } from './messages.js';

export function orderPlaced(data: OrderPlaced['data']): OrderPlaced {
  return { type: 'order.placed', version: 1, id: randomUUID(), occurredAt: new Date().toISOString(), data };
}

export async function sendOrderPlaced(sqs: SQSClient, queueUrl: string, event: OrderPlaced): Promise<string | undefined> {
  const isFifo = queueUrl.endsWith('.fifo');
  const { MessageId } = await sqs.send(
    new SendMessageCommand({
      QueueUrl: queueUrl,
      MessageBody: JSON.stringify(event),
      // Attributes are readable without parsing the body (routing, filtering, metrics).
      MessageAttributes: {
        type: { DataType: 'String', StringValue: event.type },
        channel: { DataType: 'String', StringValue: event.data.channel },
      },
      // FIFO only: order is kept per group, duplicates within 5 minutes are dropped.
      ...(isFifo ? { MessageGroupId: event.data.orderId, MessageDeduplicationId: event.id } : {}),
    }),
  );
  return MessageId;
}

// Up to 10 messages per call = up to 10x fewer requests (and a smaller bill).
export async function sendBatch(sqs: SQSClient, queueUrl: string, events: OrderPlaced[], maxAttempts = 3): Promise<void> {
  for (let start = 0; start < events.length; start += 10) {
    let pending = events.slice(start, start + 10);
    for (let attempt = 1; pending.length > 0; attempt++) {
      const result = await sqs.send(
        new SendMessageBatchCommand({
          QueueUrl: queueUrl,
          Entries: pending.map((e) => ({ Id: e.id, MessageBody: JSON.stringify(e) })),
        }),
      );
      // A batch call can succeed (HTTP 200) while some entries fail – always check `Failed`.
      const failed = new Set((result.Failed ?? []).map((f) => f.Id));
      pending = pending.filter((e) => failed.has(e.id));
      if (pending.length > 0 && attempt >= maxAttempts) {
        throw new Error(`${pending.length} messages not sent: ${JSON.stringify(result.Failed)}`);
      }
      if (pending.length > 0) await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));
    }
  }
}
dotnet/SqsDemo/OrderProducer.cs
using System.Text.Json;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SqsDemo;

// Same JSON envelope as the Node.js producer: { type, version, id, occurredAt, data }.
public sealed record OrderItem(string Dish, int Quantity);
public sealed record OrderPlacedData(string OrderId, string Channel, IReadOnlyList<OrderItem> Items);

public sealed record OrderPlaced(string Type, int Version, Guid Id, DateTimeOffset OccurredAt, OrderPlacedData Data)
{
    public static OrderPlaced Create(string orderId, string channel, IReadOnlyList<OrderItem> items) =>
        new("order.placed", 1, Guid.NewGuid(), DateTimeOffset.UtcNow, new OrderPlacedData(orderId, channel, items));
}

public sealed class OrderProducer(IAmazonSQS sqs, string queueUrl)
{
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);

    public async Task<string> SendAsync(OrderPlaced evt, CancellationToken ct = default)
    {
        var request = new SendMessageRequest
        {
            QueueUrl = queueUrl,
            MessageBody = JsonSerializer.Serialize(evt, Json),
            MessageAttributes = new Dictionary<string, MessageAttributeValue>
            {
                ["type"] = new() { DataType = "String", StringValue = evt.Type },
                ["channel"] = new() { DataType = "String", StringValue = evt.Data.Channel },
            },
        };
        if (queueUrl.EndsWith(".fifo", StringComparison.Ordinal))
        {
            request.MessageGroupId = evt.Data.OrderId; // ordering per order
            request.MessageDeduplicationId = evt.Id.ToString(); // 5-minute deduplication window
        }
        var response = await sqs.SendMessageAsync(request, ct);
        return response.MessageId;
    }

    public async Task SendBatchAsync(IReadOnlyList<OrderPlaced> events, CancellationToken ct = default)
    {
        foreach (var chunk in events.Chunk(10)) // max 10 entries per batch
        {
            var response = await sqs.SendMessageBatchAsync(new SendMessageBatchRequest
            {
                QueueUrl = queueUrl,
                Entries = chunk.Select(e => new SendMessageBatchRequestEntry(e.Id.ToString(), JsonSerializer.Serialize(e, Json))).ToList(),
            }, ct);
            // HTTP 200 does not mean every entry made it.
            if (response.Failed is { Count: > 0 } failed)
                throw new InvalidOperationException($"{failed.Count} messages failed: {string.Join(", ", failed.Select(f => f.Code))}");
        }
    }
}
python/producer.py
import json
import os
import uuid
from datetime import datetime, timezone

import boto3

sqs = boto3.client("sqs", region_name=os.environ.get("AWS_REGION", "eu-central-1"))
QUEUE_URL = os.environ["ORDERS_QUEUE_URL"]


def order_placed(order_id: str, channel: str, items: list[dict]) -> dict:
    return {
        "type": "order.placed",
        "version": 1,
        "id": str(uuid.uuid4()),
        "occurredAt": datetime.now(timezone.utc).isoformat(),
        "data": {"orderId": order_id, "channel": channel, "items": items},
    }


def send_order_placed(event: dict) -> str:
    params = {
        "QueueUrl": QUEUE_URL,
        "MessageBody": json.dumps(event),
        "MessageAttributes": {
            "type": {"DataType": "String", "StringValue": event["type"]},
            "channel": {"DataType": "String", "StringValue": event["data"]["channel"]},
        },
    }
    if QUEUE_URL.endswith(".fifo"):
        params["MessageGroupId"] = event["data"]["orderId"]
        params["MessageDeduplicationId"] = event["id"]
    return sqs.send_message(**params)["MessageId"]


def send_batch(events: list[dict]) -> None:
    for start in range(0, len(events), 10):  # max 10 entries per call
        chunk = events[start : start + 10]
        result = sqs.send_message_batch(
            QueueUrl=QUEUE_URL,
            Entries=[{"Id": e["id"], "MessageBody": json.dumps(e)} for e in chunk],
        )
        if result.get("Failed"):  # HTTP 200 does not mean every entry made it
            raise RuntimeError(f"failed entries: {result['Failed']}")


if __name__ == "__main__":
    print(send_order_placed(order_placed("o-1001", "web", [{"dish": "ruskie", "quantity": 20}])))

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 3. The consumer: long polling, visibility timeout, heartbeat
  • Step 4. Idempotency: a duplicate must not print two tickets
  • Step 5. Fan-out through SNS
  • Step 6. Lambda as a consumer
  • Step 7. Tests
  • C# and Python variants
  • Operations: DLQ, alarms and redrive
  • Costs
  • Common mistakes
  • Check yourself
  • What's next

Create a free account · Sign in