Observability For Serverless

Comprehensive guide for observability for serverless covering essential concepts, practical examples, and production best practices.

Serverless architectures—where functions execute in response to events, managed by a cloud provider—introduce new challenges to observability: ephemeral execution, distributed state, and execution context that spans multiple services with no fixed host. Observability for serverless is not just monitoring, but the ability to understand what happened, why it happened, and how to fix it across a dynamic, multi-layered environment. It matters when a function fails silently under load, a downstream service returns unexpected data, or a cold start degrades end-user experience. This page details how to achieve observability across serverless workloads using real, standard tools and patterns.

Understanding Function Execution

To observe a serverless function, you must capture what happens from invocation to completion. The core is the function’s execution context, which includes logs, metrics, and traces. The first task is to ensure that every function emits meaningful logs in a consistent format.

Each function invocation must emit structured logs using JSON. The log entry must include at least the function name, invocation ID, start and end timestamps, and any error details. A typical entry in a cloud function platform looks like:

{
  "function": "process-user-signup",
  "invocationId": "a1b2c3d4-e5f6-7890-g1h2-i3j4k5l6m7n8",
  "timestamp": "2024-05-04T12:34:56.789Z",
  "level": "info",
  "message": "User registration completed",
  "userId": "u987654321",
  "durationMs": 142,
  "metadata": {
    "eventSource": "s3",
    "eventVersion": "1.0",
    "trigger": "new-user-upload"
  }
}

Logs should be streamed to a centralized system—such as Elasticsearch, Fluentd, or CloudWatch Logs—and indexed by invocationId and function. Use jq to filter and analyze logs:

jq -r '.function == "process-user-signup" and .level == "error" | .message' \
   < /var/log/functions.log

The most common failure is missing invocationId in logs. When logs are not tied to an invocation, it becomes impossible to correlate logs across services or reconstruct the flow of a single execution.

Correlating Across Services

In serverless, a single user request may trigger multiple functions across different services, each with its own log stream. To understand a complete request flow, you must propagate context across these boundaries.

The standard pattern is distributed context propagation using a header, typically traceparent, which follows the W3C Trace Context specification. A function must extract the context from incoming events and inject it into outgoing calls.

When a function receives an HTTP request, it parses the traceparent header:

traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01

The traceparent field contains:

The function then creates a new traceparent for any downstream call and adds it to outgoing HTTP headers:

traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
tracestate: otel.trace_id=0af7651916cd43dd8448eb211c80319c,ot.temp=22

This context is propagated through all services: from API Gateway to Lambda, from Lambda to DynamoDB, from Lambda to SQS, and back.

The key failure mode is context loss: a function receives an event but fails to extract or inject traceparent. This often happens when the event source does not include headers (e.g., S3 event triggers) or when the function framework does not parse traceparent automatically.

To detect context loss, use curl to simulate an incoming request with traceparent:

curl -X POST https://api.example.com/signup \
  -H "traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice", "email": "[email protected]"}'

A missing traceparent leads to fragmented traces, making it hard to correlate logs across services.

Measuring Performance and Latency

Serverless functions exhibit variable performance due to cold starts, concurrency limits, and resource allocation. Observability must track execution duration, memory usage, and invocation rate.

Each function should emit metrics in a standard format—typically OpenTelemetry or Prometheus. The core metrics are:

These metrics are collected using a standard tooling stack. A Lambda function can emit metrics via CloudWatch using the PutMetricData API:

{
  "Namespace": "Serverless/Functions",
  "MetricData": [
    {
      "MetricName": "DurationMs",
      "Dimensions": [
        { "Name": "FunctionName", "Value": "process-user-signup" }
      ],
      "Value": 142.3,
      "Unit": "Milliseconds"
    },
    {
      "MetricName": "ColdStart",
      "Dimensions": [
        { "Name": "FunctionName", "Value": "process-user-signup" }
      ],
      "Value": 1,
      "Unit": "Count"
    }
  ]
}

The PutMetricData call is made using curl or a simple HTTP client:

curl -X POST https://monitoring.us-east-1.amazonaws.com \
  -H "Content-Type: application/x-amz-json-1.4" \
  -H "X-Amz-Target: CloudWatch_20100801.PutMetricData" \
  -d '{
    "Namespace": "Serverless/Functions",
    "MetricData": [
      {
        "MetricName": "DurationMs",
        "Dimensions": [
          { "Name": "FunctionName", "Value": "process-user-signup" }
        ],
        "Value": 142.3,
        "Unit": "Milliseconds"
      }
    ]
  }'

