Tracing & Performance

AWS Lambda Error Tracking

Set up AWS Lambda error monitoring with LightTrace in minutes. Get full stack traces, distributed tracing, and alerting across your serverless functions.

AWS Lambda stripped away server management, but it didn't strip away errors. Cold starts, timeout failures, out-of-memory crashes, and permission denials still happen—they just happen inside a managed black box. CloudWatch logs will show you the raw event, but extracting signal from noise requires spending hours grepping through thousands of unstructured lines. If you're running more than a handful of Lambda functions in production, AWS Lambda error monitoring setup needs to be systematic, and CloudWatch alone won't cut it.

LightTrace captures every error across your Lambda fleet—with full stack traces, execution context, affected users, and breadcrumbs of what happened before the crash. Because LightTrace speaks the Sentry protocol, any Sentry SDK (Node.js, Python, Java, Go, Rust, and more) points at LightTrace with a single dsn change. No rewrite. No new SDK to learn. Your Lambda errors land in a dashboard built for fast investigation, grouped by issue fingerprint, with one-click links to your GitHub source.

Why CloudWatch Logs Aren't Enough for Lambda Errors

CloudWatch is a log aggregator, not an error tracker. Every Lambda invocation writes to CloudWatch, and in a high-traffic function, that's thousands of log lines per minute. When an error happens, you see a stack trace buried in the noise—and it's unstructured. Searching for a specific error class requires regex skills. Counting occurrences of a particular TypeError requires running custom CloudWatch Insights queries. Understanding which user hit the error, what payload they sent, or what Lambda layers were warm requires piecing together multiple log groups and sifting through timestamps.

CloudWatch Logs charges by the gigabyte ingested AND by query cost. High-volume Lambda functions quickly rack up bills, and you're paying for every log line whether you need it or not.

Worse, CloudWatch gives you no correlation across services. If your Lambda calls an RPC backend, a database, or another async function, CloudWatch shows you only the Lambda logs. You can't see the full picture—whether the error originated in the Lambda, in the downstream service, or somewhere in the network between them.

Common Lambda Error Patterns You Need to Catch

Lambda errors fall into distinct categories, and you need visibility into each:

Cold Start Failures occur when Lambda container initialization fails—a dependency won't download, a credential provider times out, or a configuration file is missing. The function never even starts executing user code. These errors spike shortly after a deployment or during traffic spikes, and they're invisible to application-level logging because there's no runtime to log from.

Timeout and Memory Errors happen when a function exceeds its configured time limit (default 3 seconds) or memory ceiling. In CloudWatch, you see a generic message and a RequestId; you don't automatically know which line of code was executing or what state the function was in.

Permission and Authorization Errors are classic Lambda headaches—an IAM role is missing a permission to read from an S3 bucket, access Secrets Manager, or invoke downstream services. Your code tries to execute, hits the denied action, and crashes. These need immediate alerting because they often affect entire deployments.

Dependency and Import Errors happen when a Lambda layer is misconfigured, a package version is missing, or a native binary doesn't match the Lambda architecture. These are deterministic—every invocation fails the same way—so you need to detect them fast and rollback.

Setting Up AWS Lambda Error Monitoring with Sentry SDK

Because LightTrace speaks Sentry protocol, integrating Lambda is a matter of adding the Sentry SDK for your runtime and pointing it at LightTrace. Here's a Node.js example:

import * as Sentry from "@sentry/aws-lambda";
import { APIGatewayProxyHandler } from "aws-lambda";

Sentry.init({
  dsn: "https://<YOUR_KEY>@light-trace.robomiri.com/1",
  environment: "production",
  tracesSampleRate: 0.1, // capture 10% of transactions
});

const handler: APIGatewayProxyHandler = async (event, context) => {
  // Bind context for distributed tracing
  return Sentry.wrapHandler(async () => {
    const userId = event.queryStringParameters?.userId;
    
    try {
      const result = await processOrder(userId);
      return {
        statusCode: 200,
        body: JSON.stringify(result),
      };
    } catch (error) {
      Sentry.captureException(error, {
        tags: { function: "processOrder", userId },
      });
      throw error; // Re-throw so Lambda runtime also logs
    }
  })(event, context);
};

export { handler };

For Python, the setup is similarly minimal:

import sentry_sdk
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration
from sentry_sdk.integrations.sqlalchemy import SqlAlchemyIntegration

sentry_sdk.init(
    dsn="https://<YOUR_KEY>@light-trace.robomiri.com/1",
    integrations=[AwsLambdaIntegration(), SqlAlchemyIntegration()],
    environment="production",
    traces_sample_rate=0.1,
)

def handler(event, context):
    try:
        user_id = event.get("userId")
        result = process_order(user_id)
        return {"statusCode": 200, "body": result}
    except Exception as e:
        sentry_sdk.capture_exception(e)
        raise

Include environment, release, and service tags in your init config. This lets you filter errors by environment in the dashboard and correlate errors across your Lambda functions and other services.

The Sentry SDK handles cold start detection automatically—if your Lambda initializer throws, the SDK captures it and sends it to LightTrace. You don't need to wrap your entire handler; wrapHandler() (Node.js) or the decorator (Python) takes care of context binding and automatic error reporting.

Distributed Tracing Across Lambda and Downstream Services

Lambda functions rarely work in isolation. Your function calls RPC services, databases, or other Lambdas. A timeout error might originate in your function, but it could be caused by a slow downstream database query or a cascading failure in a dependent service.

Distributed tracing lets you see the full request journey across all services. Every span—your Lambda execution, the database call, the RPC to another service—carries a trace ID. When you click an error in LightTrace, you see the entire span waterfall, so you know exactly where latency was added or where the failure happened.

