DEV Community

Dinesh_gowtham
Dinesh_gowtham

Posted on

How EventBridge Pipes Can Replace Lambda for Real‑Time Claude AI Agent Orchestration, Explained Simply

Imagine an AI coding assistant that can trigger downstream tools without writing a single Lambda function. EventBridge Pipes lets you connect Claude’s output directly to the services that need to act, cutting latency and boiler‑plate. In minutes you’ll have a fully‑observable, retry‑aware pipeline that feels like magic.

Why EventBridge Pipes Beats Lambda for AI Agents

When you build an AI‑driven workflow, the usual pattern is:

  1. Call the AI model (Claude, in our case).
  2. Run some code (e.g., a linter) based on the model’s suggestion.
  3. Notify a human (Slack, email, etc.).

Most engineers reach for AWS Lambda as the “glue” that runs step 2 because it’s a familiar serverless function. That works, but it adds hidden latency:

  • Cold starts – the first request after a period of inactivity has to spin up a container, adding 100‑200 ms or more.
  • Invisible retries – if the function fails, you need to add a dead‑letter queue (DLQ) or custom retry logic.
  • Extra code – you must write a handler, package dependencies, and maintain IAM permissions.

EventBridge Pipes is a newer service that acts like a conveyor belt for events. It takes an event from a source (our Claude response) and pushes it straight to a target (a Lambda that runs the linter, or even directly to an SNS topic). The belt can be configured to retry, filter, or transform messages without writing any extra code.

In plain English: A Pipe is a built‑in, managed workflow that moves data from A to B, handling retries and observability for you, while a Lambda‑only approach forces you to build those pieces yourself.

The Analogy

Think of a kitchen assembly line. With Lambda you’re handing each dish to a separate chef who must decide whether to re‑cook it if something goes wrong. With Pipes, the dish rides on a moving belt that automatically sends it to the next station, and if the station can’t handle it, the belt diverts the dish to a “scrap” bin (the DLQ) you set up once.

Known gotchas (EventBridge SDK)

  • The @aws-sdk/client-eventbridge client does not automatically retry on Pipe creation errors; you must handle exceptions in your setup script.
  • When you use a filter pattern on a Pipe, the pattern must be a valid JSON object—mistyped keys cause silent drops.

Known gotchas (Lambda SDK)

  • The @aws-sdk/client-lambda client requires you to specify the Publish flag if you want a new version each deployment; forgetting it keeps updating the $LATEST version, which can be confusing during debugging.
  • If you invoke a Lambda synchronously (InvocationType: 'RequestResponse') from a Pipe, the Pipe treats any non‑200 response as a failure and will apply its retry policy.

Setting Up a Claude‑Powered Agent with EventBridge

First, we need an Event Bus – a named channel where events live. Think of it as a mailbox that any service can drop a letter into.

// eventbus-setup.js
import { EventBridgeClient, CreateEventBusCommand } from "@aws-sdk/client-eventbridge";

// Create a client that talks to the EventBridge service in the current region
const ebClient = new EventBridgeClient({});

async function createBus() {
  try {
    // Create a custom event bus called "ClaudeAgentBus"
    const cmd = new CreateEventBusCommand({ Name: "ClaudeAgentBus" });
    const resp = await ebClient.send(cmd);
    console.log("Event bus created:", resp.EventBusArn);
  } catch (err) {
    // If the bus already exists, we ignore the error
    if (err.name !== "ResourceAlreadyExistsException") {
      console.error("Failed to create event bus:", err);
      process.exit(1);
    }
    console.log("Event bus already exists.");
  }
}

createBus();
Enter fullscreen mode Exit fullscreen mode

Key takeaway: An Event Bus is just a named queue for events; you can have many buses in one AWS account.

Why we need a custom bus

Claude will emit many kinds of events (tool calls, errors, status updates). By using a dedicated bus we keep our AI workflow isolated from other application events, which simplifies filtering later.

Streaming Claude Tool Calls Through a Pipe

Claude returns a JSON payload that may include a tool call – a request for the system to run a command (e.g., lint code). We publish that payload to our event bus, then let a Pipe forward it to the Lambda that executes the tool.

Step 1 – Publish Claude’s response

// claude-publisher.js
import { EventBridgeClient, PutEventsCommand } from "@aws-sdk/client-eventbridge";
import fetch from "node-fetch"; // Node 22 supports native fetch, but keep it explicit for clarity

