{"id":"6b09417c5ce40d447918f299","slug":"aws-sqs","title":"Amazon SQS in practice – standard and FIFO queues, long polling, DLQ, idempotency, SNS fan-out and Lambda (Node.js, C#, Python)","summary":"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).","servedLang":"en","availableLangs":["pl","en"],"topics":["aws-sqs","event-driven-architecture"],"techs":["node","typescript","dotnet","python"],"tags":["aws","sqs","sns","fifo","dead-letter-queue","idempotency","long-polling","lambda","aws-sdk-v3","boto3"],"level":"intermediate","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":26,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:20.692Z","updatedAt":"2026-11-27T13:12:00.159Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"amber","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"Amazon SQS step by step – standard vs FIFO, @aws-sdk/client-sqs, ReceiveMessage with long polling, visibility timeout, DLQ and redrive, idempotency (DynamoDB), SendMessageBatch, SNS fan-out with filters, Lambda with ReportBatchItemFailures, costs; examples in Node.js, C# and Python.","wordCount":5195,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"callout","attrs":{"variant":"info","title":"In a nutshell"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"SQS delivers a message at least once","marks":[{"type":"bold"}]},{"type":"text","text":" (standard queue) – the same message can arrive twice, so the consumer has to be idempotent."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A message does not disappear when received.","marks":[{"type":"bold"}]},{"type":"text","text":" It becomes invisible for the "},{"type":"text","text":"visibility timeout","marks":[{"type":"italic"}]},{"type":"text","text":"; you delete it only after successful processing. A failure = the message comes back, and after N attempts it moves to a dead-letter queue (DLQ)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Long polling, batches and SNS fan-out","marks":[{"type":"bold"}]},{"type":"text","text":" are three levers for cost and architecture: fewer empty responses, fewer requests and one publish for many recipients."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"An "},{"type":"text","text":"orders-kitchen","marks":[{"type":"code"}]},{"type":"text","text":" queue with a DLQ and a FIFO queue for status changes, an "},{"type":"text","text":"order-placed","marks":[{"type":"code"}]},{"type":"text","text":" SNS topic with a subscription filter, a producer with batch sends (handling partial failures), a consumer with long polling, parallel processing, heartbeats and graceful shutdown, idempotency on DynamoDB, and a Lambda handler with "},{"type":"text","text":"batchItemFailures","marks":[{"type":"code"}]},{"type":"text","text":". Plus producer and consumer variants in C# and Python – all three languages exchange the same message format. Download the code (26 files) as a ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" an AWS account and AWS CLI v2 (plus "},{"type":"text","text":"jq","marks":[{"type":"code"}]},{"type":"text","text":" for the infrastructure script), Node.js 22+, the basics of "},{"type":"text","text":"AWS SDK v3 from the S3 tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/aws-s3"}}]},{"type":"text","text":" (clients, credentials). For the variants: .NET 10 SDK or Python 3.10+."}]},{"type":"stats","attrs":{"items":[{"value":"1 MiB","label":"max message size","hint":"since August 2025 (previously 256 KiB)"},{"value":"20 s","label":"max long polling","hint":"`WaitTimeSeconds`"},{"value":"12 h","label":"max visibility timeout","hint":"30 s by default"},{"value":"14 days","label":"max retention","hint":"4 days by default"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  API[Pierogi API] -->|Publish order.placed| T{{SNS: order-placed}}\n  T -->|filter: all| QK[[SQS: orders-kitchen]]\n  T -->|filter: all| QI[[SQS: invoices]]\n  T -->|filter: channel = web| QL[[SQS: loyalty]]\n  QK --> WK[Kitchen worker<br/>ECS / container]\n  QI --> LI[Invoice Lambda]\n  QL --> WL[Points worker]\n  QK -. after 5 failed attempts .-> DLQ[[orders-kitchen-dlq]]\n  WK --> DDB[(DynamoDB<br/>idempotency)]","caption":"An order through SNS to many queues – each recipient at its own pace"}},{"type":"heading","attrs":{"level":2,"id":"standard-or-fifo"},"content":[{"type":"text","text":"Standard or FIFO?"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph"}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Standard"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"FIFO ("},{"type":"text","text":".fifo","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Delivery"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"at least once – duplicates possible"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"exactly once within a 5-minute deduplication window"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Ordering"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"best effort, no guarantee"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"strict within a "},{"type":"text","text":"MessageGroupId","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Throughput"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"practically unlimited"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"300 calls/s per action without batching (3,000 messages/s with batching); high throughput mode – much more, depending on the region"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Price (per 1M requests)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"about USD 0.40"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"about USD 0.50"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"When"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kitchen tickets, e-mails, image processing"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"status changes of one order, balance operations"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"MessageGroupId","marks":[{"type":"code"}]},{"type":"text","text":" 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)."}]},{"type":"heading","attrs":{"level":2,"id":"step-1-the-project-and-infrastructure"},"content":[{"type":"text","text":"Step 1. The project and infrastructure"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm install @aws-sdk/client-sqs @aws-sdk/client-sns @aws-sdk/client-dynamodb zod\nnpm install -D typescript tsx vitest @types/node @types/aws-lambda"}]},{"type":"codeGroup","attrs":{"title":"Project configuration"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-sqs\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=22.12\" },\n  \"scripts\": {\n    \"worker\": \"tsx --env-file-if-exists=.env src/kitchen-worker.ts\",\n    \"publish:demo\": \"tsx --env-file-if-exists=.env src/publish-demo.ts\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"typecheck\": \"tsc --noEmit\",\n    \"test\": \"vitest run\"\n  },\n  \"dependencies\": {\n    \"@aws-sdk/client-dynamodb\": \"^3.1178.0\",\n    \"@aws-sdk/client-sns\": \"^3.1178.0\",\n    \"@aws-sdk/client-sqs\": \"^3.1178.0\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/aws-lambda\": \"^8.10.164\",\n    \"@types/node\": \"^24.19.4\",\n    \"tsx\": \"^4.23.15\",\n    \"typescript\": \"^7.0.2\",\n    \"vitest\": \"^5.1.2\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"ES2024\",\n    \"module\": \"nodenext\",\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"verbatimModuleSyntax\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true,\n    \"noEmit\": true,\n    \"types\": [\"node\"]\n  },\n  \"include\": [\"src\", \"test\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.build.json"},"content":[{"type":"text","text":"{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": { \"noEmit\": false, \"rootDir\": \"src\", \"outDir\": \"dist\" },\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":".env.example"},"content":[{"type":"text","text":"AWS_REGION=eu-central-1\nORDERS_QUEUE_URL=https://sqs.eu-central-1.amazonaws.com/123456789012/orders-kitchen\nORDER_EVENTS_TOPIC_ARN=arn:aws:sns:eu-central-1:123456789012:order-placed\nIDEMPOTENCY_TABLE=processed-messages\n# Local development with LocalStack: AWS_ENDPOINT_URL=http://localhost:4566"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/config.ts"},"content":[{"type":"text","text":"import { z } from 'zod';\n\nconst EnvSchema = z.object({\n  AWS_REGION: z.string().default('eu-central-1'),\n  ORDERS_QUEUE_URL: z.url(),\n  ORDER_EVENTS_TOPIC_ARN: z.string().startsWith('arn:aws:sns:'),\n  IDEMPOTENCY_TABLE: z.string().default('processed-messages'),\n});\n\nexport type Config = z.infer<typeof EnvSchema>;\nexport const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => EnvSchema.parse(env);"}]}]},{"type":"paragraph","content":[{"type":"text","text":"The infrastructure is created by one AWS CLI script (in a real project move it to Terraform, CDK or CloudFormation):"}]},{"type":"codeGroup","attrs":{"title":"Queues, DLQ, SNS, idempotency table and permissions"},"content":[{"type":"codeBlock","attrs":{"language":"bash","filename":"infra/create-queues.sh"},"content":[{"type":"text","text":"#!/usr/bin/env bash\n# Creates the queues, the SNS fan-out and the idempotency table for the pierogi shop.\nset -euo pipefail\nexport AWS_REGION=${AWS_REGION:-eu-central-1}\n\n# 1. Dead-letter queue first. Keep messages there longer than in the source queue:\n#    a standard queue keeps the original enqueue timestamp after redrive.\nDLQ_URL=$(aws sqs create-queue --queue-name orders-kitchen-dlq \\\n  --attributes MessageRetentionPeriod=1209600 --query QueueUrl --output text)\nDLQ_ARN=$(aws sqs get-queue-attributes --queue-url \"$DLQ_URL\" \\\n  --attribute-names QueueArn --query Attributes.QueueArn --output text)\n\n# 2. Main queue: long polling by default, 60 s visibility, DLQ after 5 failed receives.\nATTRS=$(mktemp)\ncat > \"$ATTRS\" <<JSON\n{\n  \"VisibilityTimeout\": \"60\",\n  \"ReceiveMessageWaitTimeSeconds\": \"20\",\n  \"MessageRetentionPeriod\": \"345600\",\n  \"SqsManagedSseEnabled\": \"true\",\n  \"RedrivePolicy\": \"{\\\"deadLetterTargetArn\\\":\\\"$DLQ_ARN\\\",\\\"maxReceiveCount\\\":\\\"5\\\"}\"\n}\nJSON\nQUEUE_URL=$(aws sqs create-queue --queue-name orders-kitchen --attributes \"file://$ATTRS\" --query QueueUrl --output text)\nQUEUE_ARN=$(aws sqs get-queue-attributes --queue-url \"$QUEUE_URL\" \\\n  --attribute-names QueueArn --query Attributes.QueueArn --output text)\n\n# 3. FIFO queue for per-order status changes (ordered within MessageGroupId = orderId).\naws sqs create-queue --queue-name order-status.fifo \\\n  --attributes FifoQueue=true,ContentBasedDeduplication=false >/dev/null\n\n# 4. SNS topic -> queue (fan-out). Raw delivery = the queue gets our JSON, not an SNS envelope.\nTOPIC_ARN=$(aws sns create-topic --name order-placed --query TopicArn --output text)\nPOLICY=$(sed -e \"s|QUEUE_ARN|$QUEUE_ARN|\" -e \"s|TOPIC_ARN|$TOPIC_ARN|\" infra/queue-policy-sns.json | jq -c .)\naws sqs set-queue-attributes --queue-url \"$QUEUE_URL\" --attributes \"$(jq -nc --arg p \"$POLICY\" '{Policy: $p}')\"\naws sns subscribe --topic-arn \"$TOPIC_ARN\" --protocol sqs --notification-endpoint \"$QUEUE_ARN\" \\\n  --attributes \"$(jq -nc --arg f \"$(jq -c . infra/filter-policy.json)\" '{RawMessageDelivery: \"true\", FilterPolicy: $f}')\"\n\n# 5. Idempotency table with TTL.\naws dynamodb create-table --table-name processed-messages \\\n  --attribute-definitions AttributeName=pk,AttributeType=S --key-schema AttributeName=pk,KeyType=HASH \\\n  --billing-mode PAY_PER_REQUEST >/dev/null\naws dynamodb wait table-exists --table-name processed-messages\naws dynamodb update-time-to-live --table-name processed-messages \\\n  --time-to-live-specification Enabled=true,AttributeName=expiresAt >/dev/null\n\necho \"ORDERS_QUEUE_URL=$QUEUE_URL\"\necho \"ORDER_EVENTS_TOPIC_ARN=$TOPIC_ARN\""}]},{"type":"codeBlock","attrs":{"language":"json","filename":"infra/queue-policy-sns.json"},"content":[{"type":"text","text":"{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"AllowOrderPlacedTopic\",\n      \"Effect\": \"Allow\",\n      \"Principal\": { \"Service\": \"sns.amazonaws.com\" },\n      \"Action\": \"sqs:SendMessage\",\n      \"Resource\": \"QUEUE_ARN\",\n      \"Condition\": { \"ArnEquals\": { \"aws:SourceArn\": \"TOPIC_ARN\" } }\n    }\n  ]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"infra/filter-policy.json"},"content":[{"type":"text","text":"{\n  \"type\": [\"order.placed\"],\n  \"channel\": [\"web\", \"phone\", \"pyszne\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"infra/iam-worker-policy.json"},"content":[{"type":"text","text":"{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"ConsumeKitchenQueue\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\"sqs:ReceiveMessage\", \"sqs:DeleteMessage\", \"sqs:ChangeMessageVisibility\", \"sqs:GetQueueAttributes\"],\n      \"Resource\": \"arn:aws:sqs:eu-central-1:123456789012:orders-kitchen\"\n    },\n    {\n      \"Sid\": \"Idempotency\",\n      \"Effect\": \"Allow\",\n      \"Action\": \"dynamodb:PutItem\",\n      \"Resource\": \"arn:aws:dynamodb:eu-central-1:123456789012:table/processed-messages\"\n    }\n  ]\n}"}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"DLQ first","marks":[{"type":"bold"}]},{"type":"text","text":", 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."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"maxReceiveCount: 5","marks":[{"type":"code"}]},{"type":"text","text":" – 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."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ReceiveMessageWaitTimeSeconds: 20","marks":[{"type":"code"}]},{"type":"text","text":" enables long polling for all consumers, including those that forget to set "},{"type":"text","text":"WaitTimeSeconds","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"SqsManagedSseEnabled","marks":[{"type":"code"}]},{"type":"text","text":" encrypts messages with an SQS-managed key. With your own KMS key, producers and consumers also need "},{"type":"text","text":"kms:GenerateDataKey","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"kms:Decrypt","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The queue policy","marks":[{"type":"bold"}]},{"type":"text","text":" allows only a specific SNS topic to send to it (the "},{"type":"text","text":"aws:SourceArn","marks":[{"type":"code"}]},{"type":"text","text":" condition), and "},{"type":"text","text":"RawMessageDelivery","marks":[{"type":"code"}]},{"type":"text","text":" means the queue receives our JSON, not an SNS envelope."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"step-2-the-producer-message-format-fifo-and-batches"},"content":[{"type":"text","text":"Step 2. The producer: message format, FIFO and batches"}]},{"type":"codeGroup","attrs":{"title":"Producer (Node.js, C#, Python)"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/messages.ts"},"content":[{"type":"text","text":"import { z } from 'zod';\n\n// A versioned envelope: consumers can reject or migrate unknown versions explicitly.\nexport const OrderPlacedSchema = z.object({\n  type: z.literal('order.placed'),\n  version: z.literal(1),\n  id: z.uuid(), // event id = idempotency key\n  occurredAt: z.iso.datetime(),\n  data: z.object({\n    orderId: z.string(),\n    channel: z.enum(['web', 'phone', 'pyszne']),\n    items: z.array(z.object({ dish: z.string(), quantity: z.number().int().positive() })).min(1),\n  }),\n});\n\nexport type OrderPlaced = z.infer<typeof OrderPlacedSchema>;"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/producer.ts"},"content":[{"type":"text","text":"import { randomUUID } from 'node:crypto';\nimport { SendMessageBatchCommand, SendMessageCommand, type SQSClient } from '@aws-sdk/client-sqs';\nimport type { OrderPlaced } from './messages.js';\n\nexport function orderPlaced(data: OrderPlaced['data']): OrderPlaced {\n  return { type: 'order.placed', version: 1, id: randomUUID(), occurredAt: new Date().toISOString(), data };\n}\n\nexport async function sendOrderPlaced(sqs: SQSClient, queueUrl: string, event: OrderPlaced): Promise<string | undefined> {\n  const isFifo = queueUrl.endsWith('.fifo');\n  const { MessageId } = await sqs.send(\n    new SendMessageCommand({\n      QueueUrl: queueUrl,\n      MessageBody: JSON.stringify(event),\n      // Attributes are readable without parsing the body (routing, filtering, metrics).\n      MessageAttributes: {\n        type: { DataType: 'String', StringValue: event.type },\n        channel: { DataType: 'String', StringValue: event.data.channel },\n      },\n      // FIFO only: order is kept per group, duplicates within 5 minutes are dropped.\n      ...(isFifo ? { MessageGroupId: event.data.orderId, MessageDeduplicationId: event.id } : {}),\n    }),\n  );\n  return MessageId;\n}\n\n// Up to 10 messages per call = up to 10x fewer requests (and a smaller bill).\nexport async function sendBatch(sqs: SQSClient, queueUrl: string, events: OrderPlaced[], maxAttempts = 3): Promise<void> {\n  for (let start = 0; start < events.length; start += 10) {\n    let pending = events.slice(start, start + 10);\n    for (let attempt = 1; pending.length > 0; attempt++) {\n      const result = await sqs.send(\n        new SendMessageBatchCommand({\n          QueueUrl: queueUrl,\n          Entries: pending.map((e) => ({ Id: e.id, MessageBody: JSON.stringify(e) })),\n        }),\n      );\n      // A batch call can succeed (HTTP 200) while some entries fail – always check `Failed`.\n      const failed = new Set((result.Failed ?? []).map((f) => f.Id));\n      pending = pending.filter((e) => failed.has(e.id));\n      if (pending.length > 0 && attempt >= maxAttempts) {\n        throw new Error(`${pending.length} messages not sent: ${JSON.stringify(result.Failed)}`);\n      }\n      if (pending.length > 0) await new Promise((r) => setTimeout(r, 200 * 2 ** attempt));\n    }\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"dotnet/SqsDemo/OrderProducer.cs"},"content":[{"type":"text","text":"using System.Text.Json;\nusing Amazon.SQS;\nusing Amazon.SQS.Model;\n\nnamespace SqsDemo;\n\n// Same JSON envelope as the Node.js producer: { type, version, id, occurredAt, data }.\npublic sealed record OrderItem(string Dish, int Quantity);\npublic sealed record OrderPlacedData(string OrderId, string Channel, IReadOnlyList<OrderItem> Items);\n\npublic sealed record OrderPlaced(string Type, int Version, Guid Id, DateTimeOffset OccurredAt, OrderPlacedData Data)\n{\n    public static OrderPlaced Create(string orderId, string channel, IReadOnlyList<OrderItem> items) =>\n        new(\"order.placed\", 1, Guid.NewGuid(), DateTimeOffset.UtcNow, new OrderPlacedData(orderId, channel, items));\n}\n\npublic sealed class OrderProducer(IAmazonSQS sqs, string queueUrl)\n{\n    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);\n\n    public async Task<string> SendAsync(OrderPlaced evt, CancellationToken ct = default)\n    {\n        var request = new SendMessageRequest\n        {\n            QueueUrl = queueUrl,\n            MessageBody = JsonSerializer.Serialize(evt, Json),\n            MessageAttributes = new Dictionary<string, MessageAttributeValue>\n            {\n                [\"type\"] = new() { DataType = \"String\", StringValue = evt.Type },\n                [\"channel\"] = new() { DataType = \"String\", StringValue = evt.Data.Channel },\n            },\n        };\n        if (queueUrl.EndsWith(\".fifo\", StringComparison.Ordinal))\n        {\n            request.MessageGroupId = evt.Data.OrderId; // ordering per order\n            request.MessageDeduplicationId = evt.Id.ToString(); // 5-minute deduplication window\n        }\n        var response = await sqs.SendMessageAsync(request, ct);\n        return response.MessageId;\n    }\n\n    public async Task SendBatchAsync(IReadOnlyList<OrderPlaced> events, CancellationToken ct = default)\n    {\n        foreach (var chunk in events.Chunk(10)) // max 10 entries per batch\n        {\n            var response = await sqs.SendMessageBatchAsync(new SendMessageBatchRequest\n            {\n                QueueUrl = queueUrl,\n                Entries = chunk.Select(e => new SendMessageBatchRequestEntry(e.Id.ToString(), JsonSerializer.Serialize(e, Json))).ToList(),\n            }, ct);\n            // HTTP 200 does not mean every entry made it.\n            if (response.Failed is { Count: > 0 } failed)\n                throw new InvalidOperationException($\"{failed.Count} messages failed: {string.Join(\", \", failed.Select(f => f.Code))}\");\n        }\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"python/producer.py"},"content":[{"type":"text","text":"import json\nimport os\nimport uuid\nfrom datetime import datetime, timezone\n\nimport boto3\n\nsqs = boto3.client(\"sqs\", region_name=os.environ.get(\"AWS_REGION\", \"eu-central-1\"))\nQUEUE_URL = os.environ[\"ORDERS_QUEUE_URL\"]\n\n\ndef order_placed(order_id: str, channel: str, items: list[dict]) -> dict:\n    return {\n        \"type\": \"order.placed\",\n        \"version\": 1,\n        \"id\": str(uuid.uuid4()),\n        \"occurredAt\": datetime.now(timezone.utc).isoformat(),\n        \"data\": {\"orderId\": order_id, \"channel\": channel, \"items\": items},\n    }\n\n\ndef send_order_placed(event: dict) -> str:\n    params = {\n        \"QueueUrl\": QUEUE_URL,\n        \"MessageBody\": json.dumps(event),\n        \"MessageAttributes\": {\n            \"type\": {\"DataType\": \"String\", \"StringValue\": event[\"type\"]},\n            \"channel\": {\"DataType\": \"String\", \"StringValue\": event[\"data\"][\"channel\"]},\n        },\n    }\n    if QUEUE_URL.endswith(\".fifo\"):\n        params[\"MessageGroupId\"] = event[\"data\"][\"orderId\"]\n        params[\"MessageDeduplicationId\"] = event[\"id\"]\n    return sqs.send_message(**params)[\"MessageId\"]\n\n\ndef send_batch(events: list[dict]) -> None:\n    for start in range(0, len(events), 10):  # max 10 entries per call\n        chunk = events[start : start + 10]\n        result = sqs.send_message_batch(\n            QueueUrl=QUEUE_URL,\n            Entries=[{\"Id\": e[\"id\"], \"MessageBody\": json.dumps(e)} for e in chunk],\n        )\n        if result.get(\"Failed\"):  # HTTP 200 does not mean every entry made it\n            raise RuntimeError(f\"failed entries: {result['Failed']}\")\n\n\nif __name__ == \"__main__\":\n    print(send_order_placed(order_placed(\"o-1001\", \"web\", [{\"dish\": \"ruskie\", \"quantity\": 20}])))"}]}]}]},"toc":[{"id":"standard-or-fifo","text":"Standard or FIFO?","level":2,"locked":false},{"id":"step-1-the-project-and-infrastructure","text":"Step 1. The project and infrastructure","level":2,"locked":false},{"id":"step-2-the-producer-message-format-fifo-and-batches","text":"Step 2. The producer: message format, FIFO and batches","level":2,"locked":false},{"id":"step-3-the-consumer-long-polling-visibility-timeout-heartbeat","text":"Step 3. The consumer: long polling, visibility timeout, heartbeat","level":2,"locked":true},{"id":"step-4-idempotency-a-duplicate-must-not-print-two-tickets","text":"Step 4. Idempotency: a duplicate must not print two tickets","level":2,"locked":true},{"id":"step-5-fan-out-through-sns","text":"Step 5. Fan-out through SNS","level":2,"locked":true},{"id":"step-6-lambda-as-a-consumer","text":"Step 6. Lambda as a consumer","level":2,"locked":true},{"id":"step-7-tests","text":"Step 7. Tests","level":2,"locked":true},{"id":"c-and-python-variants","text":"C# and Python variants","level":2,"locked":true},{"id":"operations-dlq-alarms-and-redrive","text":"Operations: DLQ, alarms and redrive","level":2,"locked":true},{"id":"costs","text":"Costs","level":2,"locked":true},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":true},{"id":"check-yourself","text":"Check yourself","level":2,"locked":true},{"id":"what-s-next","text":"What's next","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":63,"visibleBlocks":17,"resources":[{"id":"6b0857c03c96f2d34d0b43dd","type":"article","provider":"web","url":"https://milanjovanovic.tech/blog/complete-guide-to-amazon-sqs-and-amazon-sns-with-masstransit","embedUrl":null,"title":"Complete Guide to Amazon SQS and Amazon SNS With MassTransit","description":"In this article, we'll explore how to use Amazon SQS and SNS for asynchronous messaging in .NET applications.","author":"Milan Jovanović","thumbnailUrl":"https://milanjovanovic.tech/blog-covers/mnw_103.png","durationSec":null,"lang":"en","topics":["event-driven-architecture"],"techs":["dotnet"],"tags":["messaging","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2024-08-17T00:00:00.000Z","popularity":50,"verifiedAt":"2026-11-26T11:29:07.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857bf3c96f2d34d0b4262","type":"article","provider":"web","url":"https://aws.amazon.com/builders-library/avoiding-insurmountable-queue-backlogs","embedUrl":null,"title":"Avoiding insurmountable queue backlogs | AWS Builder Center","description":"How Amazon prevents queue backlogs from becoming unrecoverable, using backpressure, prioritization, and constant work to drain queues safely.","author":"Amazon Builders' Library","thumbnailUrl":"https://builder.aws.com/assets/og-hiXAX-on.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["aws","distributed-systems","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2019-12-05T12:00:00.000Z","popularity":65,"verifiedAt":"2026-11-26T11:25:40.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857bf3c96f2d34d0b42c4","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/patterns/idempotent-consumer","embedUrl":null,"title":"Idempotent Consumer Pattern","description":"Use the Idempotent Consumer pattern to safely process duplicate messages from at-least-once deliveries so that repeated processing has the same effects as processing once.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["azure","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":60,"verifiedAt":"2026-11-26T11:07:52.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c03c96f2d34d0b4400","type":"article","provider":"web","url":"https://event-driven.io/en/deduplication-in-distributed-systems","embedUrl":null,"title":"Deduplication in Distributed Systems: Myths, Realities, and Practical Solutions - Event-Driven.io","description":"Last week, we discussed how to use queuing to guarantee idempotency. What’s idempotency? It’s when we ensure that no matter how often we run the same operation, we’ll…","author":"Oskar Dudycz (event-driven.io)","thumbnailUrl":"https://event-driven.io/_astro/2024-11-25-cover.CXdKto9X_1KuQVR.png","durationSec":null,"lang":"en","topics":["event-driven-architecture"],"techs":["general"],"tags":["event-sourcing","system-design","distributed-systems","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2024-11-25T00:00:00.000Z","popularity":50,"verifiedAt":"2026-11-26T11:28:21.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857bf3c96f2d34d0b4291","type":"article","provider":"web","url":"https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter","embedUrl":null,"title":"Timeouts, retries, and backoff with jitter | AWS Builder Center","description":"How Amazon uses timeouts, retries, and exponential backoff with jitter to handle transient failures without overwhelming struggling services.","author":"Amazon Builders' Library","thumbnailUrl":"https://builder.aws.com/assets/og-hiXAX-on.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["aws","distributed-systems","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2019-12-05T12:00:00.000Z","popularity":65,"verifiedAt":"2026-11-26T11:25:38.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"}],"challenges":[{"id":"6b093dc191bd8fbaf2a0c8d0","slug":"inventory-cqrs","title":"Inventory with CQRS – separate write and read models","summary":"Warehouse commands validated on their own write model, events on a bus and a projection building a read model with a low-stock report. The read model can be rebuilt from events alone.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"architecture","status":"published","difficulty":"medium","topics":["cqrs","event-driven-architecture"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["cqrs","read-model","projection","events","inventory"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.519Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}