跳到正文
DEV Community· Dinesh_gowtham·· 1 小時前AI 評分16

Claude Code 程式碼建議如何透過 SNS FIFO 主題保持有序即時傳送:簡明教學

How to Use SNS FIFO Topics for Ordered, Real‑Time Claude Code Suggestions, Explained Simply

AI 導讀

文章講解如何透過 SNS FIFO 主題發佈 Claude Code 程式碼建議,確保相同 MessageGroupId 的訊息按發佈次序送達訂閲者。Node.js 22 Lambda 使用 PublishBatch 發佈訊息,並以 SHA-256 雜湊作為 MessageDeduplicationId;相同 ID 的訊息若在五分鐘內重複提交,SNS 會將其丟棄。

正文

Claude just gave you a fresh piece of code—how do you get that suggestion to the right developers instantly without losing order? By publishing it to an SNS FIFO topic you can fan‑out reliably to Slack, a review Lambda, and a logging queue. This post shows you the exact steps, so you can trust the flow the first time.

Why SNS FIFO Topics Matter for AI Assistants

When an AI assistant like Claude spits out a series of suggestions, the order often carries meaning. The first suggestion might be a quick fix, the second a refactor, the third a performance tweak. If those messages arrive out of order, reviewers could waste time chasing a later suggestion that depends on an earlier one.

FIFO stands for First‑In‑First‑Out. An SNS FIFO topic guarantees that subscribers receive messages in the exact sequence they were published, as long as they share the same MessageGroupId. Think of it like a line at a coffee shop: everyone gets their drink in the order they arrived, not in a random shuffle.

In plain English: Using a FIFO topic makes sure “the code suggestion that came first is the one everyone sees first,” which is essential for deterministic CI pipelines.

Key pieces of the FIFO puzzle

Term What it means
MessageGroupId A label (string) that groups related messages together. All messages with the same group travel in order, while different groups can be processed in parallel.
MessageDeduplicationId A token that tells SNS “I’ve already seen this payload.” If the same ID shows up again within five minutes, SNS quietly drops the duplicate.
Standard vs FIFO Standard topics give best‑effort delivery with no ordering guarantees. FIFO topics add ordering and exactly‑once delivery (when deduplication is handled correctly).

Gotcha: You cannot mix a standard topic with a FIFO subscription. The whole chain must stay FIFO if you need ordering.

Setting Up a Claude‑Powered Code Suggestion Publisher

The publisher lives in a Node.js 22 Lambda. Its job is simple:

  1. Call Claude’s HTTP API to get a suggestion.
  2. Turn the suggestion into a JSON payload.
  3. Compute a SHA‑256 hash of that payload – this becomes the MessageDeduplicationId.
  4. Send the payload to an SNS FIFO topic using the PublishBatch operation (batching lets you send many suggestions at once, but we’ll use a single‑item batch for clarity).

Step‑by‑step code

// src/publisher.ts
import { SNSClient, PublishBatchCommand } from "@aws-sdk/client-sns";
import crypto from "crypto";

// ---------- 1. Create the SNS client (uses default credentials) ----------
const sns = new SNSClient({ region: "us-east-1" });

// ---------- 2. Helper: turn any object into a SHA‑256 string ----------
function sha256(data: string): string {
  // crypto.createHash returns a hash object; we feed the data and get a hex string
  return crypto.createHash("sha256").update(data).digest("hex");
}

