/blogs/how-modern-backends-are-debugged

← Back to blogs
Blog

How Modern Backends Are Debugged

Understand how modern backend teams use structured logging, metrics, distributed tracing, and production debugging with OpenTelemetry and modern observability tools.

·8 min read·

Building a Debuggable Backend: Logging, Monitoring, and Observability

Backend applications run in distributed environments. Requests travel through load balancers, API gateways, multiple microservices, databases, and external APIs. When a user reports an error, finding the exact point of failure requires more than just checking the server logs.

Logging, monitoring, and observability are not strict checklists. They exist on a spectrum. No system is 100% observable, and no team implements every possible metric. Instead, these practices represent a maturity model. Implementing them gives you the context needed to debug complex issues quickly and understand your system's behavior under load.

Logging

Logging is the practice of recording discrete events within your application lifecycle. It is the journal your backend maintains. When a user logs in, a database query executes, or an external API times out, you record the event with relevant metadata like the user ID, request ID, and latency.

Monitoring

Monitoring is the continuous tracking of your system's health and performance metrics. It provides near real-time data about your infrastructure and application state. You monitor CPU usage, memory consumption, active database connections, and request throughput.

Monitoring data is rarely true real-time. There is usually a 10 to 15-second delay in the aggregation pipeline. This delay is intentional; pushing metrics every single millisecond would overwhelm your monitoring infrastructure.

Observability

Observability is the ability to determine the internal state of your system by examining its external outputs. If monitoring tells you that a problem exists, observability tells you why it exists.

#Traditional Monitoring vs. Modern Observability

A decade ago, infrastructure teams relied heavily on traditional monitoring. You set up alerts in Grafana, and if CPU usage spiked or error rates crossed a threshold, you received a Slack notification.

The limitation of traditional monitoring is that it only alerts you to a symptom. It tells you the error rate is at 80%, but it does not tell you which endpoint is failing or why. You are left guessing.

Modern observability solves this by combining logs, metrics, and traces. When an alert fires, you do not just know that the system is failing; you can immediately drill down into the specific transaction that caused the failure.

#The Three Pillars in Action

A system is considered observable when it effectively implements three components. Here is how they work together during a production incident.

Rendering diagram...
  1. The Alert: Your monitoring system detects that the API error rate has exceeded 80% in the last five minutes. You receive a Slack notification.
  2. The Metrics: You open your dashboard and look at the metrics. You see a massive spike in 500 Internal Server Error responses on the /api/todos endpoint. You also check business metrics, like how many to-dos failed to create.
  3. The Logs: You filter the logs for that specific endpoint and time window. You find a JSON log entry showing a database connection timeout.
  4. The Trace: You click the trace ID attached to that log entry. The trace visualization shows the request passing through the middleware, hitting the service layer, and hanging for 30 seconds at the database query before timing out.

You now know exactly what failed, where it failed, and the context surrounding the failure.

#Logging Strategies

How you format and categorize your logs dictates how useful they are when you need to debug an issue.

Log Levels

Assigning a severity level to your logs allows you to filter out noise.

  • Debug: Highly detailed information, typically only useful during local development. Disable this in production to avoid overwhelming your log aggregator.
  • Info: General application events and successful operations. For example, logging that a new resource was created.
  • Warn: Events that are unexpected but not critical. For example, a user failing authentication due to an incorrect password. This is not a system error; it is just a user mistake.
  • Error: Operations that failed. Database query failures or validation errors fall into this category.
  • Fatal: Critical failures that cause the application to crash or shut down.

Structured vs. Unstructured Logging

In your local development environment, you want logs to be human-readable. Unstructured logging outputs plain text, often with colors and formatting, making it easy to scan your terminal.

In production, plain text is a liability. Log aggregation tools struggle to parse unstructured text to extract metadata like request IDs or user IDs.

Instead, use structured logging. This means outputting your logs as JSON objects.

>_ text
{
  "level": "error",
  "timestamp": "2026-06-30T10:00:00Z",
  "message": "Database query failed",
  "requestId": "req_8f7d6c5b",
  "userId": "user_123",
  "error": "connection timeout"
}

Structured logs can be easily parsed, indexed, and queried by tools like Datadog, New Relic, or the ELK stack.

#Instrumentation and Tracing in Practice

To make a system observable, you must instrument your code. Instrumentation is the practice of embedding measurement logic into your application to capture traces and metrics.

OpenTelemetry is the open standard for this. It provides a unified set of APIs and SDKs across all major programming languages, allowing you to collect traces and export them to any backend.

