AI agents generate a flood of internal events that most engineers can’t see without third‑party APM tools. With CloudWatch Application Signals now GA, you can pull those traces straight into the AWS console—no Datadog required. This post shows exactly how to wire OpenTelemetry in a Node.js Claude‑powered Lambda and turn raw spans into actionable metrics.
What Are CloudWatch Application Signals?
Why it matters – When a Lambda runs an AI model, it makes many tiny decisions: token generation, context stitching, retry handling, etc. Each decision creates a span (a timed piece of work). Without a view of those spans you only see the final Lambda duration, missing the root causes of latency or error spikes.
CloudWatch Application Signals (often shortened to Application Signals) is a built‑in observability layer that collects traces, logs, and custom metrics and presents them together in the CloudWatch console. It works like a universal adapter that understands data from OpenTelemetry, X‑Ray, and native AWS services, then groups everything under a service name and a namespace you choose.
In plain English: Application Signals is AWS’s answer to “where did my request go?” – it stitches together every hop inside your Lambda so you can see the whole story without adding a separate APM product.
Key pieces to remember
| Piece | What it is | Why you need it |
|---|---|---|
| Trace | A collection of spans that belong to a single request. | Shows end‑to‑end latency. |
| Span | One timed operation, e.g., “call Claude”. | Lets you zoom into hot spots. |
| EMF metric | “Embedded Metric Format” – a JSON‑like payload that CloudWatch can turn into a metric without a separate putMetricData call. | Gives you custom, high‑resolution numbers (like token‑usage) alongside traces. |
| Service name | A string you set on the OpenTelemetry exporter (e.g., my-clause-agent). |
Determines which dashboard the trace appears in. |
| Namespace | A grouping label for metrics, usually AWS/‑prefixed. |
Prevents your custom metrics from colliding with others. |
Tip: The service name you send to the OTLP exporter must match the name you use when you look at Application Signals. If they differ, your traces land in the “Unidentified” bucket and won’t show up on the dashboards.
Setting Up OpenTelemetry in Node.js for Claude Agents
Why we need OpenTelemetry – OpenTelemetry is an open‑source standard for generating traces and metrics. AWS’s Application Signals can ingest data from the OpenTelemetry protocol (OTLP), so by installing the OpenTelemetry SDK we get a bridge from our code to CloudWatch without writing a custom exporter.
Step‑by‑step setup
- Create a new Lambda project (TypeScript).
- Add the required packages – the OpenTelemetry core, the Node.js API, the OTLP HTTP exporter, and the AWS SDK clients we’ll need later.
npm init -y
npm install --save-dev typescript @types/aws-lambda
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http \
@aws-sdk/client-cloudwatch @aws-sdk/client-xray \
@aws-sdk/credential-providers
-
Configure the OpenTelemetry SDK. The most important line is setting
resource.service.name. Think ofresourceas a name tag you put on every span so the backend knows who produced it.
// otel-config.ts
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
// -------------------------------------------------------------------
// What this file does:
// 1. Creates a tracer provider (the object that creates spans).
// 2. Attaches an OTLP HTTP exporter that talks to the CloudWatch endpoint.
// 3. Labels every span with a service name that Application Signals understands.
// -------------------------------------------------------------------
// Service name must match the name you’ll use later in the console.
const serviceName = 'claude-agent-service';
const provider = new NodeTracerProvider({
// Resource is a set of attributes attached to every span.
resource: new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: serviceName,
}),
});
const exporter = new OTLPTraceExporter({
// CloudWatch Application Signals listens on this endpoint.
// The region is taken from the Lambda’s environment.
url: `https://otel.${process.env.AWS_REGION}.amazonaws.com/v1/traces`,
});
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));
// Register the provider globally – now any `@opentelemetry/api` call uses it.
provider.register();
// Optional: auto‑instrument common libraries (http, https, aws-sdk, etc.)
registerInstrumentations({
instrumentations: [], // add specific instrumentations if you like
});
export const tracer = provider.getTracer('claude-agent-tracer');
- Use the tracer inside your Lambda handler. The code below shows a minimal Claude call via Bedrock, wrapped in a span.
// index.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { BedrockRuntimeClient, InvokeModelCommand } from '@aws-sdk/client-bedrock-runtime';
import { CloudWatchClient, PutMetricDataCommand } from '@aws-sdk/client-cloudwatch';
import { XRayClient, PutTraceSegmentsCommand } from '@aws-sdk/client-xray';
import { tracer } from './otel-config';
import { context, propagation, trace } from '@opentelemetry/api';
// -------------------------------------------------------------------
// Why we do this:
// * `tracer.startActiveSpan` creates a span that automatically ends when the
// callback finishes.
// * Inside the span we call Claude, emit a custom metric, and forward the X‑Ray
// trace ID so Application Signals can link the two.
// -------------------------------------------------------------------
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
// Start a top‑level span for the whole request.
return tracer.startActiveSpan('lambda.handler', async (span) => {
try {
// -----------------------------------------------------------------
// 1️⃣ Call Claude via Bedrock.
// -----------------------------------------------------------------
const bedrock = new BedrockRuntimeClient({});
const invokeCmd = new InvokeModelCommand({
modelId: 'anthropic.claude-v2',
// Prompt comes from the API Gateway body.
body: JSON.stringify({ prompt: event.body ?? '' }),
contentType: 'application/json',
});
const bedrockResponse = await bedrock.send(invokeCmd);
const claudeResult = new TextDecoder().decode(bedrockResponse.body);
// -----------------------------------------------------------------
// 2️⃣ Emit an EMF metric (aws.lambda.duration) – we’ll also send a
// custom metric for token usage.
// -----------------------------------------------------------------
const cw = new CloudWatchClient({});
const emfMetric = {
_aws: {
// Namespace tells CloudWatch where to store the metric.
// Use a custom namespace to avoid colliding with AWS defaults.
Namespace: 'MyAI/ClaudeAgent',
// Timestamp is optional; CloudWatch will add one if omitted.
Timestamp: new Date(),
},
// Custom fields become dimensions or metric values.
TokenCount: JSON.parse(claudeResult).usage?.inputTokens ?? 0,
// A required field for EMF – it tells CloudWatch the metric name.
aws_lambda_duration: process.env.AWS_LAMBDA_FUNCTION_TIMEOUT ?? 3,
};
// PutMetricData is not needed when using EMF – the payload is logged.
// However, we still need to send a log event so CloudWatch can ingest it.
console.log(JSON.stringify(emfMetric));
// -----------------------------------------------------------------
// 3️⃣ Propagate X‑Ray trace ID so Application Signals can join the dots.
// -----------------------------------------------------------------
// X‑Ray uses a header called `X-Amzn-Trace-Id`. We copy it into the
// OpenTelemetry context so the OTLP exporter includes it.
const xray = new XRayClient({});
const segment = {
name: 'claude-agent-segment',
id: span.spanContext().spanId,
trace_id: `1-${process.env.AWS_LAMBDA_FUNCTION_NAME}-${span.spanContext().traceId}`,
start_time: Date.now() / 1000,
end_time: (Date.now() + 10) / 1000, // dummy end time
};
// In a real Lambda you would call `PutTraceSegments` only if you need
// custom X‑Ray data; otherwise the SDK does it automatically.
await xray.send(
new PutTraceSegmentsCommand({
TraceSegmentDocuments: [JSON.stringify(segment)],
})
);
// Return the Claude response.
return {
statusCode: 200,
body: claudeResult,
};
} catch (err) {
span.recordException(err as Error);
span.setStatus({ code: 2, message: (err as Error).message }); // 2 = ERROR
throw err;
} finally {
// End the span – `startActiveSpan` does this automatically,
// but we call it explicitly for clarity.
span.end();
}
});
};
Key takeaway: The service name (
claude-agent-service) you set inotel-config.tsmust be exactly the same string you later see in the Application Signals UI; otherwise CloudWatch will label the trace as “Unidentified”.
Sending Custom EMF Metrics from Your Lambda
Why custom metrics help – CloudWatch already records the Lambda’s duration, memory usage, and error count. For an AI agent you often care about tokens generated or prompt length. EMF lets you embed those numbers in a log line; CloudWatch extracts them as first‑class metrics without an extra API call.
Minimal EMF example
// emf-helper.ts
/**
* Writes an EMF (Embedded Metric Format) log line.
* EMF is a JSON structure that CloudWatch parses into a metric.
*
* @param metricName - The name CloudWatch will show (e.g., TokenCount).
* @param value - Numeric value to record.
* @param namespace - Custom namespace to keep your metrics separate.
*/
export function emitEmfMetric(metricName: string, value: number, namespace = 'MyAI/ClaudeAgent') {
const emf = {
_aws: {
Timestamp: new Date(),
Namespace: namespace,
},
// The metric name becomes a dimension when CloudWatch ingests it.
[metricName]: value,
};
// Logging the JSON string is enough – CloudWatch extracts it.
console.log(JSON.stringify(emf));
}
Use it inside the Lambda after you receive Claude’s reply:
import { emitEmfMetric } from './emf-helper';
// ...
const tokenCount = JSON.parse(claudeResult).usage?.outputTokens ?? 0;
emitEmfMetric('OutputTokenCount', tokenCount);
In plain English: Think of EMF as a “sticky note” you attach to a log line. CloudWatch reads the note and turns it into a metric you can chart, all without an extra network hop.
Gotchas with EMF
| Gotcha | Impact | Fix |
|---|---|---|
| Log Insights scans every log line, costing $0.005 per GB. | High volume agents can become pricey. | Set a short retention (e.g., 7 days) and filter out noisy logs. |
| Default log retention is Never Expire. | Logs accumulate forever, inflating storage costs. | Use a lifecycle rule or configure logGroup retention in CDK/SAM. |
| 1‑second metric resolution costs 3× a 1‑minute metric. | Real‑time dashboards can become expensive. | Keep high‑resolution metrics only for the most critical KPIs. |
| Missing data in alarms can trigger false alerts during deployments. | You might receive unnecessary pages. | Use “Treat missing data as ignore” on CloudWatch alarms. |
Cross‑account observations need an IAM policy that grants cloudwatch:PutMetricData and xray:PutTraceSegments. |
Traces disappear from the console. | Add an ObservabilityAccess policy to the target account. |
Viewing Traces and Signals in the CloudWatch Console
Why you need the console view – After instrumentation, the real proof is that you can open the AWS console, pick the correct service name, and instantly see a flame‑graph of Claude’s request, plus any custom EMF metrics you emitted.
Steps to locate your traces
- Open CloudWatch → Application Signals.
- Choose the Service dropdown and select
claude-agent-service. - Click Traces – you’ll see a list of recent request IDs.
- Click a trace to view the span timeline. Each span shows:
- Name (e.g.,
lambda.handler,InvokeModelCommand) - Duration (ms)
- Attributes (like
modelIdortokenCount)
- Name (e.g.,
If you only see “Unidentified” traces, double‑check the service.name you set in the OTLP exporter.
Tip: The console automatically correlates EMF metrics with the trace that generated them, so you can see token counts right next to the span that produced them.
Quick sanity check with the AWS CLI
You can also verify that the OTLP exporter is sending data:
aws cloudwatch get-metric-statistics \
--namespace MyAI/ClaudeAgent \
--metric-name OutputTokenCount \
--start-time $(date -u -d '5 minutes ago' +%Y-%m-%dT%H:%M:%SZ) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
--period 60 \
--statistics Average
If the CLI returns a non‑empty result, your EMF metric is landing correctly.
Comparing Application Signals to Datadog APM
Why a comparison helps – Many teams already use Datadog for APM and wonder if moving to native AWS observability loses features. Below is a side‑by‑side view of the most common concerns.
| Feature | CloudWatch Application Signals | Datadog APM |
|---|---|---|
| Trace depth | Captures every span you create; you control granularity. | Similar depth, but offers auto‑instrumentation for many frameworks out of the box. |
| Custom metric integration | EMF lets you embed metrics directly in logs; no separate API required. | Requires dogstatsd or the Datadog API for custom metrics. |
| Pricing model | Pay for ingest (per GB) + metric resolution. No per‑trace fee. | Charges per host‑hour + per‑trace‑unit; can become expensive at scale. |
| Dashboarding | Built‑in dashboards for latency, error rate, and custom EMF metrics. | Rich, highly customizable dashboards; more widgets. |
| Cold‑start impact | Adding the OpenTelemetry SDK adds ~30 ms cold start (negligible). | Datadog’s Lambda layer can add 50‑100 ms if not tuned. |
| Cross‑account view | Requires an ObservabilityAccess policy, but works natively. | Needs an external organization set‑up; extra steps. |
| Vendor lock‑in | Fully AWS; no third‑party agent to maintain. | Multi‑cloud visibility, but adds a separate service to manage. |
In plain English: If your stack already lives in AWS and you’re mainly interested in tracing AI agents, Application Signals gives you most of what Datadog offers without the extra per‑trace bill.
The Takeaway
Key points to remember
- Application Signals is AWS’s native way to see every span, log, and metric from a Lambda that runs an AI model.
-
Set
resource.service.nameon the OTLP exporter to the exact name you’ll select in the console; otherwise traces go to “Unidentified”. -
EMF metrics let you add custom numbers (like token counts) without a separate
PutMetricDatacall; just log a JSON line. - X‑Ray trace IDs can be propagated manually to make sure OpenTelemetry and X‑Ray data appear under the same service view.
- Watch out for cost traps – log scanning, high‑resolution metrics, and default log retention can add up quickly.
- Compared to Datadog, Application Signals provides comparable depth with a simpler pricing model for AWS‑centric workloads.
By following the minimal TypeScript example above, you can instrument a Claude‑powered Lambda, ship traces and custom metrics to CloudWatch, and start debugging AI‑agent behavior directly from the AWS console. Happy tracing!
Transparency notice
This article was written with the help of an AI system — Groq (GPT OSS 120B).
Published: 2026-12-01 · Primary focus: CloudWatch
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)