Home / Articles

Debug Lambda AI Agents with EMF Metrics and X-Ray

How to time Claude tool calls on Lambda, emit CloudWatch EMF metrics, and use X-Ray so a slow agent stops being a five-second mystery.

Publisher: REACTAPP.TOP9 min read2005 words

This article is published in English.

Sources: AI Agent Observability with AWS CloudWatch EMF and X-Ray

Agents that call APIs, look things up, run tools, and make several decisions before they answer are awkward to debug. The error at the end rarely names the step that broke. The model round may have been slow. An outside API may have timed out. The tool may have handed back a payload the model did not expect. Or the next model call may have failed after the tool had already returned.

A Lambda log that only shows how long the function ran will not sort those cases quickly.

Record each step in the loop that can stall or fail. On a Node.js agent, two AWS signals split the work. EMF, CloudWatch's format for metrics tucked inside a log event, gives you numbers you can chart. X-Ray shows the path of one request.

Why an agent is hard to debug

Take an agent that reaches Claude through Amazon Bedrock and calls external tools while it answers a question.

The loop usually has four beats:

  1. Plan. The model chooses a tool.
  2. Act. Your code runs that call.
  3. Observe. The tool result is sent back to the model.
  4. Respond. The model writes the answer, or it asks for another tool.

Any beat can add delay, and any beat can fail.

Say the reply takes five seconds. If you only have the Lambda report, you know the function took five seconds. You still cannot tell whether the wait sat in the model call, in an external API, or in the same tool being invoked again and again.

That is why you want three signals that answer different questions:

  • Logs describe what happened on that request.
  • Metrics show counts and how latency moves across many requests.
  • Traces point at the operation that was slow or that threw.

EMF is how you get the metrics out of the log stream. X-Ray is how you get the traces.

EMF turns a log line into a metric

Embedded Metric Format is a JSON log event that carries metric values inside it. CloudWatch Logs lifts those numbers out and stores them as CloudWatch metrics.

Lambda agents are a good fit. You already print to stdout, and the platform ships those lines onward. You skip a separate call to the metrics API for every sample.

For an agent, the first numbers worth emitting are:

  • How long one tool call took.
  • How many tool calls succeeded, and how many failed.
  • How long the model call took.
  • How many tools a single request used.
  • How long the full agent run lasted.

Record tool latency with one helper

Start with a small helper that prints a valid EMF event. The input is just the tool's name and the elapsed milliseconds.

interface ToolMetric {
  toolName: string;
  latencyMs: number;
}

emitToolLatency writes one JSON document. The _aws object is the EMF envelope: Timestamp is Date.now(), and CloudWatchMetrics describes the series. The namespace is AI/Agent. The dimension list is only ToolName. The metric name is ToolCallLatency and the unit is Milliseconds. Beside _aws, the same object sets ToolName and ToolCallLatency to the live values, which is what CloudWatch reads when it applies that definition.

export const emitToolLatency = ({
  toolName,
  latencyMs,
}: ToolMetric): void => {
  console.log(
    JSON.stringify({
      _aws: {
        Timestamp: Date.now(),
        CloudWatchMetrics: [
          {
            Namespace: "AI/Agent",
            Dimensions: [["ToolName"]],
            Metrics: [
              {
                Name: "ToolCallLatency",
                Unit: "Milliseconds",
              },
            ],
          },
        ],
      },
      ToolName: toolName,
      ToolCallLatency: latencyMs,
    }),
  );
};

Stamp the clock before the tool runs.

const startedAt = Date.now();

After it returns, pass the name and the delta into the helper. The sample calls callWeatherTool with "London". That function is assumed to be defined somewhere else.

const result = await callWeatherTool("London");emitToolLatency({
  toolName: "weather",
  latencyMs: Date.now() - startedAt,
});

Lambda prints that JSON to standard output. The logging path forwards the line to CloudWatch Logs, and CloudWatch extracts ToolCallLatency under the EMF rules. From there you can build a graph and an alarm.

This sample only fires when the call succeeds. If the tool throws, nothing is emitted. Around a real tool, use try, catch, and finally so you still publish a success sample or a failure sample, and a broken call stays visible.

EMF does not wipe the cost either. Ingesting logs, keeping them, and publishing custom metrics can all show up on the bill.

X-Ray when the chart only says slow

A metric tells you that something got worse. It usually does not show the exact hop inside the request that caused it. A distributed trace is what fills that gap.

AWS X-Ray stores a request as segments and subsegments. On a Lambda agent that is already instrumented, you can inspect outbound HTTP, the model call, and other activities your tracer knows how to wrap.

One trace can separate cases that look the same on a chart:

  • The Bedrock call was the slow one.
  • An external tool was the slow one.
  • Tools ran one after another.
  • The tool raised an exception while it ran.

Time the tool, then attach a real tracer

The wrapper below is plain TypeScript, with no tracing SDK imported. It clocks the work and writes a structured result. You can hang your own tracer on the same boundary later.