Let's look at how this works in a Node.js application using a proprietary tool like New Relic, which abstracts away the complexity of setting up an open-source stack.

The Middleware Layer

Tracing begins at the edge of your application. You implement a middleware that intercepts every incoming HTTP request.

>_ text
import newrelic from "newrelic";
import type { Request, Response, NextFunction } from "express";

export function enhancedTracingMiddleware(
  req: Request,
  res: Response,
  next: NextFunction
) {
  // Current transaction (automatically created by New Relic Express instrumentation)
  const transaction = newrelic.getTransaction();

  try {
    newrelic.addCustomAttributes({
      serviceName: process.env.SERVICE_NAME,
      environment: process.env.NODE_ENV,
      requestId: req.header("x-request-id"),
      userId: req.user?.id,
      tenantId: req.user?.tenantId,
      userAgent: req.get("user-agent"),
      ipAddress: req.ip,
      method: req.method,
      route: req.originalUrl,
    });

    // Optional: store transaction on request
    req.transaction = transaction;

    next();
  } finally {
    transaction.end();
  }
}

This middleware creates a transaction, attaches metadata, and passes the transaction down the request chain via the context.

The Service Layer

When the request reaches your business logic, you extract the transaction from the context. This allows you to add deeper, domain-specific attributes to the trace.

>_ text
import newrelic from "newrelic";

export class TodoService {
  constructor(private readonly repo: TodoRepository) {}

  async createTodo(req: CreateTodoRequest) {
    const transaction = newrelic.getTransaction();

    return newrelic.startSegment(
      "TodoService.createTodo",
      true,
      async () => {
        try {
          newrelic.addCustomAttributes({
            "todo.title": req.title,
            "todo.priority": req.priority,
          });

          logger.info(
            {
              title: req.title,
            },
            "initiating todo creation"
          );

          const todo = await this.repo.create(req);

          newrelic.addCustomAttributes({
            "operation.result": "success",
            "todo.id": todo.id,
          });

          logger.info(
            {
              id: todo.id,
              title: todo.title,
              categoryId: todo.categoryId,
            },
            "business event: todo created"
          );

          return todo;
        } catch (error) {
          newrelic.noticeError(error as Error);

          newrelic.addCustomAttributes({
            "operation.result": "error",
          });

          logger.error(
            {
              err: error,
            },
            "database operation failed"
          );

          throw error;
        } finally {
          transaction.end();
        }
      }
    );
  }
}

By passing the transaction through the context, the trace automatically links the HTTP request, the service logic, and the database operation into a single, continuous timeline.

#Visualizing the Data

Once your code is instrumented and logs are structured, the data flows into your observability platform. Here is what you actually look at when debugging.

Reading the Metrics

Metrics provide the aggregate numbers. You look at average transaction time, throughput, and error rates. If you are monitoring the Go runtime, you can also see garbage collection times and memory usage, which helps identify if your application is suffering from memory leaks or excessive CPU consumption.

Reading the Logs

When you click into a specific error from your metrics dashboard, you see the parsed JSON log. Because it is structured, the dashboard automatically extracts the fields. You can see the application name, the environment, the HTTP status code, the host IP, the log level, the exact error message, the HTTP method, the API route, the span ID, and the timestamp.

Reading the Traces

Clicking the trace ID opens a waterfall view of the request. You can see exactly how many milliseconds the database query took compared to the JSON serialization. If the request failed at the repository layer, the trace highlights that specific segment in red, showing you the exact function and line of code where the execution stopped.

#Choosing Your Tooling

You do not need to build your observability stack from scratch. You have two main paths.

The open-source route uses tools like Prometheus for metrics, Loki for logs, and Jaeger for traces, all tied together with Grafana dashboards. This gives you maximum control but requires significant infrastructure maintenance. You have to manage the storage, the retention policies, and the upgrades.

The proprietary route uses platforms like New Relic or Datadog. You install an SDK or an OpenTelemetry collector, and the platform handles the storage, indexing, and UI. This is often the better choice for smaller teams that want to spend their time writing application code rather than managing monitoring infrastructure.

Observability is a continuous effort and a collective responsibility. Developers must instrument the code and structure the logs, while infrastructure teams must ensure the collection pipelines and storage backends are reliable. You will never reach a state where your system is 100% observable. Instead, focus on instrumenting your critical paths, structuring your logs, and ensuring that when an alert fires, you have the context required to fix the problem.

1,321 words left