Comprehensive guide to apm best practices for production observability and monitoring systems.
APM (Application Performance Monitoring) is the practice of measuring and analysing the performance and availability of software services in production. It matters when users report slow responses, when services fail under load, or when you need to diagnose latency spikes across microservices. APM is not just about collecting metrics—it is about connecting traces, logs, and metrics to form a complete picture of how your system behaves under real conditions.
To build an effective APM system, instrument every service in your stack with distributed tracing. Begin by setting up a global trace context that propagates across network boundaries. Use HTTP headers to carry trace identifiers: traceparent for W3C Trace Context, baggage for contextual data, and tracestate for metadata.
GET /api/users/123 HTTP/1.1
Host: userservice.example.com
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e5686-00f0673205c4211d-01
baggage: user_id=123,session_id=abc456
The traceparent header contains version, trace ID, parent ID, and flags. When a service receives a request, it creates a new span and adds it to the current trace. The span must record the duration, operation name, and any relevant metadata.
In a Go service using OpenTelemetry, a typical span creation looks like:
func HandleUserRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) {
tracer := otel.Tracer("userservice")
ctx, span := tracer.Start(ctx, "HandleUserRequest")
defer span.End()
userID := r.URL.Query().Get("user_id")
span.SetAttributes(
attribute.String("user.id", userID),
attribute.String("http.method", r.Method),
)
// Process the request
user, err := fetchUserFromDatabase(ctx, userID)
if err != nil {
span.RecordError(err)
http.Error(w, "Internal Server Error", 500)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
Spans should be nested and ordered: each service call creates a child span within the parent trace. When a service calls a downstream service over HTTP, it must capture the full request and response lifecycle.
A trace tells you what happened, but logs and metrics provide context. To correlate them, ensure every log line includes the trace ID, and every metric includes a set of dimensions that map to trace attributes.
In your application logs, emit structured JSON with the trace ID and span ID:
{
"timestamp": "2024-04-10T12:34:56.789Z",
"level": "info",
"message": "User fetched from database",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e5686",
"span_id": "00f0673205c4211d",
"user_id": "123",
"db.query": "SELECT * FROM users WHERE id = $1"
}
In your metrics, use the trace ID as a label. In Prometheus, define a metric like:
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds{service="userservice", method="GET", route="/api/users/{id}", trace_id="4bf92f3577b34da6a3ce929d0e0e5686"} 0.123 1234
Use a single query engine—such as Grafana with the PromQL language—to visualize traces alongside metrics and logs. In a panel, use a query like:
sum by (trace_id) (
rate(http_request_duration_seconds[5m])
) * on (trace_id) (
sum by (trace_id) (
rate(logs{job="userservice"}[1m])
)
)
This query aligns the duration of HTTP requests with the log events that occurred during the same trace, enabling a full-stack view.
Spans should be meaningful, not just per-request. Choose span boundaries carefully: one span per logical unit of work. Avoid spanning too broadly (e.g., a single span for an entire service request) or too finely (e.g., one span per SQL row).
A span should represent a discrete unit of work—like "fetch user from database", "validate request body", or "generate JWT token". Name spans consistently using verbs and nouns. Use the format Verb Noun or Noun Verb, such as Fetch User, Validate Input, Generate Token.
When a service makes a call to another service, the span should capture the entire lifecycle: from initiating the HTTP request to receiving the response. Include the following data in every outgoing span:
http.urlhttp.methodhttp.status_codehttp.request.sizehttp.response.sizepeer.service (the downstream service name)If a service calls a database, include:
db.system (e.g., postgresql, mysql, redis)db.operation (e.g., SELECT, INSERT, GET)db.statement (the SQL query)db.duration (the time spent executing the query)Spans should be sampled based on load and latency. Use a probabilistic sampling strategy: 10% of traces are sampled in production, with a 100% sample rate for traces with latency over 500ms.
Distributed tracing works only when context flows seamlessly across service boundaries. Use a standard format—W3C Trace Context—for propagating trace IDs and baggage across protocols.
In a gRPC service, propagate the trace context from HTTP to gRPC:
func ServeGRPC(ctx context.Context, req *pb.UserRequest) (*pb.UserResponse, error) {
tracer := otel.Tracer("grpc-service")
ctx, span := tracer.Start(ctx, "ServeGRPC")
defer span.End()
// Extract trace context from gRPC metadata
md, ok := metadata.FromIncomingContext(ctx)
if ok {
if traceparent := md.Get("traceparent"); len(traceparent) > 0 {
ctx = otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{
Get: func(key string) string {
if key == "traceparent" {
return traceparent[0]
}
return ""
},
})
}
}
// Inject trace context into outgoing gRPC response
carrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, carrier)
for k, v := range carrier {
md.Set(k, v)
}
// Process request
user, err := fetchUserFromDatabase(ctx, req.UserId)
if err != nil {
span.RecordError(err)
return nil, err
}
return &pb.UserResponse{User: user}, nil
}
For HTTP services, use middleware to extract and inject the trace context:
func TraceMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.MapCarrier{
Get: func(key string) string {
return r.Header.Get(key)
},
})
r = r.WithContext(ctx)
w.Header().Add("traceparent", otel.GetTextMapPropagator().Inject(ctx))
next.ServeHTTP(w, r)
})
}
Ensure that every service uses the same propagation format. If a service receives a request with traceparent but no baggage, it should extract the trace context and propagate it to all downstream calls.
Traces can be lost, incomplete, or inconsistent. The most common failure is a missing span in the middle of a trace. This often happens when a service calls another service but fails to create a span for the call.
When a service receives a request but does not create a span, the trace is missing the entry point. Check for this by verifying that every service logs a Start Trace event at the entry point.
Another failure mode: spans are created but not properly ended. A span may start but never call span.End(), leading to incomplete traces. Use a middleware or a global hook to ensure every trace is finalized.
For services that use async processing (e.g., message queues), create spans for message consumption. When a worker processes a message, create a span that includes the time from when the message was received to when it was acknowledged.
func ConsumeMessage(ctx context.Context, message []byte) error {
tracer := otel.Tracer("worker")
ctx, span := tracer.Start(ctx, "ConsumeMessage")
defer span.End()
span.SetAttributes(
attribute.String("message.id", "abc123"),
attribute.String("message.queue", "user-events"),
)
// Process the message
err := processMessage(ctx, message)
if err != nil {
span.RecordError(err)
return err
}
return nil
}
Use a background task to detect missing spans. In a monitoring pipeline, run a query that finds traces with no Start Trace span, or traces with a Start Trace but no corresponding End Trace span.
Traces generate significant volume. Optimize storage by compressing trace data, batching writes, and indexing on common fields.
Store traces in a columnar format—such as Parquet or Apache Arrow—for efficient querying. Index on trace_id, service, span_name, start_time, and duration.
Use a tiered storage strategy: hot traces (last 7 days) in high-speed storage (e.g., SSDs), warm traces (last 30 days) in cost-effective storage (e.g., S3), and cold traces (older than 30 days) in archival storage (e.g., Glacier).
When querying traces, use a two-stage approach:
service=userservice AND duration > 1s).For performance, cache frequently accessed traces in memory. In a service, maintain a LRU cache of the most recent 10,000 traces.
Use a query interface that supports filtering by:
user.id=123, http.status_code=500)When a user selects a trace in a dashboard, show the full trace with all spans, the associated logs, and the corresponding metrics.
As the number of services grows, so does the cardinality of traces. A single service may produce hundreds of distinct span names, and thousands of unique attributes.
To manage high cardinality, reduce the number of attributes by aggregating or sampling them. For example, aggregate user_id, session_id, and request_id into a single context attribute.
Use a schema registry to define common span attributes across services. Define a standard schema for user, payment, and order services. Enforce this schema through validation in the APM pipeline.
For high-volume traces, use stream processing to ingest and transform data. Use Kafka or Pulsar to collect traces from services, and process them with a real-time pipeline (e.g., Flink or Spark Streaming) that:
In the pipeline, enrich traces with metadata from external sources—such as deployment metadata, configuration changes, or feature flags.
Finally, ensure that traces are not only collected but also actionable. Define a set of trace quality checks that run continuously:
Start Trace event.error=true or http.status_code >= 500 are flagged as errors.Use these checks to generate alerts. For example, when a service has more than 10% of traces with errors, trigger an alert.
Make trace inspection a first-class task in your observability workflow. When an alert fires, show the top 5 traces for that service in the last 10 minutes, with a timeline view of spans, logs, and metrics.
Use a standard query interface—such as a GraphQL API—to retrieve traces:
query GetTraces($service: String!, $from: DateTime!, $to: DateTime!, $limit: Int) {
traces(
service: $service
from: $from
to: $to
limit: $limit
filters: [
{ key: "duration", operator: GT, value: 1.0 }
{ key: "error", value: true }
]
) {
id
duration
startTime
spans {
name
startTime
duration
attributes
logs {
timestamp
message
fields
}
}
metrics {
name
values
labels
}
}
}
This query returns a list of high-latency, error-prone traces with full context—enabling engineers to investigate issues with minimal effort.
This page was rewritten on 17 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.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy