Comprehensive guide to custom instrumentation for production observability and monitoring systems.
Custom Instrumentation is the deliberate act of embedding metrics, logs, and traces into an application to answer questions that off-the-shelf observability cannot. It matters when you need to understand a system’s behavior beyond what auto-instrumentation provides—when latency spikes in a microservice, when a batch job fails intermittently, or when a user journey spans multiple services with no shared context.
To track a business metric like "average time from order placement to first delivery confirmation," you instrument the code where the order is confirmed. This requires adding a metric that captures the duration between two events: order_placed and first_delivery_confirmation.
from prometheus_client import Histogram, Counter, start_http_server
delivery_confirmation_time = Histogram(
'order_delivery_confirmation_time_seconds',
'Time from order placement to first delivery confirmation',
['region', 'order_type']
)
# In the order confirmation service
def confirm_order(order_id, region, order_type):
start_time = time.time()
# ... logic to confirm order ...
delivery_confirmation_time.labels(region=region, order_type=order_type).observe(time.time() - start_time)
The metric appears in Prometheus with the label order_type=subscription, region=APAC, and the histogram bucket values are automatically computed. The histogram is not just a count; it includes sum, count, and bucket values per label set. If the order_type label is missing, the metric is still usable but less actionable.
The key failure mode is label mismatch: if order_type is subscription in one service but Subscription in another, the labels are treated as distinct. To fix this, ensure all services use the same case and values.
When a trace spans services, you often want logs from a service to be visible at the same time as the trace. Use structured logs with trace IDs.
{
"timestamp": "2023-09-15T14:32:11.234Z",
"level": "info",
"message": "Processing user profile update",
"trace_id": "a3e1c8f2-9b4d-4a3c-9e6f-7d1a2b3c4d5e",
"span_id": "b4f3d2e1-c1a2-b3c4-d5e6-f7a8b9c0d1e2",
"user_id": 12345,
"profile_updated_fields": ["name", "email"]
}
The trace_id and span_id are used to correlate logs with distributed traces. In a logging system like Loki, the trace ID is used to group logs by trace, allowing you to see all logs from a single request across services.
The subtle failure is trace ID propagation: if the trace_id is not passed between services via headers (e.g., X-B3-TraceId), logs from downstream services do not link to the root trace. The most common cause is missing header propagation in HTTP clients.
To understand user behavior, emit custom events from the frontend and backend. Each event captures a moment in the user journey.
{
"event": "user_checkout_started",
"user_id": 456,
"session_id": "s7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p",
"timestamp": "2023-09-15T14:32:11.234Z",
"metadata": {
"cart_size": 3,
"checkout_step": "shipping",
"device": "mobile"
}
}
These events are ingested into a streaming platform like Apache Kafka or Amazon Kinesis. A consumer service processes them to build real-time dashboards or trigger downstream actions.
The critical issue is event schema evolution. If checkout_step changes from "shipping" to "shipping_details", older events are not readable. To avoid this, use a schema registry (e.g., Confluent Schema Registry) and version the event schema. The event producer must include the schema ID in the event metadata.
When a service processes a request, you want to break down the total time into its components: network, database, business logic, and external calls.
func HandleOrderRequest(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Track total request time
latencyTotal := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "order_request_duration_seconds",
Help: "Duration of order request processing",
},
[]string{"route", "status"},
)
defer latencyTotal.WithLabelValues(r.URL.Path, "200").Observe(time.Since(start).Seconds())
// Sub-timers for individual steps
dbStart := time.Now()
db.Query("SELECT * FROM orders WHERE id = ?", orderID)
dbLatency := time.Since(dbStart)
prometheus.MustRegister(dbLatencyHistogram)
dbLatencyHistogram.Observe(dbLatency.Seconds())
// External call to payment service
paymentStart := time.Now()
client := &http.Client{}
resp, err := client.Post("https://payment.example.com/v1/charge", "application/json", body)
paymentLatency := time.Since(paymentStart)
paymentLatencyHistogram.Observe(paymentLatency.Seconds())
// Log all steps
log.Printf("order_id=%d, db_time=%v, payment_time=%v, total_time=%v",
orderID, dbLatency, paymentLatency, time.Since(start))
}
The dbLatencyHistogram is a histogram with buckets defined at 0.01, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0 seconds. The paymentLatencyHistogram is registered globally and exported via Prometheus HTTP endpoint.
The common failure is missing histogram registration: if prometheus.MustRegister is omitted, the histogram is not exported, and the metric appears in the registry but is not scraped.
Beyond request-level metrics, define metrics that capture system health at a higher level.
# prometheus.yml
scrape_configs:
- job_name: 'api-service'
static_configs:
- targets: ['api.example.com:9090']
metrics_path: '/metrics'
scheme: 'http'
# Add custom metric collection
metrics:
- name: 'queue_length'
query: |
SELECT
count(*) AS queue_length
FROM message_queue
WHERE status = 'pending'
interval: 10s
labels:
service: 'api-service'
queue: 'order-processing'
- name: 'active_workers'
query: |
SELECT
count(*) AS active_workers
FROM worker_processes
WHERE status = 'running'
interval: 15s
labels:
service: 'api-service'
worker_type: 'processor'
This configuration defines two custom metrics collected via Prometheus’s prometheus job. The queue_length metric is updated every 10 seconds by running the SQL query on a database. The active_workers metric uses a worker_type label.
The failure mode is query timeouts: if the SQL query takes longer than interval, the next sample is delayed. The result is overlapping samples, and the metric appears jagged. To avoid this, ensure the query is optimized and the database connection pool is sized appropriately.
When a failure occurs, you want to gather more detail than logs and traces alone provide. Use structured instrumentation to capture the state of the system at the time of a failure.
{
"error": "order_processing_failed",
"timestamp": "2023-09-15T14:32:11.234Z",
"error_code": "ORDER_502",
"details": {
"order_id": 12345,
"user_id": 67890,
"step": "calculate_total",
"input": {
"items": [
{ "id": 1, "price": 19.99 },
{ "id": 2, "price": 5.50 }
],
"tax_rate": 0.08,
"shipping_method": "express"
},
"output": {
"total": 35.48,
"tax": 2.08,
"shipping": 10.00
},
"environment": {
"region": "us-west-2",
"version": "v1.2.3",
"deploy_id": "d1a2b3c4e5f6"
}
}
}
This error event is emitted when the calculate_total step fails. The details object captures the full context of the failure: the input, output, and environment. The event is stored in a central event store like Elasticsearch or a time-series database.
The sharp edge is event size: if the input contains 100 items, the event becomes large and slow to ingest. To manage this, use event compression (e.g., gzip) and truncate large arrays. Also, ensure the event schema is versioned so that older consumers can handle new fields.
Labels are the primary way to slice and dice metrics. To be effective, label keys must be consistent across all metrics.
{
"name": "order_request_duration_seconds",
"help": "Time to process order request",
"type": "histogram",
"labels": [
{ "name": "method", "values": ["POST", "PUT"] },
{ "name": "status", "values": ["200", "500", "400"] },
{ "name": "service", "values": ["api", "gateway", "order"] }
]
}
The method and status labels appear across multiple metrics. If method is Post in one metric and POST in another, the labels are treated as different. To avoid this, normalize labels using a standard set of values.
When a request flows from one service to another, context must be preserved. Use a standard format for trace context.
GET /api/v1/orders/123 HTTP/1.1
Host: api.example.com
X-B3-TraceId: a3e1c8f2-9b4d-4a3c-9e6f-7d1a2b3c4d5e
X-B3-SpanId: b4f3d2e1-c1a2-b3c4-d5e6-f7a8b9c0d1e2
X-B3-ParentSpanId: a3e1c8f2-9b4d-4a3c-9e6f-7d1a2b3c4d5e
X-B3-Sampled: true
The X-B3-TraceId identifies the full trace. The X-B3-ParentSpanId links the new span to its parent. The X-B3-Sampled flag indicates the trace should be retained.
The common failure is missing X-B3-Sampled. Without it, the trace is not sampled, and the data is too coarse for analysis.
Define a contract for instrumentation: what metrics, logs, and events must be emitted, and how they are structured.
A contract for the order_processing service might state:
order_processed_total counterevent: order_processedtrace_id and span_idservice=order-processingtimestamp, user_id, and order_idThe contract is documented in INSTRUMENTATION.md and enforced via CI:
# .github/workflows/instrumentation-check.yml
name: Instrumentation Validation
on: [push]
jobs:
validate-instrumentation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: |
npm install -g @observability/instrumentation-validator
instrumentation-validator --config instrumentation.json --path src/
# Exits non-zero if any metric or event is missing
The validator checks that every emitted metric has the required labels, every event has required fields, and every log has required keys. It fails silently if a required field is missing.
When instrumentation is heavy, the cost of emitting metrics and logs can impact the main application performance.
To mitigate this, use asynchronous instrumentation:
import asyncio
async def log_event(event):
# Send to Kafka asynchronously
await kafka.produce(topic="events", value=json.dumps(event))
# Do not wait for response; continue processing
The failure mode is dropped events: if the Kafka producer fails and the event is not sent, the event is lost. To detect this, emit a event_sent_total counter and a event_sent_error counter.
Custom Instrumentation is not a one-time setup. It is a discipline of answering questions with precise, measurable, and actionable data. It thrives on consistency, context, and simplicity. When it breaks, it breaks visibly: metrics are missing, logs are inconsistent, and traces are disconnected. The key to success is not just writing code, but defining and enforcing instrumentation contracts across teams.
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