To enable tracing across services:

  1. Configure trace sampling in your Sentry init: tracesSampleRate: 0.1 captures 10% of all transactions. For high-traffic Lambdas, 1-5% is usually enough to catch errors and slow transactions without overwhelming your quota.

  2. Integrate with database drivers and HTTP clients using Sentry's auto-instrumentation integrations. For Node.js, integrations like HttpIntegration and PrismaIntegration automatically capture outbound calls.

  3. Propagate trace context by including the traceparent header in any HTTP calls your Lambda makes to other services. The Sentry SDK does this automatically for instrumented clients.

  4. Link async invocations by passing the trace ID to any child Lambdas or async jobs. Capture it with Sentry.getCurrentHub().getTraceContext() and include it in your event payload.

If your Lambda invokes EventBridge, SQS, or SNS, the trace context gets lost unless you explicitly propagate it. Attach the current trace ID to the message body or a custom header so the downstream Lambda can resume the trace.

Monitoring Lambda Performance and Cold Starts

Errors are only half the story. AWS Lambda error monitoring setup also means understanding performance. Every function has a cold start penalty—time spent initializing the container before your code runs. In a low-traffic function, cold starts are rare; in a function that scales from zero to hundreds of concurrent instances, cold starts add up.

LightTrace captures performance metrics automatically:

  • Transaction duration broken down by function name and Lambda environment.
  • Cold start counts and duration—Sentry detects when a container is fresh and flags those transactions.
  • P50, P75, P95, P99 latency so you can see if a recent deployment made your function slower.
  • Throughput to detect traffic anomalies or failed deployments.

Set traces_sample_rate conservatively (5-10% for production Lambda) to avoid flooding your quota, but keep it consistent so your performance metrics are representative.

Sentry.init({
  dsn: "https://<YOUR_KEY>@light-trace.robomiri.com/1",
  environment: "production",
  tracesSampleRate: process.env.NODE_ENV === "production" ? 0.05 : 1.0,
  // Capture 5% in production, 100% in dev for testing
  integrations: [
    new Sentry.Integrations.AwsLambda(),
    new Sentry.Integrations.Http({ tracing: true }),
  ],
});

Alerting on Lambda Errors and Anomalies

Errors in production need immediate attention. LightTrace alert rules let you define thresholds and get notified by email:

  • New issue alert: Fire when a never-before-seen error appears (e.g., a new TypeError after a deployment).
  • Event-frequency alert: Fire when an existing error crosses a threshold (e.g., more than 10 occurrences in 1 hour).

Set up rules for critical paths—for example, alert immediately if your payment-processing Lambda logs any error, but alert only if your logging Lambda errors exceed 100 per minute.

In the LightTrace dashboard, create an alert by clicking an issue and selecting "Create Alert Rule." Set thresholds based on your SLA. For high-traffic functions, even a 1% error rate is worth knowing about; for batch jobs, you might tolerate higher rates.

Bringing It Together: A Complete Example

Here's a realistic Lambda function—an order processor that calls a payment service and stores results in a database:

import * as Sentry from "@sentry/aws-lambda";
import { PrismaClient } from "@prisma/client";
import axios from "axios";

Sentry.init({
  dsn: "https://<YOUR_KEY>@light-trace.robomiri.com/1",
  environment: process.env.STAGE || "dev",
  release: process.env.RELEASE_ID,
  integrations: [
    new Sentry.Integrations.AwsLambda(),
    new Sentry.Integrations.Http({ tracing: true }),
  ],
  tracesSampleRate: 0.1,
  beforeSend(event) {
    // Redact sensitive data
    if (event.request?.url) {
      event.request.url = event.request.url.replace(/api_key=[^&]+/g, "api_key=REDACTED");
    }
    return event;
  },
});

const prisma = new PrismaClient();

async function handler(event) {
  return Sentry.wrapHandler(async () => {
    const { orderId, userId, amount } = event;

    Sentry.setTag("orderId", orderId);
    Sentry.setContext("user", { id: userId });

    try {
      // Call payment service
      const payment = await axios.post("https://payment-api.example.com/charge", {
        userId,
        amount,
      });

      // Store order
      const order = await prisma.order.create({
        data: { orderId, userId, amount, paymentId: payment.data.id, status: "completed" },
      });

      return { statusCode: 200, body: JSON.stringify(order) };
    } catch (error) {
      Sentry.captureException(error, {
        tags: { function: "processOrder" },
        level: error.response?.status >= 500 ? "error" : "warning",
      });
      throw error;
    }
  })(event);
}

export { handler };

The Sentry SDK automatically captures:

  • Latency of the payment API call (traced).
  • Latency of the Prisma database insert (traced).
  • Any exception, with the orderId and userId attached.
  • Cold start duration (if the container was freshly initialized).

In LightTrace, you filter by orderId, see the full trace waterfall, and know whether the error was in your code, the payment service, or the database.

Use beforeSend to redact sensitive fields before they hit LightTrace. API keys, credit card tokens, and personally identifiable information should never leave your function.

Getting Started

AWS Lambda error monitoring doesn't require complex setup or a separate observability platform. Add the Sentry SDK (which you may already be using elsewhere), point it at LightTrace, and errors flow in automatically. You get full stack traces, distributed tracing across services, performance metrics, and alerting—all from a single dashboard built for speed.

Start tracking errors in minutes

Start tracking Lambda errors today with LightTrace. Sign up free, set your dsn, and get visibility into your serverless fleet in minutes. Your team will thank you when the next production error lands in your inbox with a direct link to the failing code.

Fix your next production error faster

Point any Sentry SDK at LightTrace — free up to 5,000 events/month.