const ebClient = new EventBridgeClient({});

async function callClaudeAndPublish(prompt) {
  // 1️⃣ Call Claude (replace with your actual endpoint and key)
  const response = await fetch("https://api.anthropic.com/v1/complete", {
    method: "POST",
    headers: {
      "x-api-key": process.env.CLAUDE_API_KEY,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-3-5-sonnet-20241022",
      prompt,
    }),
  });

  const data = await response.json();

  // 2️⃣ Publish the whole Claude response as an EventBridge event
  const putCmd = new PutEventsCommand({
    Entries: [
      {
        EventBusName: "ClaudeAgentBus",
        Source: "com.myapp.claude",
        DetailType: "ClaudeToolCall",
        // Detail must be a stringified JSON object
        Detail: JSON.stringify(data),
      },
    ],
  });

  const result = await ebClient.send(putCmd);
  console.log("Published event IDs:", result.Entries.map(e => e.EventId));
}

// Example usage
callClaudeAndPublish("Please lint the following JavaScript file...");
Enter fullscreen mode Exit fullscreen mode

Tip: The Detail field is limited to 256 KB. If Claude returns a huge payload, consider sending a reference (e.g., an S3 URL) instead.

Step 2 – Create the Pipe

A Pipe needs three pieces:

  • Source – our Event Bus.
  • Target – a Lambda function.
  • Filter – optional, but we’ll filter on DetailType = "ClaudeToolCall".
// pipe-setup.js
import { EventBridgeClient, CreatePipeCommand } from "@aws-sdk/client-eventbridge";

const ebClient = new EventBridgeClient({});

async function createPipe() {
  const cmd = new CreatePipeCommand({
    Name: "ClaudeToolPipe",
    // Source: the event bus we created earlier
    Source: "arn:aws:events:us-east-1:123456789012:event-bus/ClaudeAgentBus",
    // Target: the ARN of the Lambda that runs the linter
    Target: "arn:aws:lambda:us-east-1:123456789012:function:RunLinter",
    // Filter pattern ensures only tool‑call events get through
    FilterCriteria: {
      Filters: [
        {
          Pattern: JSON.stringify({ "detail-type": ["ClaudeToolCall"] }),
        },
      ],
    },
    // Optional: enable a dead‑letter queue for failed deliveries
    DeadLetterConfig: {
      Arn: "arn:aws:sqs:us-east-1:123456789012:ClaudePipeDLQ",
    },
    // Retry policy – try up to 3 times with exponential backoff
    RetryPolicy: {
      MaximumRetryAttempts: 3,
      MaximumEventAgeInSeconds: 300,
    },
  });

  try {
    const resp = await ebClient.send(cmd);
    console.log("Pipe created:", resp.PipeArn);
  } catch (err) {
    console.error("Failed to create pipe:", err);
  }
}

createPipe();
Enter fullscreen mode Exit fullscreen mode

In plain English: The Pipe watches the Claude bus, picks out any events that look like a tool call, and hands them to our Lambda. If the Lambda can’t be reached, the event lands in an SQS queue (the DLQ) so you never lose work.

Gotcha alert

If you omit the DeadLetterConfig, a Lambda invocation error (e.g., timeout) will simply be dropped after the retry attempts. That silent loss is hard to notice until you see missing Slack notifications.

Observability & Retries Using diagnostics_channel

Even though Pipes handle retries, it’s useful to see why a particular delivery failed. Node’s diagnostics_channel lets us tap into low‑level events emitted by the AWS SDK and the Lambda runtime.

// observability.js
import { createChannel } from "diagnostics_channel";

// Create a channel named "aws-sdk:eventbridge" (the SDK publishes to this name)
const ebChannel = createChannel("aws-sdk:eventbridge");

// Listen for any error events coming from EventBridge client calls
ebChannel.subscribe(event => {
  if (event?.error) {
    console.warn("[Obs] EventBridge error:", event.error.message);
    // Here you could push to CloudWatch Logs or an external monitoring service
  }
});

// Example: wrap the pipe‑creation call to see diagnostics
import { EventBridgeClient, CreatePipeCommand } from "@aws-sdk/client-eventbridge";
const ebClient = new EventBridgeClient({});

async function safeCreatePipe() {
  try {
    await ebClient.send(new CreatePipeCommand({ /* …same as before… */ }));
    console.log("Pipe created successfully");
  } catch (err) {
    console.error("Pipe creation failed:", err);
    // The diagnostics channel will also log the low‑level request/response
  }
}

