---
title: "What I Learned Fixing Observability in a Distributed System with Thousands of Users"
canonical: https://cesarfelipe.dev/articles/what-i-learned-fixing-observability-in-a-distributed-system/
published: 2025-12-18
updated: 2026-12-05
author: César Felipe
---

**TL;DR**

- With thousands of concurrent Lambda invocations, CloudWatch scatters one user's requests across hundreds of log streams, and debugging one user takes minutes.
- We treated logs as data: every entry is a JSON document with context (tenantId, requestId) and metadata (userId).
- LogLayer emits them through a per-invocation child logger, so context never leaks into the next request on a warm Lambda.
- Datadog indexes the JSON as is, so one query finds every log for a user: near-APM debugging without the full APM cost.

![Structured logging pipeline: a Lambda creates a per-invocation LogLayer child logger with tenantId and requestId as context, so each log entry is a JSON document; Datadog parses the nested context and metadata fields as searchable attributes, and one query such as @metadata.userId:123456 returns every log for that user across all functions](https://cesarfelipe.dev/_astro/structured-logging-pipeline.Cmgd7V_r.svg)

For a while, logging worked fine.

We’d deploy a few Lambdas, send everything to CloudWatch, and scroll through logs like good little operators.

Then the product grew.

And so did the pain.

## The problem: CloudWatch doesn’t scale with humans

CloudWatch logging works, until it doesn’t.

Once you have thousands of concurrent Lambda invocations, you have hundreds of log streams.

A log stream doesn’t map to a request. It maps to an execution environment: every time Lambda spins up a new environment to handle concurrency, that environment gets its own stream, and every invocation it serves while warm is appended to it. One stream interleaves many users. One user’s requests land on whatever environments happened to be free, so they end up spread across many streams.

So debugging a user issue meant:

1.  Searching for the log group.
2.  Guessing the right stream.
3.  Scrolling, copying request IDs, and hoping you didn’t miss context.

What used to take seconds turned into minutes, multiplied by every engineer on call.

We didn’t have an observability problem.

We had a context problem.

## The realization: logs are data, not text

Distributed systems fail in distributed ways.

And our logs were plain text: one message, one line, zero structure. CloudWatch can’t search for a field that was never written as a field.

But logs, when structured, become searchable telemetry.

So we redefined our rule:

> *Every log entry should be a JSON document, not a string.*

That was the turning point.

## The solution: structured logs with LogLayer and Datadog

We moved our logging pipeline to Datadog, but the secret sauce was LogLayer, a small, clever library that enforces structured output and metadata context.

Here’s what it looks like in a Lambda:

```ts
import { LogLayer, ConsoleTransport } from "loglayer";

export const logger = new LogLayer({
  transport: new ConsoleTransport({
    logger: console,
    stringify: true,
    dateField: "timestamp",
    levelField: "level",
    messageField: "message",
  }),
  contextFieldName: "context",
  metadataFieldName: "metadata",
});
```

`levelField` looks optional. It isn’t. Without a level in the JSON, Datadog has nothing to map to the log status, and your errors show up as `info`.

Instead of writing:

```ts
console.log("User created", userId);
```

We now log structured events, from a logger that belongs to the invocation:

```ts
import type { Context } from "aws-lambda";
import { logger } from "./logger";

export async function handler(event: CreateUserEvent, lambdaContext: Context) {
  const log = logger.child().withContext({
    tenantId: event.tenantId,
    requestId: lambdaContext.awsRequestId,
  });

  const userId = await createUser(event, log);

  log.withMetadata({ userId }).info("User created");
}
```

Context is what belongs to the whole request (tenant, request ID). Metadata is what belongs to one event (the user that was just created). LogLayer keeps them in separate fields, which matters later when you write queries.

Each log entry looks like this:

```json
{
  "timestamp": "2025-11-09T20:17:12Z",
  "level": "info",
  "message": "User created",
  "context": {
    "tenantId": "alpha-co",
    "requestId": "req-9fbd23"
  },
  "metadata": {
    "userId": "123456"
  }
}
```

Every log emitted through `log` during that invocation carries the same context. Nobody has to remember to pass `tenantId` to each call.

## The gotcha: context on a warm Lambda

The tempting version is to call `logger.withContext({ tenantId, requestId })` on the module-level logger at the top of the handler. It works in local tests. It lies in production.

Module scope survives between invocations. When Lambda reuses a warm execution environment, the logger from the previous invocation is still there, with the previous invocation’s context still attached. Overwrite `requestId` and `tenantId` every time and you’re fine, until one code path adds a key the next request doesn’t set. Then request B’s logs carry request A’s `userId`, and you are debugging the wrong customer with total confidence.

There are two safe patterns:

-   **A child logger per invocation**, as above. `child()` copies the parent’s context at creation, and the parent never gets touched, so there is nothing to clean up.
-   **Reset at the start of every invocation**, with `logger.clearContext()` before `withContext(...)`. It works, but it depends on every handler remembering to do it, and the one that forgets is the one you’ll be debugging.

I prefer the child logger. It makes the lifetime of the context match the lifetime of the request, and it fails safe.

The cost is that `log` has to reach the code that logs. We pass it explicitly into services. If threading it through deep call stacks gets painful, Node’s `AsyncLocalStorage` can hold the per-invocation logger instead, but I’d reach for that only when the explicit version actually hurts.

## The result: one query finds every log for a user

In Datadog, logs became a queryable data layer.

I can now search:

```text
@metadata.userId:123456
```

and instantly see every log related to that user, across all services, functions, and invocations.

I can also query by tenant or request ID, with `@context.tenantId:alpha-co` or `@context.requestId:req-9fbd23`.

Everything is consistent. Everything is centralized.

No more log-stream roulette.

No more clicking through twenty functions to trace one error.

## Under the hood: how Datadog reads nested fields

Datadog parses JSON logs on its own, nested objects included. Every field becomes an attribute addressed by its full path, so the entry above is searchable as it is:

```text
@metadata.userId:123456
@context.tenantId:alpha-co
@context.requestId:req-9fbd23
```

The catch is that every query and dashboard is now tied to how LogLayer nests fields. Move `userId` from metadata to context one day and every saved query on `@metadata.userId` silently returns nothing. The JSON layout is part of the contract: decide once where each key lives, and keep it there.

Searching doesn’t require a facet. Aggregating does: to filter from the sidebar, group by tenant or count errors per user, you need a facet on that path.

This brought trace-like debugging without the full APM cost. If you do run the Datadog tracer, the same structured logs can carry trace IDs and link straight to APM traces, but the requestId alone already got us most of the way.

## How I’d do it today

-   **Decide the context keys before writing code.** `tenantId`, `requestId`, `userId`, and whatever your domain needs. Same names, same casing, in every service. A `tenant_id` in one function and a `tenantId` in another is two fields to Datadog.
-   **Create the logger per invocation.** Never mutate a module-level logger with request data.
-   **Always emit a level.** Status drives alerts, and an error logged as info never pages anyone.
-   **Keep context small and boring.** IDs, not payloads. Large objects inflate ingestion cost, and full request bodies are where PII sneaks in.
-   **Treat the log layout as a contract.** Queries, monitors and dashboards address `@context.*` and `@metadata.*` paths, so moving a key from one to the other breaks them without a single error.
-   **Watch the bill.** Datadog charges for ingesting and for indexing logs. Exclusion filters on noisy, low-value logs (health checks, `started` events) keep the useful ones affordable.
-   **Check what Lambda gives you for free.** Lambda can emit its own logs as JSON (the log format setting in its logging configuration), with the request ID included, which makes even the platform lines queryable.

## Lessons learned

-   Text logs are for developers. Structured logs are for systems.
-   Treat logs as telemetry, not breadcrumbs.
-   Context is your currency in distributed systems: never lose it, and never let it leak into the next request.
-   You can achieve near-APM visibility without instrumenting everything.
-   Good observability scales your *team*, not just your infra.

## Key takeaways

If you’re scaling a serverless or distributed app:

-   Stop printing strings.
-   Start emitting structured events.
-   Pass context like userId, tenantId, and requestId everywhere, through a logger created per invocation.
-   Remember that a log stream is an execution environment, not a request.
-   Query those fields in Datadog by their JSON path, and keep the layout stable.

Your logs will finally start working *for* you, not against you.

## References

-   Datadog Logs Guide — [https://docs.datadoghq.com/logs/](https://docs.datadoghq.com/logs/)
-   Datadog APM Tracing for Node.js — [https://docs.datadoghq.com/tracing/trace\_collection/automatic\_instrumentation/dd\_libraries/nodejs/](https://docs.datadoghq.com/tracing/trace_collection/automatic_instrumentation/dd_libraries/nodejs/)
-   Datadog Log Search Syntax — [https://docs.datadoghq.com/logs/explorer/search\_syntax/](https://docs.datadoghq.com/logs/explorer/search_syntax/)
-   LogLayer Documentation — [https://loglayer.dev/](https://loglayer.dev/)
-   AWS Lambda Logging Best Practices — [https://docs.aws.amazon.com/lambda/latest/dg/nodejs-logging.html](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-logging.html)
