{"id":"6b09417c5ce40d447918f299","slug":"aws-sqs","title":"Amazon SQS w praktyce – kolejki standard i FIFO, long polling, DLQ, idempotencja, SNS fan-out i Lambda (Node.js, C#, Python)","summary":"Przenosimy obsługę zamówień pierogarni do kolejki Amazon SQS – producent i konsument w AWS SDK v3 z long pollingiem, visibility timeout i heartbeatem, kolejka martwych listów (DLQ), idempotentne przetwarzanie z DynamoDB, wysyłka wsadowa, fan-out przez SNS i Lambda z częściowymi błędami wsadu. Warianty w C# (AWSSDK.SQS) i Pythonie (boto3).","servedLang":"pl","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":25,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:20.692Z","updatedAt":"2026-11-27T10:04:16.692Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"amber","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"Amazon SQS krok po kroku – standard vs FIFO, @aws-sdk/client-sqs, ReceiveMessage z long pollingiem, visibility timeout, DLQ i redrive, idempotencja (DynamoDB), SendMessageBatch, SNS fan-out z filtrami, Lambda z ReportBatchItemFailures, koszty; przykłady w Node.js, C# i Pythonie.","wordCount":4883,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"W piątek o 18:00 pierogarnia dostaje sto zamówień w kwadrans. Jeśli API po przyjęciu zamówienia synchronicznie drukuje bilecik w kuchni, wystawia fakturę i nalicza punkty lojalnościowe, to awaria drukarki zatrzymuje sprzedaż. Kolejka rozdziela te światy: API zapisuje zamówienie, wrzuca wiadomość i odpowiada klientowi w milisekundach, a reszta dzieje się w tle, we własnym tempie i z ponowieniami. W tym poradniku zbudujesz to na Amazon SQS – z pułapkami, które wychodzą dopiero na produkcji."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"SQS dostarcza wiadomość co najmniej raz","marks":[{"type":"bold"}]},{"type":"text","text":" (kolejka standard) – ta sama wiadomość może przyjść dwa razy, więc konsument musi być idempotentny."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Wiadomość nie znika po odebraniu.","marks":[{"type":"bold"}]},{"type":"text","text":" Staje się niewidoczna na czas "},{"type":"text","text":"visibility timeout","marks":[{"type":"italic"}]},{"type":"text","text":"; usuwasz ją dopiero po udanym przetworzeniu. Błąd = wiadomość wraca, a po N próbach trafia do kolejki martwych listów (DLQ)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Long polling, wsady i SNS fan-out","marks":[{"type":"bold"}]},{"type":"text","text":" to trzy dźwignie kosztów i architektury: mniej pustych odpowiedzi, mniej żądań i jedna publikacja dla wielu odbiorców."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kolejkę "},{"type":"text","text":"orders-kitchen","marks":[{"type":"code"}]},{"type":"text","text":" z DLQ i kolejkę FIFO na statusy, temat SNS "},{"type":"text","text":"order-placed","marks":[{"type":"code"}]},{"type":"text","text":" z filtrem subskrypcji, producenta z wysyłką wsadową (z obsługą częściowych błędów), konsumenta z long pollingiem, równoległym przetwarzaniem, heartbeatem i łagodnym zamykaniem, idempotencję na DynamoDB oraz handler Lambdy z "},{"type":"text","text":"batchItemFailures","marks":[{"type":"code"}]},{"type":"text","text":". Do tego warianty producenta i konsumenta w C# i Pythonie – wszystkie trzy języki wymieniają ten sam format wiadomości. Kod (26 plików) pobierzesz jako ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" konto AWS i AWS CLI v2 (plus "},{"type":"text","text":"jq","marks":[{"type":"code"}]},{"type":"text","text":" dla skryptu infrastruktury), Node.js 22+, podstawy "},{"type":"text","text":"AWS SDK v3 z poradnika S3","marks":[{"type":"link","attrs":{"href":"/pl/articles/aws-s3"}}]},{"type":"text","text":" (klienci, poświadczenia). Dla wariantów: .NET 10 SDK lub Python 3.10+."}]},{"type":"stats","attrs":{"items":[{"value":"1 MiB","label":"maks. rozmiar wiadomości","hint":"od sierpnia 2025 (wcześniej 256 KiB)"},{"value":"20 s","label":"maks. long polling","hint":"`WaitTimeSeconds`"},{"value":"12 h","label":"maks. visibility timeout","hint":"domyślnie 30 s"},{"value":"14 dni","label":"maks. retencja","hint":"domyślnie 4 dni"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  API[API pierogarni] -->|Publish order.placed| T{{SNS: order-placed}}\n  T -->|filtr: wszystkie| QK[[SQS: orders-kitchen]]\n  T -->|filtr: wszystkie| QI[[SQS: invoices]]\n  T -->|filtr: channel = web| QL[[SQS: loyalty]]\n  QK --> WK[Worker kuchni<br/>ECS / kontener]\n  QI --> LI[Lambda faktur]\n  QL --> WL[Worker punktów]\n  QK -. po 5 nieudanych próbach .-> DLQ[[orders-kitchen-dlq]]\n  WK --> DDB[(DynamoDB<br/>idempotencja)]","caption":"Zamówienie przez SNS do wielu kolejek – każdy odbiorca w swoim tempie"}},{"type":"heading","attrs":{"level":2,"id":"standard-czy-fifo"},"content":[{"type":"text","text":"Standard czy 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":"Dostarczenie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"co najmniej raz – możliwe duplikaty"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dokładnie raz w obrębie 5-minutowego okna deduplikacji"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kolejność"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"najlepsza możliwa, bez gwarancji"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ściśle w obrębie "},{"type":"text","text":"MessageGroupId","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przepustowość"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"praktycznie nieograniczona"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"300 wywołań/s na akcję bez wsadów (3000 wiadomości/s z wsadami); tryb high throughput – dużo więcej, zależnie od regionu"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Cena (za 1 mln żądań)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ok. 0,40 USD"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ok. 0,50 USD"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kiedy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"bilety do kuchni, e-maile, przetwarzanie zdjęć"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zmiany statusu jednego zamówienia, operacje na saldzie"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Domyślnie wybieraj kolejkę standard i idempotentnych konsumentów – to i tak potrzebne, bo nawet FIFO nie uchroni przed duplikatem, gdy konsument przetworzy wiadomość, ale nie zdąży jej usunąć. FIFO bierz tam, gdzie kolejność ma znaczenie biznesowe, i dobieraj "},{"type":"text","text":"MessageGroupId","marks":[{"type":"code"}]},{"type":"text","text":" tak, żeby grup było dużo (np. id zamówienia, a nie jedna stała wartość – wtedy cała kolejka przetwarza się jednym wątkiem)."}]},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt-i-infrastruktura"},"content":[{"type":"text","text":"Krok 1. Projekt i infrastruktura"}]},{"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":"Konfiguracja projektu"},"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":"Infrastrukturę tworzy jeden skrypt AWS CLI (w prawdziwym projekcie przenieś to do Terraform, CDK albo CloudFormation):"}]},{"type":"codeGroup","attrs":{"title":"Kolejki, DLQ, SNS, tabela idempotencji i uprawnienia"},"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 najpierw","marks":[{"type":"bold"}]},{"type":"text","text":", z dłuższą retencją niż kolejka źródłowa – w kolejce standard wiadomość po przeniesieniu do DLQ zachowuje oryginalny czas dodania, więc przy tej samej retencji mogłaby wygasnąć, zanim ktoś ją obejrzy."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"maxReceiveCount: 5","marks":[{"type":"code"}]},{"type":"text","text":" – po pięciu odbiorach bez usunięcia wiadomość trafia do DLQ. Zbyt mała liczba (1–2) wysyła do DLQ wiadomości, które padły na chwilowej awarii; zbyt duża blokuje kolejkę „trującymi” wiadomościami."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ReceiveMessageWaitTimeSeconds: 20","marks":[{"type":"code"}]},{"type":"text","text":" włącza long polling dla wszystkich konsumentów, także tych, którzy zapomną ustawić "},{"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":" szyfruje wiadomości kluczem zarządzanym przez SQS. Przy własnym kluczu KMS producent i konsument potrzebują też "},{"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":"Polityka kolejki","marks":[{"type":"bold"}]},{"type":"text","text":" pozwala wysyłać do niej tylko konkretnemu tematowi SNS (warunek "},{"type":"text","text":"aws:SourceArn","marks":[{"type":"code"}]},{"type":"text","text":"), a "},{"type":"text","text":"RawMessageDelivery","marks":[{"type":"code"}]},{"type":"text","text":" sprawia, że do kolejki trafia nasz JSON, a nie koperta SNS."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-producent-format-wiadomosci-fifo-i-wsady"},"content":[{"type":"text","text":"Krok 2. Producent: format wiadomości, FIFO i wsady"}]},{"type":"codeGroup","attrs":{"title":"Producent (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-czy-fifo","text":"Standard czy FIFO?","level":2,"locked":false},{"id":"krok-1-projekt-i-infrastruktura","text":"Krok 1. Projekt i infrastruktura","level":2,"locked":false},{"id":"krok-2-producent-format-wiadomosci-fifo-i-wsady","text":"Krok 2. Producent: format wiadomości, FIFO i wsady","level":2,"locked":false},{"id":"krok-3-konsument-long-polling-visibility-timeout-heartbeat","text":"Krok 3. Konsument: long polling, visibility timeout, heartbeat","level":2,"locked":true},{"id":"krok-4-idempotencja-duplikat-nie-moze-wydrukowac-dwoch-bilecikow","text":"Krok 4. Idempotencja: duplikat nie może wydrukować dwóch bilecików","level":2,"locked":true},{"id":"krok-5-fan-out-przez-sns","text":"Krok 5. Fan-out przez SNS","level":2,"locked":true},{"id":"krok-6-lambda-jako-konsument","text":"Krok 6. Lambda jako konsument","level":2,"locked":true},{"id":"krok-7-testy","text":"Krok 7. Testy","level":2,"locked":true},{"id":"warianty-w-c-i-pythonie","text":"Warianty w C# i Pythonie","level":2,"locked":true},{"id":"operacje-dlq-alarmy-i-redrive","text":"Operacje: DLQ, alarmy i redrive","level":2,"locked":true},{"id":"koszty","text":"Koszty","level":2,"locked":true},{"id":"typowe-bledy","text":"Typowe błędy","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","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":"Magazyn z CQRS – osobny model zapisu i odczytu","summary":"Komendy magazynowe walidowane na własnym modelu zapisu, zdarzenia na szynie i projekcja budująca model odczytu z raportem niskich stanów. Model odczytu da się odtworzyć z samych zdarzeń.","servedLang":"pl","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":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}