safeCreatePipe();
Enter fullscreen mode Exit fullscreen mode

Key tip: diagnostics_channel is built into Node 14+. It gives you a non‑intrusive way to surface SDK errors without adding extra logging statements everywhere.

Why we need it

  • Visibility – When a Pipe retries, you can see each attempt in CloudWatch Logs of the Lambda and in the diagnostics output.
  • Root cause – If the failure is due to a permission error, the channel will expose the exact AWS error code (AccessDeniedException).
  • No code changes – You don’t have to modify the Lambda logic; the channel observes the SDK internals.

Putting It All Together: A Real‑World Code Review Bot

Let’s walk through a minimal end‑to‑end example. The flow is:

  1. Developer pushes code → a webhook triggers claude-publisher.js.
  2. Claude replies with a suggestion to run a linter.
  3. EventBridge Pipe forwards the suggestion to run-linter.js.
  4. Lambda executes the linter, publishes its result back to ClaudeResultBus.
  5. Another Pipe sends the result to an SNS topic that Slack is subscribed to.

Lambda that runs the linter

// run-linter.js (Lambda handler)
import { execSync } from "child_process";
import { EventBridgeClient, PutEventsCommand } from "@aws-sdk/client-eventbridge";

const ebClient = new EventBridgeClient({});

export const handler = async (event) => {
  // The event we receive is the whole Claude payload
  const payload = JSON.parse(event.detail);
  // Assume Claude gave us a code snippet under payload.tool_calls[0].input
  const code = payload?.tool_calls?.[0]?.input || "";

  // Write the code to a temporary file
  const fs = await import("fs/promises");
  const tmpPath = "/tmp/subject.js";
  await fs.writeFile(tmpPath, code, "utf8");

  let lintResult = "";
  try {
    // Run ESLint (you must bundle it with the Lambda or use a layer)
    lintResult = execSync(`npx eslint ${tmpPath} -f json`, { encoding: "utf8" });
  } catch (err) {
    // ESLint exits with non‑zero code when it finds problems
    lintResult = err.stdout || err.message;
  }

  // Publish the lint result back to a second bus
  const putCmd = new PutEventsCommand({
    Entries: [
      {
        EventBusName: "ClaudeResultBus",
        Source: "com.myapp.linter",
        DetailType: "LintResult",
        Detail: JSON.stringify({ lintResult, originalCode: code }),
      },
    ],
  });

  await ebClient.send(putCmd);
  console.log("Lint result published");
};
Enter fullscreen mode Exit fullscreen mode

In plain English: The Lambda receives Claude’s request, runs a linter locally, then sends the outcome back onto another event bus for downstream consumption.

Second Pipe → Slack

// slack-pipe-setup.js
import { EventBridgeClient, CreatePipeCommand } from "@aws-sdk/client-eventbridge";

const ebClient = new EventBridgeClient({});

async function createSlackPipe() {
  const cmd = new CreatePipeCommand({
    Name: "LintResultToSlack",
    Source: "arn:aws:events:us-east-1:123456789012:event-bus/ClaudeResultBus",
    Target: "arn:aws:sns:us-east-1:123456789012:SlackNotifications",
    FilterCriteria: {
      Filters: [
        {
          Pattern: JSON.stringify({ "detail-type": ["LintResult"] }),
        },
      ],
    },
    // Slack integration via SNS → HTTP endpoint is already set up elsewhere
    // No DLQ needed here because SNS will retry 3 times automatically
  });

  const resp = await ebClient.send(cmd);
  console.log("Slack Pipe ARN:", resp.PipeArn);
}

createSlackPipe();
Enter fullscreen mode Exit fullscreen mode

Tip: SNS can forward to an HTTPS endpoint that your Slack app exposes (via Incoming Webhook). This keeps the whole flow serverless.

Full runnable script

Below is a single script you can copy, npm install @aws-sdk/client-eventbridge node-fetch, set the required environment variables (CLAUDE_API_KEY), and execute. It creates the buses, the pipes, and sends a test prompt.

// full-demo.js
import "dotenv/config";
import { EventBridgeClient, CreateEventBusCommand, PutEventsCommand } from "@aws-sdk/client-eventbridge";
import { CreatePipeCommand } from "@aws-sdk/client-eventbridge";
import fetch from "node-fetch";

