Structured Logs, Metrics, and Correlation IDs for APIs
Instrument API integrations with structured logs, service metrics, and correlation IDs so teams can trace failures without exposing secrets or personal data.
Follow one accepted order request from its structured log and bounded metric to worker trace context and queue acknowledgement. This guide shows how to omit sensitive fields, propagate W3C trace context through a message, and keep request IDs out of metric labels so operators can diagnose the same operation without creating unbounded time series.
Structured Logs, Metrics, and Correlation IDs for APIs
Introduction
When an API call fails across several services, a plain message like “request failed” offers little help. Logs preserve selected fields, metrics show how often a problem occurs, and trace context connects work across services. Together they can narrow a customer-visible error to a failing dependency or workflow stage.
The examples below follow one accepted order through all three signals.
Log one accepted request
Use fields that explain a request without recording its body: a route template, method, status, duration, outcome, and trace or request ID. This synthetic, redacted record shows one POST /v1/orders accepted for asynchronous processing. Credentials, customer details, and the request body are omitted.
{
"event": "order.request.accepted",
"service": "orders-api",
"route": "/v1/orders",
"method": "POST",
"status_code": 202,
"duration_ms": 84,
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"request_id": "req_7f32",
"order_id": "ord_91c2"
}
The request ID is a diagnostic join value, not an identity claim. Validate any inbound ID and replace it when malformed or outside the allowed format. Restrict access to logs with identifiers, and omit tokens, payment data, email addresses, and raw payloads.
Count operations with bounded labels
For that same accepted order, increment a queue-operation counter once when the message is published:
orders_queue_operations_total{queue="orders", operation="publish", outcome="accepted"} 1
The label values come from small, controlled sets: known queue names, operation types, and outcomes. Do not add request_id, trace_id, order_id, or customer IDs. Each unique label combination creates another time series; Prometheus naming guidance warns against high-cardinality labels such as user IDs. Put unique identifiers in logs or traces instead.
Carry trace context through a queue
The API server starts a trace for the accepted request and creates a producer span while publishing the order. An OpenTelemetry propagator injects trace context into the queue message’s header carrier. For example, a message can carry:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
request_id: req_7f32
traceparent follows the W3C format for version, trace ID, parent ID, and trace flags. The application request_id is a separate field. The worker extracts the trace context before processing the message and records the same request ID in its logs. After the worker completes the operation according to the service’s delivery contract, it settles or acknowledges the message. Broker acknowledgement semantics vary. The sequence is:
POST /v1/orders
-> producer span publishes to orders queue
-> message carries traceparent + request_id
-> worker extracts context and processes order
-> settle/ack span records acknowledgement
OpenTelemetry’s messaging conventions recommend linking a consumer process span to the message creation context; exact parent/link relationships can vary with the queue and instrumentation. Settlement can be represented by its own span. If your tracing backend supports searching span attributes, you can also add request_id there. See the W3C Trace Context Recommendation, OpenTelemetry context propagation, and OpenTelemetry messaging span conventions.
The HTTP request ID may help find the accepted record, while the trace connects the producer, worker, and acknowledgement. Keep the same request ID as searchable metadata if a trace is sampled out; do not turn it into a metric label.
When to use and when not to
Use structured logs for diagnostic details, metrics for service health and alerting, and trace context for distributed request paths. Add correlation metadata to queued work and webhooks when the operation spans time. Do not use a request ID as a metric label or as authorization. Do not log payloads simply because a debugging tool makes it convenient; capture only fields with a clear diagnostic purpose.
Observability checklist
- Log the order route, status, duration, request ID, and trace ID; omit secrets and the body.
- Count queue publish, process, and acknowledgement outcomes with fixed label values.
- Inject trace context into the message and extract it in the worker.
- Keep request and trace IDs out of metric labels.
- Retain errors and slow traces when sampling successful traffic.
Security and compliance notes
Treat inbound IDs as untrusted: enforce length and character limits, and prevent control characters from altering log records. Restrict log access and retention. Redact authorization headers, personal or payment data, and payloads; hashing low-entropy personal fields is not a substitute for redaction. A correlation ID is diagnostic metadata, not proof of identity or permission.
Common pitfalls
- Logging raw request or response bodies for convenience can expose credentials and personal data. Log selected fields with a clear diagnostic purpose.
- Using a request ID as a metric label creates a new time series for nearly every call. Keep unique IDs in logs or traces.
- Propagating an ID without trace spans may connect events but still hide where time was spent. Add spans or dependency timing when latency diagnosis matters.
- Sampling away every successful trace can make a low-frequency failure impossible to compare with normal traffic. Keep a small baseline sample and retain errors and slow requests.
Quick recap checklist
- Use logs for detailed events, metrics for aggregate trends, and traces for request paths.
- Propagate correlation or trace context across services and asynchronous boundaries.
- Keep metric dimensions bounded; put unique request identifiers in logs or traces.
- Scrub secrets and sensitive data from telemetry and control access to it.
Interview questions
Further reading
- API Gateway and Integration Monitoring follows route and dependency health across an integration.
- Metrics, monitoring, and alerting covers service health signals and alert design.
- Partial failure, ordering, and eventual consistency shows why operation context matters across asynchronous workflows.
- API mocks, sandboxes, and test data discusses capturing request and response metadata safely in tests.
- OpenTelemetry: Traces and context propagation explains how spans connect work across services.
- Prometheus: Metric and label naming describes naming guidance and high-cardinality label risks.
Conclusion
When an order fails, the request ID helps find its log, the metric shows whether queue operations are affected broadly, and the trace shows where this request spent time. Keep the identifiers useful for diagnosis and keep them out of access decisions and metric labels.
Category
Related Posts
Database Monitoring: Metrics, Tools, and Alerting
Monitor PostgreSQL with user-facing latency, connection and lock pressure, replication lag, and disk headroom. Includes versioned system-view examples and alert guidance.
ELK Stack: Elasticsearch, Logstash, Kibana, and Beats
Complete guide to the ELK Stack for log aggregation and analysis. Learn Elasticsearch indexing, Logstash pipelines, Kibana visualizations, and Beats shippers.
Logging Best Practices: Structured Logs, Levels, Aggregation
Learn production logging with structured formats, useful log levels, correlation IDs, and scalable aggregation. Includes secure patterns for containerized apps.