// ---------- 3. Main handler for the Lambda ----------
export const handler = async (event: any) => {
  // 3a. Ask Claude for a suggestion (replace with your real endpoint and auth)
  const claudeResponse = await fetch("https://api.anthropic.com/v1/complete", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": process.env.CLAUDE_API_KEY!,
    },
    body: JSON.stringify({
      prompt: "Suggest a TypeScript function to debounce user input.",
      max_tokens: 300,
    }),
  });

  const suggestion = await claudeResponse.json(); // assume JSON payload

  // 3b. Build the message we will publish
  const payload = {
    repository: event.repositoryName, // coming from the event that triggered the Lambda
    suggestion,
    timestamp: new Date().toISOString(),
  };

  const payloadString = JSON.stringify(payload);

  // 3c. Compute deduplication ID – must be unique for every distinct payload
  const dedupId = sha256(payloadString);

  // 3d. Publish to the FIFO topic
  const command = new PublishBatchCommand({
    TopicArn: process.env.SNS_FIFO_TOPIC_ARN, // ARN of the FIFO topic
    PublishBatchRequestEntries: [
      {
        Id: "msg1", // identifier within this batch, must be unique per batch
        Message: payloadString,
        MessageGroupId: payload.repository, // groups by repo name → ordered per repo
        MessageDeduplicationId: dedupId,
      },
    ],
  });

  try {
    const result = await sns.send(command);
    console.log("Publish result:", result);
  } catch (err) {
    console.error("Failed to publish suggestion:", err);
    // re‑throw so Lambda records a failure; later we can wire a DLQ
    throw err;
  }
};

Why this matters

  • The MessageGroupId ties every suggestion for the same repository together, guaranteeing order per repo.
  • The SHA‑256 hash guarantees that even if the same suggestion is generated twice, SNS will treat the second as a duplicate only if the payload is identical and the request occurs within five minutes.

Tip: Use a cryptographic hash (SHA‑256) rather than a simple counter. Counters can clash when multiple Lambdas run in parallel, leading to silent drops.

Known Lambda gotchas

  • In Node 22, require('esm') can break existing Lambda layers without a clear error – keep your code pure ESM or CommonJS, not a mix.
  • SnapStart (a cold‑start optimization) gives no benefit when the Lambda runs inside a VPC because the network attachment time dominates.

Configuring Ordered Fan‑Out to Lambda and SQS

Now that we can publish ordered messages, we need listeners that also respect ordering. A typical pipeline might look like:

  • Slack notifier Lambda – posts the suggestion to a channel.
  • Review Lambda – runs static analysis on the suggestion.
  • Logging queue (SQS FIFO) – stores every suggestion for audit.

All three must be FIFO subscribers of the same SNS topic.

Creating the FIFO topic (CLI example)

aws sns create-topic \
  --name claude-code-suggestions.fifo \
  --attributes FifoTopic=true

Notice the .fifo suffix – SNS requires it for FIFO topics.

Subscribing a Lambda (FIFO)

import { SNSClient, SubscribeCommand } from "@aws-sdk/client-sns";

const sns = new SNSClient({ region: "us-east-1" });

await sns.send(
  new SubscribeCommand({
    TopicArn: process.env.SNS_FIFO_TOPIC_ARN,
    Protocol: "lambda",
    Endpoint: process.env.SLACK_NOTIFIER_ARN, // ARN of the Lambda that posts to Slack
    Attributes: {
      // FIFO subscription attributes
      RawMessageDelivery: "true", // deliver the raw JSON string, not SNS envelope
    },
  })
);

Gotcha: SNS delivery retries happen per subscriber. If the Slack Lambda times out, SNS will retry, but you won’t see a warning unless you enable CloudWatch metrics or a dead‑letter queue (DLQ) on the Lambda's destination.

Subscribing an SQS FIFO queue

import { SNSClient, SubscribeCommand } from "@aws-sdk/client-sns";

await sns.send(
  new SubscribeCommand({
    TopicArn: process.env.SNS_FIFO_TOPIC_ARN,
    Protocol: "sqs",
    Endpoint: process.env.LOGGING_QUEUE_ARN, // ARN of the FIFO queue
    Attributes: {
      RawMessageDelivery: "true",
      // Message attribute filtering allows us to route only certain suggestions,
      // but remember the 5‑attribute limit per subscription.
      FilterPolicy: JSON.stringify({
        repository: [{ prefix: "my‑awesome‑app" }],
      }),
    },
  })
);