const REGION = "us-east-1";
const eb = new EventBridgeClient({ region: REGION });

async function main() {
  // 1️⃣ Create buses
  await Promise.all([
    eb.send(new CreateEventBusCommand({ Name: "ClaudeAgentBus" })),
    eb.send(new CreateEventBusCommand({ Name: "ClaudeResultBus" })),
  ]);
  console.log("Buses ready");

  // 2️⃣ Create the Pipe from Claude → Linter Lambda (assumes Lambda already exists)
  await eb.send(
    new CreatePipeCommand({
      Name: "ClaudeToolPipe",
      Source: `arn:aws:events:${REGION}:123456789012:event-bus/ClaudeAgentBus`,
      Target: "arn:aws:lambda:us-east-1:123456789012:function:RunLinter",
      FilterCriteria: { Filters: [{ Pattern: JSON.stringify({ "detail-type": ["ClaudeToolCall"] }) }] },
      DeadLetterConfig: { Arn: "arn:aws:sqs:us-east-1:123456789012:ClaudePipeDLQ" },
      RetryPolicy: { MaximumRetryAttempts: 3, MaximumEventAgeInSeconds: 300 },
    })
  );
  console.log("Pipe Claude→Linter created");

  // 3️⃣ Create the Pipe from LintResult → Slack (SNS)
  await eb.send(
    new CreatePipeCommand({
      Name: "LintResultToSlack",
      Source: `arn:aws:events:${REGION}:123456789012:event-bus/ClaudeResultBus`,
      Target: "arn:aws:sns:us-east-1:123456789012:SlackNotifications",
      FilterCriteria: { Filters: [{ Pattern: JSON.stringify({ "detail-type": ["LintResult"] }) }] },
    })
  );
  console.log("Pipe LintResult→Slack created");

  // 4️⃣ Call Claude and publish a test event
  const resp = await fetch("https://api.anthropic.com/v1/complete", {
    method: "POST",
    headers: {
      "x-api-key": process.env.CLAUDE_API_KEY,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-3-5-sonnet-20241022",
      prompt: "Please lint this code:\n```

js\nconst x=1;\n

```",
    }),
  });
  const data = await resp.json();

  await eb.send(
    new PutEventsCommand({
      Entries: [
        {
          EventBusName: "ClaudeAgentBus",
          Source: "com.myapp.claude",
          DetailType: "ClaudeToolCall",
          Detail: JSON.stringify(data),
        },
      ],
    })
  );

  console.log("Test event published – watch CloudWatch Logs for Lambda output");
}

main().catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Run it with:

node full-demo.js
Enter fullscreen mode Exit fullscreen mode

If everything is wired correctly, you’ll see:

  • A Lambda execution log showing the lint command.
  • A message appear in your Slack channel with the lint report.

The Takeaway

Key points to remember

  • EventBridge Pipes act like a managed conveyor belt, moving Claude’s output straight to the next service without a custom Lambda glue layer.
  • Latency drops because there’s no cold‑start container for a “glue” Lambda; the Pipe delivers events almost instantly.
  • Observability comes built‑in: CloudWatch metrics for pipe success/failure, plus optional diagnostics_channel hooks for deeper SDK insights.
  • Retry safety requires a dead‑letter queue; without it, a Lambda error can disappear silently.
  • Code footprint shrinks dramatically—you only write the business logic (the linter Lambda) and a few lines to publish/subscribe.
  • Scalability is handled by the service; Pipes can process thousands of events per second without you provisioning anything.

Conclusion

By replacing ad‑hoc Lambda glue with EventBridge Pipes, you turn a multi‑step AI workflow into a clean, observable pipeline that’s easier to reason about and cheaper to run. The example above shows a full end‑to‑end code‑review bot that:

  1. Calls Claude,
  2. Publishes the suggestion,
  3. Routes it through a Pipe to a Lambda that runs a tool,
  4. Sends the result back via another Pipe to Slack.

You’ve learned how to set up the necessary Event Buses, create Pipes with retry and DLQ policies, and add lightweight diagnostics for troubleshooting. The next step is to replace the linter Lambda with any other tool—unit test runners, security scanners, or deployment scripts—and watch the same Pipe architecture handle them with minimal extra code.

Happy building, and enjoy the magic of serverless pipelines!


Transparency notice

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

Published: 2026-11-26 · Primary focus: eventbridge

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.

Top comments (0)