traceToolCall takes a ToolCallContext holding toolName, plus an async function, and it returns that function's value. It stores Date.now() first. If the function resolves, it logs tool_call_completed with durationMs and status set to "success", then returns the value. If the function throws, it logs the same event name with status set to "failure" and an errorType: error.name when the throw is an Error, otherwise "UnknownError". It then rethrows, so the caller still sees the exception.

interface ToolCallContext {
  toolName: string;
}
export const traceToolCall = async <T>(
  context: ToolCallContext,
  operation: () => Promise<T>,
): Promise<T> => {
  const startedAt = Date.now();
  try {
    const result = await operation();
    console.log(
      JSON.stringify({
        event: "tool_call_completed",
        toolName: context.toolName,
        durationMs: Date.now() - startedAt,
        status: "success",
      }),
    );
    return result;
  } catch (error) {
    console.error(
      JSON.stringify({
        event: "tool_call_completed",
        toolName: context.toolName,
        durationMs: Date.now() - startedAt,
        status: "failure",
        errorType:
          error instanceof Error
            ? error.name
            : "UnknownError",
      }),
    );
    throw error;
  }
};

Use it in place of a bare tool call. The weather lookup is still London.

const weather = await traceToolCall(
  { toolName: "weather" },
  () => callWeatherTool("London"),
);

Read the output for what it is. The wrapper writes a timing log. It does not open an X-Ray segment or a subsegment. Those appear only after you wire the operation through a supported X-Ray library or an OpenTelemetry tracer, and you pass context the way that library requires. A line that names the tool and the milliseconds is still worth having. It is a different artifact from a distributed trace. Setup for X-Ray is in the AWS X-Ray developer guide.

Use the chart, then open the trace

The payoff is using both signals in a fixed order.

Suppose the CloudWatch dashboard shows p95 for the weather tool climbing hard. Walk the incident like this:

  1. Open that dashboard.
  2. Mark the window where the latency rose.
  3. Pull a few slow requests out of the logs for that window.
  4. Open the matching trace, if one was recorded.
  5. Inspect the tool operation and the calls it made downstream.
  6. Decide whether your code was waiting, or an outside dependency was.

EMF is the picture across many requests. A trace is one request, step by step. Together they turn a vague slowdown into a sequence you can check.

Metrics worth keeping on a live agent

Start from a short list that answers an on-call question. The names below are the metrics. The second column is the question each one answers.

Metric Question it answers
ModelInvocationLatency Time spent inside a model call
ToolCallLatency Time spent inside one tool
ToolCallFailures Count of tool runs that failed
AgentExecutionDuration Time for the full agent loop
ToolCallsPerRequest Tool count on a single request

When the model API includes them, token counts and the status on the model response are worth storing too.

Do not attach high-cardinality ids to a CloudWatch metric. Request ids, user ids, and one-off trace ids are the usual mistakes. Every fresh combination of dimension values becomes another custom-metric time series, and the bill grows with that series.

Hold dimensions to a bounded set: the tool's name, the environment, or the kind of operation. Put per-request detail in a structured log, or on the trace, where it belongs.

Mistakes that hide the failure

JSON in the logs is not a span

Structured JSON, including an EMF event, does not create an X-Ray subsegment on its own. You need a tracer that hooks your runtime and forwards context.

Only the happy path gets a number

If you emit only after a tool returns cleanly, every throw drops out of the latency series and out of the success count. Write the failure outcome too.

The model call is invisible

Wrapping external tools and skipping the model leaves a hole in the loop. Time the model invocation on its own, separate from tool execution.

Too many dimension values

A unique value such as a request id multiplies custom metrics. Stay with low-cardinality dimensions.

Secrets and full prompts in the log

Skip the complete prompt, the full model reply, API credentials, and a sensitive tool payload unless you have a clear reason that has been approved. Prefer sanitized metadata and an error type.

The extra log lines still cost money

EMF removes the need for a separate publish call on each sample. CloudWatch Logs, custom metrics, trace ingest, and retention can still cost money. Watch the volume, and pick sampling plus a retention window that fit the workload.

What a Lambda agent should emit

A straightforward layout on AWS looks like a straight line: a request comes in, the Lambda agent runs, it calls a Bedrock model, a tool executes, and the model answers.

At every stage along that line:

  • Write a structured log that carries a correlation id.
  • Emit latency and the outcome through EMF.
  • Tie the instrumented steps together with a distributed trace.
  • Set CloudWatch dashboards and alarms on thresholds that match how the agent is supposed to run.
  • Leave private application data out of what you emit whenever you can.

If the app uses several Lambda functions, or it calls other services, pass tracing context across the boundaries your tracer supports. Otherwise you cannot join the related operations later.

You do not need a record of every event. You need enough reliable data to answer the question that shows up when a request fails.

Operate the agent like any other service

One user request can fan out into several model decisions, outside calls, and repeats of the same step. Without these signals, you are guessing.

EMF shows how the agent behaves across many runs. X-Ray shows the path of a single request.

Instrument the model call and the tools. Record both the runs that succeed and the runs that fail. Keep the telemetry bill in view. Then each important operation in the agent is something you can measure, trace, and see fail, the same way you would treat an ordinary production endpoint.