Important: The SQS queue must also be FIFO (my-queue.fifo). SNS will refuse to attach a FIFO topic to a standard queue.

In plain English: Think of the topic as a newspaper printing press. Each subscriber (Lambda, queue) is a different delivery van; they all get the same ordered pages, but if a van breaks down, the press keeps trying to hand the paper to that van alone.

Subscription limits to keep in mind

  • Each subscription can have at most 5 message attributes for filtering.
  • SNS to Lambda does not create a dead‑letter queue automatically. If the Lambda throws, the message disappears after retries. Add a DLQ manually by wiring the Lambda’s DeadLetterConfig.

Handling Deduplication and Errors

The silent drop behavior of MessageDeduplicationId is the biggest surprise for newcomers. If you generate the same ID twice within five minutes, SNS will not deliver the second copy and will not log an error.

Generating a truly unique ID

The hash‑based approach from the publisher works, but you must include something that changes for every distinct suggestion. A good recipe:

function makeDedupId(payload: object): string {
  // Include the repository name, the suggestion text, and a timestamp down to ms
  const data = `${payload.repository}|${payload.suggestion.text}|${Date.now()}`;
  return sha256(data);
}

Adding Date.now() ensures the hash changes even if the suggestion text repeats quickly, while still being deterministic for identical payloads that happen after the five‑minute window.

Monitoring delivery failures

Because SNS retries are invisible by default, set up the following:

  • CloudWatch Metric Filters on NumberOfNotificationsFailed for each subscription.
  • DLQ for the review Lambda – configure DeadLetterConfig to an SQS queue so you can inspect failed invocations.
  • Lambda error handling – log the full event and error stack, then re‑throw to trigger the retry cycle.
// Example of attaching a DLQ to a Lambda (using AWS SDK for Lambda)
import { LambdaClient, UpdateFunctionConfigurationCommand } from "@aws-sdk/client-lambda";

const lambda = new LambdaClient({ region: "us-east-1" });

await lambda.send(
  new UpdateFunctionConfigurationCommand({
    FunctionName: process.env.REVIEW_LAMBDA_NAME,
    DeadLetterConfig: {
      TargetArn: process.env.REVIEW_DLQ_ARN, // FIFO queue ARN
    },
  })
);

Gotcha: The Lambda SDK for Node 22 uses ESM by default. If you still write require('aws-sdk/client-lambda'), the import will fail silently in the runtime. Stick to import statements as shown.

De‑duplication edge case: identical suggestions from different repos

If two repositories happen to generate the exact same suggestion at the same millisecond, the hash will clash. To avoid accidental drops, always incorporate the repository name (or a unique repoId) into the deduplication string, as the example above does.

Putting It All Together: End‑to‑End Flow

Let’s walk through a typical request:

  1. Developer pushes code → a webhook triggers the Claude Publisher Lambda.
  2. Lambda calls Claude, receives JSON, builds payload, computes dedup ID, publishes to claude-code-suggestions.fifo.
  3. SNS receives the batch and stores it in order per MessageGroupId (repo name).
  4. Three FIFO subscriptions pull the message:
    • Slack Lambda posts a nicely formatted message to a channel.
    • Review Lambda runs a quick lint check and returns a status to a dashboard (via another SNS topic).
    • Logging SQS FIFO queue archives the payload for compliance.
  5. If any subscriber fails, SNS retries up to the default back‑off schedule. Failures that exceed retries are recorded in CloudWatch; the Review Lambda also sends the message to its DLQ.

Minimal orchestration script (CDK‑like pseudo‑code)

// infra.ts – creates all resources with correct FIFO settings
import {
  SNSClient,
  CreateTopicCommand,
  SetTopicAttributesCommand,
} from "@aws-sdk/client-sns";
import {
  LambdaClient,
  CreateFunctionCommand,
  UpdateFunctionConfigurationCommand,
} from "@aws-sdk/client-lambda";
import {
  SQSClient,
  CreateQueueCommand,
} from "@aws-sdk/client-sqs";