The most common mistake is over-aggregating metrics: sending one metric per invocation but not batching them. A function that emits 1000 metrics per minute becomes a bottleneck when the metric API is slow.

To reduce cost and latency, batch metrics using a buffer. A standard approach is to use a simple in-memory queue in the function:

import json
import boto3
from collections import deque

client = boto3.client("cloudwatch")

class MetricBuffer:
    def __init__(self, max_size=100):
        self.buffer = deque(maxlen=max_size)
        self.namespace = "Serverless/Functions"

    def add(self, name, value, dimensions=None):
        entry = {
            "MetricName": name,
            "Value": value,
            "Unit": "Milliseconds",
            "Dimensions": dimensions or []
        }
        self.buffer.append(entry)

    def flush(self):
        if not self.buffer:
            return
        response = client.put_metric_data(
            Namespace=self.namespace,
            MetricData=list(self.buffer)
        )
        return response


buffer = MetricBuffer()

def handler(event, context):
    start = context.aws_request_id
    buffer.add("DurationMs", context.get_remaining_time_in_millis(), [
        {"Name": "FunctionName", "Value": context.function_name}
    ])
    buffer.add("ColdStart", 1 if context.get_remaining_time_in_millis() > 1000 else 0, [
        {"Name": "FunctionName", "Value": context.function_name}
    ])
    # ... processing ...
    buffer.flush()

Tracing Function Flows

Distributed tracing is essential for understanding how functions interact. Traces should capture the full lifecycle of a request: from entry point, through function execution, to downstream calls.

A trace consists of spans, each representing a unit of work. A function invocation is a span. Each call to a service (e.g., DynamoDB, SQS, HTTP) is another span.

Spans must include:

A typical span in JSON:

{
  "traceId": "0af7651916cd43dd8448eb211c80319c",
  "spanId": "b7ad6b7169203331",
  "parentId": "a1b2c3d4e5f67890",
  "name": "process-user-signup",
  "startTime": "2024-05-04T12:34:56.789000Z",
  "duration": 142300,
  "attributes": {
    "function.name": "process-user-signup",
    "user.id": "u987654321",
    "event.type": "s3-upload"
  },
  "events": [
    {
      "name": "function.start",
      "time": "2024-05-04T12:34:56.789000Z"
    },
    {
      "name": "dynamodb.query",
      "time": "2024-05-04T12:34:56.931000Z",
      "attributes": {
        "table": "users",
        "key": "u987654321"
      }
    }
  ]
}

To emit traces, use OpenTelemetry SDKs. A Python function using opentelemetry-sdk:

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)

exporter = OTLPSpanExporter(endpoint="http://jaeger-collector:4317")
processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(processor)

def handler(event, context):
    with tracer.start_as_current_span("process-user-signup") as span:
        span.set_attribute("user.id", event["userId"])
        span.set_attribute("event.type", event["eventType"])
        # ... processing ...
        span.add_event("user.created", { "userId": event["userId"] })

The most subtle failure is missing span boundaries: a function starts a span but forgets to close it, or spans are not properly nested. A span that starts and ends but is not properly linked to the parent span leads to incomplete traces.

Detecting and Alerting on Issues

Once logs, metrics, and traces are available, the next step is detecting issues and alerting on them.

Alerts must be based on thresholds and patterns derived from real behavior. Common alert types include:

Use curl and jq to extract and analyze data from a metric store:

# Get 95th percentile duration over last 5 minutes
curl -X POST https://api.example.com/queries \
  -H "Content-Type: application/json" \
  -d '{
    "query": "avg by(function) (rate(function.duration_ms[5m]))",
    "start": "2024-05-04T12:30:00Z",
    "end": "2024-05-04T12:35:00Z"
  }' \
  | jq -r '.result[0].value[] | select(.function == "process-user-signup") | .value'

Alerts should be configured to trigger on both absolute and relative thresholds. A function should alert when:

Alerts must include links to logs, traces, and metrics, all linked by invocationId and traceId. Use jq to build alert messages:

{
  "title": "High latency in process-user-signup",
  "body": "95th percentile duration is 240ms (threshold: 200ms). Last 5 minutes: 1234 invocations.",
  "links": [
    {
      "label": "View logs",
      "url": "https://logs.example.com/search?function=process-user-signup&from=2024-05-04T12:30:00Z&to=2024-05-04T12:35:00Z"
    },
    {
      "label": "View trace",
      "url": "https://jaeger.example.com/trace?traceId=0af7651916cd43dd8448eb211c80319c"
    }
  ]
}

Common Failure Modes

These patterns are essential for observability in serverless. Mastering them ensures that teams can understand, debug, and optimize their serverless applications with confidence.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.