const region = "us-east-1";
const sns = new SNSClient({ region });
const lambda = new LambdaClient({ region });
const sqs = new SQSClient({ region });

async function main() {
  // 1️⃣ Create FIFO topic
  const topicRes = await sns.send(
    new CreateTopicCommand({
      Name: "claude-code-suggestions.fifo",
      Attributes: { FifoTopic: "true" },
    })
  );
  const topicArn = topicRes.TopicArn!;

  // 2️⃣ Create FIFO queue for logging
  const queueRes = await sqs.send(
    new CreateQueueCommand({
      QueueName: "claude-logging.fifo",
      Attributes: {
        FifoQueue: "true",
        ContentBasedDeduplication: "false",
      },
    })
  );
  const queueArn = `arn:aws:sqs:${region}:${process.env.AWS_ACCOUNT_ID}:claude-logging.fifo`;

  // 3️⃣ Create Slack notifier Lambda (code omitted for brevity)
  const slackLambdaRes = await lambda.send(
    new CreateFunctionCommand({
      FunctionName: "SlackNotifier",
      Runtime: "nodejs22.x",
      Role: process.env.LAMBDA_ROLE_ARN,
      Handler: "slack.handler",
      Code: { /* S3 bucket info */ },
    })
  );

  // 4️⃣ Subscribe Lambda (FIFO) to topic
  await sns.send(
    new SubscribeCommand({
      TopicArn: topicArn,
      Protocol: "lambda",
      Endpoint: slackLambdaRes.FunctionArn,
      Attributes: { RawMessageDelivery: "true" },
    })
  );

  // 5️⃣ Subscribe FIFO queue
  await sns.send(
    new SubscribeCommand({
      TopicArn: topicArn,
      Protocol: "sqs",
      Endpoint: queueArn,
      Attributes: { RawMessageDelivery: "true" },
    })
  );

  // 6️⃣ Wire DLQ to Review Lambda (code omitted)
  console.log("All resources created and linked.");
}

main().catch(console.error);

The script shows the essential pieces without overwhelming detail: create a FIFO topic, a FIFO queue, a Lambda, then wire them together. All attributes required for FIFO operation are explicit (FifoTopic, FifoQueue, RawMessageDelivery).

Key takeaway: Every component that participates in ordering must be FIFO; mixing standard and FIFO resources breaks the guarantee.

The Takeaway

Ordered pipelines are not a luxury; they are a safety net for AI‑driven code suggestions.

  • FIFO topics preserve the exact order of suggestions per repository using MessageGroupId.
  • MessageDeduplicationId must be unique for each distinct payload; a SHA‑256 of the payload plus a timestamp works well.
  • All subscribers must also be FIFO (Lambda or SQS); otherwise SNS will reject the subscription.
  • Delivery retries are per‑subscriber and invisible unless you add CloudWatch alarms or dead‑letter queues.
  • Common pitfalls: duplicate dedup IDs cause silent drops, mixing standard/FIFO resources throws errors, and Node 22’s ESM handling can break Lambda layer imports.
  • Monitoring matters: set up metrics for failed notifications and configure DLQs for any Lambda that processes suggestions.

With these steps you can build a reliable, ordered fan‑out that moves Claude’s code suggestions from the AI model straight into the hands of the people who need them—without losing a single line or mixing up the sequence. Happy coding!


Transparency notice

This article was written with the help of an AI system — Groq (GPT OSS 120B).

Published: 2026-11-25 · Primary focus: SNS

All code blocks are intended to be correct and runnable, but please verify them
against the official docs for the tools mentioned before using in production.

Find an error? Drop a comment — corrections are always welcome.

來源:DEV Community · dev.to