Skip to content

Messaging Observability & Tracing ​

“traceparent describes the position of the incoming request in its trace graph in a portable, fixed-length format.” — W3C, Trace Context (Recommendation, 23 November 2021)

Summary: Async systems break the call stack, so observability has to be rebuilt from message headers, broker counters and a few well-chosen metrics. Focus: Trace-context propagation, OpenTelemetry messaging conventions, lag and age signals per broker, safe logging, sampling and SLO alerts. Learning goal: Follow one message from publish to settlement in a trace, measure how far behind every consumer is, and page on the right number.

This chapter owns instrumentation of messaging. The general theory of logs, metrics and traces lives in Observability: Logs, Metrics, Traces; the terminal failure path in the dead-letter queue; the reaction to a growing backlog in backpressure and flow control. Here the question is narrower: how do you see a message that spends minutes inside a broker?

Page map ​

Looking forGo to
What to collect for an async systemThe three signals
How a trace survives a broker hopPropagation
Exact span and attribute namesSemantic conventions
One consumer span for a batchSpan links
Trace id versus correlation id versus message idIdentifiers
Lag, age, depth, unackedBacklog signals
Logs without payloads or personal dataLogging
Sampling and exemplarsSampling
Paging on lagAlerting
Per-broker endpoints and codeBroker differences
Horizon, Pulse, TelescopeLaravel
Experiments to reproduce each signalLab

Everything in one minute ​

QuestionWorking answerFailure if ignored
Why does a trace stop at the broker?Nothing copies the span context into the message unless your code or library doesTwo unrelated traces and no way to join them
What travels in the message?traceparent, optional tracestate, optional baggage, a message id, a correlation idLogs cannot be tied to the request that caused them
Parent-child or link?Link by default; parent-child only for one message outside another spanA batch span cannot have forty parents
What is lag?Work that exists but has not been consumed yet, in recordsA healthy-looking consumer is hours behind
What is better than depth?Age of the oldest undelivered messageA small queue with a stuck consumer never alerts
What goes in a log line?Ids, destination, attempt number, outcomePayloads and personal data leak into the log store
What do you alert on?Burn of a latency or age objective, plus “consumers = 0 with work waiting”Pages for every deploy, none for slow poison
SignalProducer sideConsumer sideBroker side
TracesPRODUCER span, context injectedCONSUMER span, link to producerRarely traced; carries headers only
MetricsSent messages, publish failuresProcess duration histogram, message ageDepth, ready, unacked, consumers, lag
LogsMessage id, destination, resultMessage id, attempt, trace id, resultBroker logs, connection and queue events
Best question it answersDid the publish succeed?How long did handling take?How far behind are we?
BrokerWhere the context goesLag sourceScrape endpoint
RabbitMQAMQP headers tablemessages_ready, messages_unacknowledgedPrometheus plugin on port 15692; management API on 15672
KafkaRecord headersLog end offset minus committed offsetClient JMX records-lag-max, kafka_exporter, Burrow
Redis StreamsExtra field/value pairsXINFO GROUPS lag and pendingYour own probe; no built-in exporter
Laravel queueJob payload or ContextQueue size, Horizon wait timeHorizon dashboard, Pulse Queues card

Where it comes from ​

Three specifications meet here. W3C Trace Context (Recommendation, 23 November 2021) defines the traceparent and tracestate header fields; it is written for HTTP but its field format is reused everywhere. W3C Baggage defines baggage, a list of key/value pairs that travels with the trace. OpenTelemetry defines the API, the SDKs and the semantic conventions that name spans and attributes. The messaging conventions carry the status “Development” on the page I read, so the names can still change.

The specifications deliberately say little about brokers. The OpenTelemetry messaging page states that it “does not specify the exact mechanisms on how the creation context is attached/extracted to/from messages”. Each client library therefore chooses: AMQP headers, Kafka record headers, a hash field in a stream entry, or a field in a job payload. Metrics are even less standard: every broker exposes its own backlog numbers under its own names.

Why it exists ​

In a synchronous call the stack is the trace: the caller waits, the callee returns, and a profiler can walk the frames. A message breaks that. The producer finishes in milliseconds; the consumer starts seconds or days later, on another host, possibly after a retry. Nothing connects the two unless you write the connection into the message.

Synchronous callMessage through a broker
Caller waits, so latency is the caller's problemLatency hides inside the queue
One trace, parent-child by defaultProducer and consumer are separate operations
Failure is an error returned to the callerFailure is a redelivery, a retry or a parked message
Load shows as slow responsesLoad shows as growing backlog while producers stay fast
Request id in the log is enoughThe request id must be written into the message

Three misunderstandings to remove first: a healthy broker does not mean healthy consumption; queue depth is a count, not a delay; and a trace id is not a business correlation id.

What it is really about ​

The mechanism is small. The producer starts a span, asks the configured propagator to write the span context into a carrier (a map of strings backed by the message headers), and publishes. The consumer reads the same keys back, builds a remote span context, and either links to it or parents under it. Everything else in this chapter is about naming, limits and failure.

Producer servicePRODUCER span "publish orders"trace 0af7...319cMessage on the brokerheaders / fields:traceparent tracestate baggagemessage id (no payload data)Consumer serviceCONSUMER span "process orders"new trace, LINK to producerinjectextractRabbitMQ: headers table Kafka: record headers Redis Streams: extra field/value pairsBroker not in the trace pathAMQP, Kafka protocol and XADD only carry the bytesBreak the chain here and you gettwo unrelated traces and no way to join them

Application signals alone are not enough. The broker knows things the application cannot: how many messages are waiting, how old the oldest one is, how many consumers are attached. Both sets of signals end in the same backend, which is why the second picture matters.

Producer / consumerOTel SDK: traces, metricsBroker endpoints/metrics, management API, JMXProbeslag, oldest age (own code)Collector / Prometheussampling, scrape, relabeldrop payload attributesTracing backendtrace view + span linksMetrics storehistograms, exemplarsAlertslag SLO, burn rate

An everyday picture ​

A parcel carries a tracking label (the trace context) written at the sender's depot. The depot staff do not follow the parcel; the label is how any later scan, even weeks later at another depot, joins the story. Queue depth is the number of parcels in the sorting room. Oldest message age is how long the parcel at the bottom of the pile has waited. A big pile that clears in a minute is fine; one parcel that has waited a week is an incident, even when the pile is tiny.

Concept catalogue ​

The three signals for async systems Must-know ​

In plain words: Traces tell you the path of one message, metrics tell you how the whole system is doing, logs tell you what happened and why.

Common misunderstanding: One of the three is enough. A trace sampled at 1 percent cannot tell you the oldest message is an hour old; a metric cannot tell you which order was lost; a log line without an id cannot be joined to either.

Definition: Traces record causally related operations as spans. Metrics aggregate measurements over time into counters, gauges and histograms. Logs record discrete events. For messaging each needs one extra ingredient: the message identity (message id, destination, partition and offset or stream id) so that the three can be joined.

text
1 order service      -> trace: span publish orders (PRODUCER)         t=0.000s
2 order service      -> metric: sent_messages{destination=orders} +1
3 order service      -> log: published message_id=m-1 destination=orders
4 broker             -> metric: ready=1, oldest_age=0s
5 consumer (later)   -> trace: span process orders (CONSUMER, link)  t=41.300s
6 consumer           -> metric: process_duration histogram, message_age 41.3s
7 consumer           -> log: handled message_id=m-1 attempt=1 outcome=ok

Real scenarios: A payment webhook is acknowledged but the ledger entry appears 40 minutes late; the trace shows the consumer span started 39 minutes after the publish span, and the age histogram shows the same. A deploy halves consumer capacity; depth looks fine for ten minutes while the age histogram bends. A poison message loops; the redelivery counter climbs while every other signal looks normal.

QuestionBest signalWhy
Why was this order late?Trace with span linkShows publish time, wait time, handler time
Are we falling behind?Lag and oldest age metricsAggregates over all messages
What did handler X do for message m-1?Structured logCarries ids and outcome
Did the new release slow processing?Duration histogramCompares distributions before and after
Is one tenant flooding the queue?Metric by low-cardinality dimensionTraces are sampled; counters are not

How to use it: Emit all three from the same wrapper so the ids match. In Go the msgtrace package below starts the span and exposes LogAttrs for the log line; msgmetrics records the histogram from the same context.

Trace-context propagation in message headers Must-know ​

In plain words: Write the trace id into the message before it leaves, and read it back when the message arrives.

Common misunderstanding: The broker or the HTTP middleware does this automatically. Only a client library with messaging instrumentation, or your own code, does; otherwise the consumer starts an unrelated trace.

Definition: A propagator injects the current span context into a carrier and extracts a remote context from a carrier. For W3C Trace Context the carrier keys are traceparent (version, trace id, parent id, trace flags) and tracestate (vendor-specific list). baggage carries application key/value pairs. An invalid traceparent must be ignored by the receiver, so a corrupted header degrades to a new trace rather than a failure.

text
traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
             |  |                                |                |
             |  trace-id (16 bytes, 32 hex)      parent-id (8 B)  flags: 01 = sampled
             version
tracestate:  rojo=00f067aa0ba902b7,congo=t61rcWkgMzE
baggage:     tenant=acme,release=2026-11

Real scenarios: A web request publishes an order event; the billing consumer's logs carry the same trace id as the web request. A relay process reads an outbox table and republishes; it must forward the stored traceparent, not mint a new one. A message moves through a retry queue and back; the headers must survive the hop.

HeaderContentLimit or ruleRisk
traceparentVersion, trace id, parent id, flagsVersion ff invalid; all-zero ids invalidA bad value silently starts a new trace
tracestateVendor list of key=valueAt most 32 list members; propagate at least 512 charactersTruncation drops whole entries
baggageApplication key/value pairsMinimums: 64 members, 8192 bytesLeaks data to every downstream service and broker
Sampled flagLast field of traceparent01 sampled, 00 notA consumer that respects it records nothing for unsampled traces

How to use it: Install a composite propagator once (TraceContext plus Baggage) and wrap publish and consume. The Go carriers below adapt AMQP headers, Kafka record headers and stream fields to the TextMapCarrier interface. Never put secrets or personal data in baggage: the W3C specification says baggage “may carry sensitive information” and assigns the receiving system the duty to assess that risk.

OpenTelemetry messaging semantic conventions Must-know ​

In plain words: A shared vocabulary so that every backend can draw a queue span without being told what it is.

Common misunderstanding: The attribute names are stable and identical across libraries. The page I read is marked “Development”, the current spec names the key messaging.system.name, while existing instrumentations and dashboards may still use the older messaging.system (my inference; the page only says older versions exist and gives an opt-in variable).

Definition: The conventions define span kinds by operation type, a span name of the form {messaging.operation.name} {destination}, a set of attributes (messaging.system.name, messaging.destination.name, messaging.operation.name, messaging.operation.type, messaging.message.id, messaging.batch.message_count and more) and client metrics (messaging.process.duration, messaging.client.sent.messages, messaging.client.consumed.messages).

text
operation.type -> span kind        name example
create         -> PRODUCER         create shop.orders
send           -> PRODUCER (or CLIENT when a Create span is the context)  publish shop.orders
receive        -> CLIENT           receive shop.orders
process        -> CONSUMER         process shop.orders
settle         -> CLIENT           ack shop.orders

Real scenarios: A push consumer (callback) gets a process span; a pull consumer (explicit poll) gets a receive span and optionally process spans inside. A Kafka producer that sends a batch creates one create span per message and one send span. A broker-side redelivery shows as a second process span linked to the same creation context.

AttributeMeaningRequirement on the spans I read
messaging.system.nameMessaging system, for example kafka, rabbitmqRequired
messaging.operation.nameSystem-specific operation, for example publish, processRequired
messaging.operation.typecreate, send, receive, process, settleConditionally required if applicable
messaging.destination.nameQueue, topic or streamConditionally required
messaging.destination.templateLow-cardinality form of a dynamic nameConditionally required if available
messaging.destination.partition.idPartition idRecommended
messaging.message.idBroker-assigned message idRecommended for a single message
messaging.message.conversation_idCorrelation idRecommended
messaging.consumer.group.nameConsumer groupConditionally required on metrics
messaging.batch.message_countMessages in a batch operationConditionally required for batches
error.typeLow-cardinality failure classConditionally required on failure
kafka.offset, kafka.message.keyKafka-specificRecommended on single-message Kafka spans
rabbitmq.destination.routing_keyRouting keyConditionally required if not empty

How to use it: Pin the convention version your instrumentation emits. The page documents OTEL_SEMCONV_STABILITY_OPT_IN with the values messaging (new conventions only) and messaging/dup (both), so dashboards can migrate. redis is not in the well-known messaging.system.name list on that page; the spec allows a custom value, which the Go snippet uses.

In plain words: A link says “this work was caused by that work” without pretending they are one call.

Common misunderstanding: The consumer span should simply be a child of the producer span. That is right for one message processed outside any other span, and wrong for batches, retries and consumers that run inside an HTTP or job span of their own.

Definition: A span has exactly one parent but any number of links. The conventions name links as the default mechanism because, in their words, “It is the only option to correlate producer and consumer(s) in batch scenarios as a span can only have a single parent.” For single messages a process span may use the creation context as its parent; the page marks that as opt-in and says not to do it by default when processing happens inside another span.

text
single message, parent-child:
  1 PRODUCER send orders
  2   +- CONSUMER process orders           (same trace)

batch of three, links:
  1 PRODUCER send orders (m1)   trace A
  2 PRODUCER send orders (m2)   trace B
  3 PRODUCER send orders (m3)   trace C
  4 CONSUMER process orders     trace D, batch_message_count=3, links -> A, B, C

Real scenarios: A Kafka poll returns 500 records and the handler writes them in one transaction. A retry republishes the message to the same queue and the second attempt must still point at the original creation context. A consumer runs inside a scheduled job span and must not lose that span as its parent.

Single message: parent-child allowed (opt-in)PRODUCER sendCONSUMER processchildSame trace, one timeline. Fine if no ambient parent.Batch: links are the only correct shapesend m1send m2send m3CONSUMER processbatch_message_count = 3dashed = link; a span has exactly one parentDefault in the semantic conventions: link producer and consumer; the consumer starts its own trace.Opt in to parent-child only for single messages and when the process runs outside another ambient span.
DesignTrace shapeGood forCost
Parent-childOne trace from producer to consumerA single message, low fan-outLong traces; a batch cannot fit
LinkConsumer starts a new trace, links backBatches, retries, fan-outUI must support following links
BothChild of ambient span plus link to producerConsumer inside another spanMore code
No relationshipTwo unrelated tracesNever intendedDebugging by timestamp guessing

Laravel's OpenTelemetry auto-instrumentation shows the trade-off in code: its worker hook makes the process span a child of the extracted context by default, and a job that implements the TracingLinked interface gets a link and a new root instead (read from the source on the main branch). Check which behaviour your library defaults to before you design dashboards around it.

How to use it: StartProcess in the snippet takes a Mode (Link or Child) and StartBatchProcess links every message in a poll result; the test TestBatchSpanLinksEveryRecord fixes the shape.

Correlation id, trace id and message id Important ​

In plain words: Three identifiers answer three different questions: which business conversation, which technical request, which physical message.

Common misunderstanding: The trace id can serve as the correlation id. A trace id is generated per trace and may be dropped by sampling, restarted by a link-style consumer, or reused across business operations; a correlation id is chosen by the business and survives all of that.

Definition: The trace id (32 hex characters in traceparent) identifies one trace. The correlation id (correlation_id property in AMQP, a header elsewhere; messaging.message.conversation_id in the conventions) groups the messages of one business conversation, such as an order. The message id (message_id in AMQP, offset or stream id elsewhere; messaging.message.id) identifies one message and is the key for deduplication.

text
1 HTTP request  -> trace_id=T1, correlation_id=order-42
2 publish m-1   -> message_id=m-1, traceparent carries T1, correlation_id=order-42
3 consumer      -> new trace T2 linked to T1, logs correlation_id=order-42, message_id=m-1
4 retry m-1     -> same message_id and correlation_id; new span, link to T1

Real scenarios: A support engineer searches logs by order number, not by trace id. A saga spans six services and eight traces; the correlation id joins them. A redelivery arrives with the same message id; the consumer's inbox uses it to skip the duplicate.

IdentifierQuestionWho creates itSurvives retry?Survives sampling?
Trace idWhich technical request?TracerLink keeps it; child shares itNo: unsampled traces vanish
Correlation idWhich business conversation?Business code or edgeYesYes
Message idWhich physical message?Producer or brokerYes for redelivery; new for a republishYes

How to use it: In AMQP set MessageId and CorrelationId separately (the snippet does). Do not reuse the message id as the correlation id. Link to idempotent consumers for deduplication by message id.

Backlog signals: lag, oldest message age, depth, unacked Must-know ​

In plain words: Lag is how much work is waiting; age is how long the oldest of it has waited; unacked is work handed out but not finished.

Common misunderstanding: Queue depth is the health number. Depth is a count; it says nothing about the time to drain. A queue of ten million messages that drains in a minute is healthy, and a queue of three whose consumer is stuck for an hour is not.

Definition: Consumer lag is, per partition or stream, the number of records produced but not yet consumed (log end minus the committed position). Queue depth (RabbitMQ messages) is ready plus unacked. Unacked is delivered but not acknowledged. Oldest message age is now - timestamp of the first undelivered message; no broker exposes it uniformly, so you compute it from a timestamp in the message or a stream id.

text
1 log end offset            = 1_200
2 committed offset (group)  =   900      -> lag = 300 records
3 first uncommitted record  = timestamp 12:00:00; now = 12:04:10  -> oldest age = 250 s
4 consumer fetched up to 960 (in memory)   -> client records-lag = 240, committed lag = 300

Real scenarios: A consumer crash-loops on a poison message: ready stays flat, redelivered climbs, age grows. A rebalance storm: lag sawtooths. A slow downstream: unacked sits at the prefetch limit while ready grows. A paused Redis consumer group whose last entry was trimmed: lag turns NULL.

Log or queue, oldest to newest: oldest ... committed / acked ... delivered but unacked ... newest (log end)Consumer lag (records)log end offset - committed offsetKafka, Redis XINFO lagOldest message age (seconds)now - timestamp of first undeliveredthe signal an SLO can useIn flight / unackeddelivered, not yet settledRabbitMQ unacked, Redis PELDepth alone misleadsa queue with 10k messages and 50k/s drain is healthy;a queue with 3 messages and a stuck consumer is notAlert onage above objective, or lag growing for N minutes,and on zero consumers with nonzero depth
SignalRabbitMQKafkaRedis Streams
Waiting workmessages_readylog end minus committed offsetXINFO GROUPS lag
In flightmessages_unacknowledgednone (offset commit is the only settlement)pending (PEL size)
Total depthmessagessum of laglag plus pending
Redeliveryredelivered flag, redeliver rate in message statsconsumer rewinds, same offset seen twicedelivery count in XPENDING extended form
Oldest agenot a standard metric; stamp the messagetimestamp of the record at the committed offsetcreation time inside the next stream id
Publish failurepublisher confirm nack, basic.returnproducer error, ackscommand error from XADD

How to use it: Export lag per group and unacked per queue, and compute age from message timestamps. lagprobe below turns each broker's numbers into one vocabulary (messaging_consumer_lag_records, messaging_queue_unacked_messages, messaging_oldest_undelivered_age_seconds). Report unknown as unknown: Kafka's admin API returns -1 and go-redis returns -1 for a NULL Redis lag; exporting them as numbers makes a graph that lies.

Logging with ids and without payloads Important ​

In plain words: Log which message and what happened, never what was inside it.

Common misunderstanding: A debug log of the payload is harmless because only engineers read logs. Logs are copied to vendors, retained for years and searched by wide groups; they become an uncontrolled copy of personal data.

Definition: Structured logging writes each event as key/value pairs. For messaging the safe set is the identifiers (trace_id, span_id, correlation_id, message_id), the position (destination, partition, offset or stream id), the attempt number and the outcome class. PII (personally identifiable information) such as names, emails, card numbers and free text stays out; a job or message carries identifiers and the handler loads the rest.

text
1 handler start  -> {"msg":"handling","message_id":"m-1","destination":"orders","attempt":1,"trace_id":"..."}
2 handler failed -> {"msg":"failed","message_id":"m-1","error.type":"*errors.errorString","attempt":1}
3 never          -> {"msg":"failed","body":"{\"email\":\"someone@example.com\"}"}

Real scenarios: A DLQ replay tool logs the full body of a thousand parked messages. A retry middleware logs err.Error() and the error text contains a customer's address. A debug flag left on in production prints every header, including baggage.

DataIn logs?Instead
Message id, correlation id, trace idYesnone needed
Destination, partition, offset, stream idYesnone needed
Attempt number, delay, outcome classYesnone needed
Payload bodyNoLog size and schema version
Exception textCarefullyLog a class or reason code; keep the text in the error tracker
Baggage valuesNoLog keys only

How to use it: The Go helper LogAttrs returns slog attributes with ids only; a test asserts the output contains the trace id and no payload. Laravel's Context adds correlation_id and trace_id to every log line, including those of queued jobs. See the security chapter for the wider data-handling rules.

Sampling and exemplars Important ​

In plain words: You cannot keep every trace, so decide cheaply which to keep and make the decision follow the message.

Common misunderstanding: Each service can sample independently. If the producer samples and the consumer decides again with a fresh random choice, you keep the producer half of some traces and the consumer half of others and join almost nothing.

Definition: Head sampling decides when the trace starts; the decision travels in the sampled flag of traceparent and a parent-based sampler obeys it. Tail sampling decides after the trace is complete, in a collector. A span link recorded at span creation “may be considered by Samplers”, which is why link-style consumers should pass links when starting the span, not add them later. An exemplar is a sample trace id attached to a metric bucket, so a slow histogram bucket points at one real trace.

text
1 producer: sampler decides -> traceparent ...-01
2 consumer: parent-based sampler reads flag 01 -> records the span
3 producer: sampler decides -> traceparent ...-00
4 consumer: reads flag 00 -> drops the span (a link to an unsampled context)

Real scenarios: A 1 percent head sample keeps almost no failed messages; a tail sampler keeps all errors and the slowest one percent. A histogram bucket for 30 seconds shows an exemplar, and the engineer opens the trace behind it. A tenant floods a topic; counters by destination show it while traces would not.

StrategyDecidesKeeps errors?Cost
Always onProducerYesHighest volume
Probability (ratio)Producer, TraceIDRatioBasedBy chanceLow, loses rare events
Parent-basedObeys incoming flagFollows producerNeeds propagation to work
Tail samplingCollectorYes (policy)Collector memory and delay
ExemplarsMetric SDKn/aNeeds OpenMetrics exposition and Prometheus exemplar storage

How to use it: The Go test TestUnsampledDecisionTravelsInFlags shows an unsampled trace ending in -00; TestSampledSpanAttachesExemplar shows the SDK attaching a trace id to a histogram point. Prometheus stores exemplars only with the exemplar-storage feature enabled and scraped from OpenMetrics output.

Alerting on lag with SLOs Must-know ​

In plain words: Say how late is too late, then alert when you are spending the allowance faster than planned.

Common misunderstanding: Alert when depth exceeds a number. A fixed depth fires on every traffic peak and misses the stuck consumer. Alert on an objective the business understands, such as “99 percent of orders start processing within 60 seconds”.

Definition: A service level objective (SLO) is a target for a service level indicator (SLI) over a window. For a queue the SLI is the fraction of messages whose age at processing start is within the limit. The error budget is the allowed fraction of misses. A burn rate is how fast the budget is spent relative to the plan. The Google SRE workbook recommends paging at “2% budget consumption in one hour and 5% budget consumption in six hours” and tickets at 10 percent in three days; for a 30-day window that is burn rates of 14.4 and 6.

text
1 SLO: 99% of messages processed within 60 s over 30 days -> budget 1%
2 5-minute error ratio   = 1 - (bucket le=60 / count)  = 0.20
3 burn rate              = 0.20 / 0.01                  = 20
4 1 h burn 20 > 14.4 AND 5 m burn 20 > 14.4 -> page
5 5 m burn drops below 14.4 -> alert resolves within 5 minutes

Real scenarios: A deploy pauses consumers for two minutes and the burn alert stays quiet because the budget barely moves. A poison message stalls a partition for an hour and the alert fires inside ten minutes. A queue with no consumers at all pages immediately through a separate rule.

AlertCondition (example)NotificationWhy
Fast burnBurn above 14.4 over 1 h and 5 mPage2 percent of 30-day budget in an hour
Slow burnBurn above 6 over 6 h and 30 mPage5 percent in six hours
DriftBurn above 1 over 3 dTicketQuiet exhaustion
No consumersReady above 0 and consumers 0 for 5 mPageNo histogram exists to burn
Oldest ageAge above objective for 10 mPageWorks when no messages complete
Lag growingLag derivative positive for 15 m and lag above floorTicketCapacity trend
yaml
groups:
  - name: messaging-slo
    rules:
      - record: slo:orders_age_within_60s:ratio_rate5m
        expr: |
          sum(rate(app_messaging_message_age_seconds_bucket{le="60",messaging_destination_name="orders"}[5m]))
          / sum(rate(app_messaging_message_age_seconds_count{messaging_destination_name="orders"}[5m]))
      - record: slo:orders_age_within_60s:ratio_rate1h
        expr: |
          sum(rate(app_messaging_message_age_seconds_bucket{le="60",messaging_destination_name="orders"}[1h]))
          / sum(rate(app_messaging_message_age_seconds_count{messaging_destination_name="orders"}[1h]))
      - alert: OrdersFastBurn
        expr: |
          (1 - slo:orders_age_within_60s:ratio_rate1h) > (14.4 * 0.01)
          and (1 - slo:orders_age_within_60s:ratio_rate5m) > (14.4 * 0.01)
        labels: {severity: page}
      - alert: OrdersNoConsumers
        expr: rabbitmq_detailed_queue_messages_ready{queue="orders.billing"} > 0 and rabbitmq_detailed_queue_consumers{queue="orders.billing"} == 0
        for: 5m
        labels: {severity: page}

How to use it: The metric names above are what a Prometheus exporter typically produces from app.messaging.message_age (dots become underscores, the unit suffix is added); check your exporter's output. The le="60" selector works only because 60 is one of the histogram's bucket boundaries.

Mechanics and exact controls ​

Header formats and where they can be lost Important ​

Propagation fails in specific ways, and each leaves a recognisable symptom.

Where it breaksCauseSymptom
ProducerNo SDK installed, so the span context is invalid and nothing is injectedConsumer traces always start fresh
ProducerInstall never called, so the no-op propagator is usedSame
ClientHeader type mismatch ([]byte versus string)Extract returns empty
Broker bridgeA shovel, MirrorMaker or connector drops headersTrace stops at the bridge
Retry or DLQ hopRepublish builds new headersLink target is the retry span, not the origin
Outbox relayRelay mints a new traceTwo traces joined only by correlation id
Redis StreamsField names collide with business fieldsBusiness reader sees traceparent
KafkaProducer appends a second traceparent on retryDuplicate header, ambiguous read
Proxy or gatewayStrips unknown headersTrace stops at the edge

Metrics endpoints and their cost Important ​

EndpointPort and pathCardinalityCost note
RabbitMQ Prometheus aggregated15692 /metricsAggregated by name (default)Output size constant as objects grow
RabbitMQ per-object15692 /metrics/per-objectOne series per objectLarge payloads with many queues
RabbitMQ detailed15692 /metrics/detailed?family=queue_coarse_metricsSelected families, filtered by vhost and queueUp to 60 times cheaper than per-object for a few metrics (docs)
RabbitMQ management API15672 /api/queues/{vhost}/{name}Per objectStatistics can be disabled
Kafka client JMXkafka.consumer:type=consumer-fetch-manager-metrics,client-id=...Per clientNeeds a JMX exporter
kafka_exporterIts own /metricsPer group, topic, partitionPolls the brokers
BurrowHTTP endpointPer group statusSliding-window evaluation
RedisXINFO GROUPS, XPENDING, INFOPer groupYou write the probe

Failure and error attributes Good to know ​

SituationWhat to recordWhere
Handler throwserror.type (class), exception event, span status ErrorConsumer span
Publish failserror.type, span status Error, counter with error.typeProducer span, messaging.client.sent.messages
Broker unreachableProbe up gauge = 0, not zero lagProbe
Lag unknownSeparate unknown gauge, no numeric lagProbe
Message redeliveredredelivered flag, attempt count in logConsumer log
Message parkedReason code on the DLQ recordDLQ

Solving classic problems ​

Broken trace after a broker hop ​

Find the first hop where the traceparent is missing: dump the message headers at the broker, then at the consumer. If the headers are present at the broker and absent in the consumer, the client dropped them; if absent at the broker, the producer never injected them. Fix the carrier or the bridge, then confirm with the offline test, which needs no broker.

An alert that fires on every deploy ​

A rolling restart pauses consumption briefly, depth spikes and a depth alert pages. Replace it with a burn-rate alert on age: a two-minute pause consumes a sliver of the budget. Keep a separate rule for “no consumers for five minutes”.

A backlog that looks fine and is not ​

Depth is flat but the age of the oldest message grows: a poison message is being redelivered forever. Alert on age and on redelivery counters, and route repeated failures to the dead-letter queue.

Measuring an outbox or a database-backed queue ​

A table is also a queue. This query yields depth and oldest age for Laravel's jobs table (unix-second columns) on PostgreSQL; the same shape works for an outbox table with a published_at column.

sql
SELECT queue,
       count(*)                                        AS depth,
       count(*) FILTER (WHERE reserved_at IS NOT NULL) AS in_flight,
       extract(epoch FROM now())
         - min(available_at) FILTER (WHERE reserved_at IS NULL
                                     AND available_at <= extract(epoch FROM now())) AS oldest_ready_age_seconds
FROM jobs
GROUP BY queue;
ProblemFixAdvantageLimit
Trace stops at brokerInject and extract in wrappersWhole path visibleEvery producer and consumer must use it
Batch consumerOne span, a link per messageHonest shapeBackends must render links
Alert noiseBurn-rate alertsPages only on real budget spendNeeds an SLI that exists
Lag lies after a trimUnknown gaugeNo false zerosDashboards need a second panel
PII in logsIds only, redact in the loggerSafer retentionHarder ad-hoc debugging
High-cardinality metricsDestination template, no idsStable costLess per-entity detail

Choosing what to instrument ​

SituationRecommendationExtra techniqueReason
Greenfield service on RabbitMQWrapper with PublishAMQP/ProcessAMQP plus Prometheus pluginAlert on ageHeaders table carries the context
Kafka with a client library offering OpenTelemetry hooksUse the hooks, set links modeBurrow or kafka_exporter for lagLess code to own
Redis StreamsContext as extra fields, own lag probeTreat NULL lag as unknownNo header section, no exporter
Laravel on Redis queuesHorizon, plus Pulse for app-level cardsOpenTelemetry auto-instrumentation if you need tracesBuilt-in dashboards first
Laravel on RabbitMQ or SQSPulse, OpenTelemetry job middlewareBroker-side metricsHorizon supports Redis only
Many small consumersLink mode, destination templateTail samplingCardinality and cost
Regulated dataIds only in logs and baggageCollector redactionAuditable retention
Low trafficAlways-on samplingSkip exemplarsSimplicity

Go ​

Before ​

The publisher writes no headers and the consumer prints the payload. Whatever request produced the message is gone, and the log line can never be joined to anything.

go
// Package main shows async code that is invisible to tracing: the producer
// publishes no headers and the consumer starts from nothing.
package main

import (
	"context"
	"log"
	"os"

	amqp "github.com/rabbitmq/amqp091-go"
)

func publish(ctx context.Context, ch *amqp.Channel, orderID string) error {
	// No traceparent, no message id, no correlation id. Whatever request
	// produced this order is lost the moment the message leaves the process.
	return ch.PublishWithContext(ctx, "orders", "order.created", false, false, amqp.Publishing{
		ContentType: "application/json",
		Body:        []byte(`{"order_id":"` + orderID + `"}`),
	})
}

func consume(ch *amqp.Channel) error {
	deliveries, err := ch.Consume("orders.billing", "", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for d := range deliveries {
		// A fresh context and a log line that cannot be joined to any
		// request, trace or message. It also prints the whole payload.
		log.Printf("handling order message: %s", d.Body)
		_ = d.Ack(false)
	}
	return nil
}

func main() {
	url := os.Getenv("AMQP_URL")
	if url == "" {
		log.Println("set AMQP_URL to run this example")
		return
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	_ = publish(context.Background(), ch, "o-1")
	_ = consume(ch)
}

After ​

Package msgtrace wraps start-span, inject, extract, link, error and log attributes around any carrier. The core is client-independent.

go
// Package msgtrace carries W3C Trace Context through message headers and
// names spans and attributes after the OpenTelemetry messaging semantic
// conventions (status: Development at the time of writing, so the attribute
// names below can still change; pin the version you emit).
package msgtrace

import (
	"context"
	"fmt"
	"log/slog"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/baggage"
	"go.opentelemetry.io/otel/codes"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/trace"
)

const instrumentationName = "academy/messaging-observability"

// Install registers the propagators that read and write `traceparent` and
// `tracestate` (TraceContext) plus `baggage`. Call once in main.
func Install() {
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
	))
}

// Meta describes one messaging operation. Nothing here is payload data.
type Meta struct {
	System         string // messaging.system.name, e.g. "rabbitmq", "kafka"
	Destination    string // messaging.destination.name: queue, topic or stream
	MessageID      string // messaging.message.id
	ConversationID string // messaging.message.conversation_id (correlation id)
	ConsumerGroup  string // messaging.consumer.group.name
	Partition      string // messaging.destination.partition.id
}

// Mode selects how a consumer span relates to the producer span.
type Mode int

const (
	// Link starts a new trace and links to the producer: the convention default.
	Link Mode = iota
	// Child makes the consumer span a child of the producer span. Use only
	// for single messages processed outside another ambient span.
	Child
)

func attrs(m Meta, operationName, operationType string) []attribute.KeyValue {
	kv := []attribute.KeyValue{
		attribute.String("messaging.system.name", m.System),
		attribute.String("messaging.destination.name", m.Destination),
		attribute.String("messaging.operation.name", operationName),
		attribute.String("messaging.operation.type", operationType),
	}
	add := func(k, v string) {
		if v != "" {
			kv = append(kv, attribute.String(k, v))
		}
	}
	add("messaging.message.id", m.MessageID)
	add("messaging.message.conversation_id", m.ConversationID)
	add("messaging.consumer.group.name", m.ConsumerGroup)
	add("messaging.destination.partition.id", m.Partition)
	return kv
}

func tracer() trace.Tracer { return otel.Tracer(instrumentationName) }

// StartSend starts a PRODUCER "send" span and injects its context into the
// carrier. The send span doubles as the message creation context.
func StartSend(ctx context.Context, carrier propagation.TextMapCarrier, operationName string, m Meta) (context.Context, trace.Span) {
	ctx, span := tracer().Start(ctx, operationName+" "+m.Destination,
		trace.WithSpanKind(trace.SpanKindProducer),
		trace.WithAttributes(attrs(m, operationName, "send")...))
	otel.GetTextMapPropagator().Inject(ctx, carrier)
	return ctx, span
}

// StartProcess extracts the creation context and starts a CONSUMER "process"
// span. In Link mode the span is a new root with a link; baggage still flows.
func StartProcess(ctx context.Context, carrier propagation.TextMapCarrier, mode Mode, m Meta) (context.Context, trace.Span) {
	extracted := otel.GetTextMapPropagator().Extract(ctx, carrier)
	opts := []trace.SpanStartOption{
		trace.WithSpanKind(trace.SpanKindConsumer),
		trace.WithAttributes(attrs(m, "process", "process")...),
	}
	name := "process " + m.Destination
	if mode == Child {
		return tracer().Start(extracted, name, opts...)
	}
	creation := trace.SpanContextFromContext(extracted)
	rooted := baggage.ContextWithBaggage(ctx, baggage.FromContext(extracted))
	opts = append(opts, trace.WithNewRoot())
	if creation.IsValid() {
		opts = append(opts, trace.WithLinks(trace.Link{SpanContext: creation}))
	}
	return tracer().Start(rooted, name, opts...)
}

// StartBatchProcess handles a batch: one CONSUMER span that links to every
// message's creation context, because a span can only have one parent.
func StartBatchProcess(ctx context.Context, carriers []propagation.TextMapCarrier, m Meta) (context.Context, trace.Span) {
	var links []trace.Link
	for _, c := range carriers {
		sc := trace.SpanContextFromContext(otel.GetTextMapPropagator().Extract(context.Background(), c))
		if sc.IsValid() {
			links = append(links, trace.Link{SpanContext: sc})
		}
	}
	return tracer().Start(ctx, "process "+m.Destination,
		trace.WithNewRoot(),
		trace.WithSpanKind(trace.SpanKindConsumer),
		trace.WithLinks(links...),
		trace.WithAttributes(attrs(m, "process", "process")...),
		trace.WithAttributes(attribute.Int("messaging.batch.message_count", len(carriers))))
}

// Fail marks a span failed. error.type stays low-cardinality: the Go type
// name, never the message text.
func Fail(span trace.Span, err error) {
	if err == nil {
		return
	}
	span.RecordError(err)
	span.SetStatus(codes.Error, "operation failed")
	span.SetAttributes(attribute.String("error.type", fmt.Sprintf("%T", err)))
}

// LogAttrs returns structured-log attributes that join a log line to its
// trace and message without printing the payload.
func LogAttrs(ctx context.Context, m Meta) []any {
	sc := trace.SpanContextFromContext(ctx)
	out := []any{
		slog.String("messaging.system.name", m.System),
		slog.String("messaging.destination.name", m.Destination),
		slog.String("messaging.message.id", m.MessageID),
	}
	if m.ConversationID != "" {
		out = append(out, slog.String("correlation_id", m.ConversationID))
	}
	if sc.IsValid() {
		out = append(out, slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()))
	}
	return out
}

The carriers adapt each broker's metadata to the OpenTelemetry TextMapCarrier interface.

go
package msgtrace

import (
	"sort"
	"strings"

	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/twmb/franz-go/pkg/kgo"
)

// AMQPHeaders adapts an AMQP 0-9-1 headers table to a TextMapCarrier. Values
// may arrive as string or []byte depending on the publishing client.
type AMQPHeaders amqp.Table

func (h AMQPHeaders) Get(key string) string {
	switch v := h[key].(type) {
	case string:
		return v
	case []byte:
		return string(v)
	}
	return ""
}

func (h AMQPHeaders) Set(key, value string) { h[key] = value }

func (h AMQPHeaders) Keys() []string {
	keys := make([]string, 0, len(h))
	for k := range h {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}

// KafkaHeaders adapts a record's header slice. Set replaces an existing key
// so a record that is produced twice never carries two traceparent headers.
type KafkaHeaders struct{ Headers *[]kgo.RecordHeader }

func (h KafkaHeaders) Get(key string) string {
	for _, rh := range *h.Headers {
		if strings.EqualFold(rh.Key, key) {
			return string(rh.Value)
		}
	}
	return ""
}

func (h KafkaHeaders) Set(key, value string) {
	for i, rh := range *h.Headers {
		if strings.EqualFold(rh.Key, key) {
			(*h.Headers)[i].Value = []byte(value)
			return
		}
	}
	*h.Headers = append(*h.Headers, kgo.RecordHeader{Key: key, Value: []byte(value)})
}

func (h KafkaHeaders) Keys() []string {
	keys := make([]string, 0, len(*h.Headers))
	for _, rh := range *h.Headers {
		keys = append(keys, rh.Key)
	}
	return keys
}

// StreamFields adapts a Redis Streams entry body (field/value pairs). A
// stream entry has no header section, so context rides in ordinary fields.
type StreamFields map[string]any

func (f StreamFields) Get(key string) string {
	switch v := f[key].(type) {
	case string:
		return v
	case []byte:
		return string(v)
	}
	return ""
}

func (f StreamFields) Set(key, value string) { f[key] = value }

func (f StreamFields) Keys() []string {
	keys := make([]string, 0, len(f))
	for k := range f {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}

Metrics use the messaging client metric names; the histogram buckets are explicit, and the attributes are low-cardinality on purpose.

go
// Package msgmetrics records the messaging client metrics defined by the
// OpenTelemetry semantic conventions (Development status): a processing
// duration histogram and sent/consumed counters. Attributes stay low
// cardinality: never a message id, never a user id.
package msgmetrics

import (
	"context"
	"fmt"
	"time"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric"
)

// Recorder owns the instruments.
type Recorder struct {
	processDuration metric.Float64Histogram
	sent            metric.Int64Counter
	consumed        metric.Int64Counter
	messageAge      metric.Float64Histogram
}

// Dim is the low-cardinality dimension set shared by every instrument.
type Dim struct {
	System        string // messaging.system.name
	Destination   string // messaging.destination.name (or its template when names are dynamic)
	ConsumerGroup string // messaging.consumer.group.name
}

// processBuckets in seconds: from a quick handler to a stuck one.
var processBuckets = []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60}

// ageBuckets in seconds: broker wait before processing starts.
var ageBuckets = []float64{0.1, 0.5, 1, 5, 15, 60, 300, 900, 3600}

// New creates the instruments on meter.
func New(meter metric.Meter) (*Recorder, error) {
	r := &Recorder{}
	var err error
	if r.processDuration, err = meter.Float64Histogram("messaging.process.duration",
		metric.WithUnit("s"), metric.WithDescription("Duration of processing operation."),
		metric.WithExplicitBucketBoundaries(processBuckets...)); err != nil {
		return nil, err
	}
	if r.sent, err = meter.Int64Counter("messaging.client.sent.messages",
		metric.WithUnit("{message}"), metric.WithDescription("Number of messages producer attempted to send to the broker.")); err != nil {
		return nil, err
	}
	if r.consumed, err = meter.Int64Counter("messaging.client.consumed.messages",
		metric.WithUnit("{message}"), metric.WithDescription("Number of messages that were delivered to the application.")); err != nil {
		return nil, err
	}
	// Not part of the conventions: this name is ours.
	if r.messageAge, err = meter.Float64Histogram("app.messaging.message_age",
		metric.WithUnit("s"), metric.WithDescription("Time from publish to the start of processing."),
		metric.WithExplicitBucketBoundaries(ageBuckets...)); err != nil {
		return nil, err
	}
	return r, nil
}

func attrs(d Dim, operation string, err error) []attribute.KeyValue {
	kv := []attribute.KeyValue{
		attribute.String("messaging.system.name", d.System),
		attribute.String("messaging.destination.name", d.Destination),
		attribute.String("messaging.operation.name", operation),
	}
	if d.ConsumerGroup != "" {
		kv = append(kv, attribute.String("messaging.consumer.group.name", d.ConsumerGroup))
	}
	if err != nil {
		kv = append(kv, attribute.String("error.type", fmt.Sprintf("%T", err)))
	}
	return kv
}

// Processed records one handler run. Pass the context that carries the
// consumer span: an SDK configured for exemplars then attaches that trace id
// to the bucket the sample lands in.
func (r *Recorder) Processed(ctx context.Context, d Dim, took time.Duration, err error) {
	opt := metric.WithAttributes(attrs(d, "process", err)...)
	r.processDuration.Record(ctx, took.Seconds(), opt)
	r.consumed.Add(ctx, 1, metric.WithAttributes(attrs(d, "process", nil)...))
}

// Sent records one publish attempt, successful or not.
func (r *Recorder) Sent(ctx context.Context, d Dim, err error) {
	r.sent.Add(ctx, 1, metric.WithAttributes(attrs(d, "send", err)...))
}

// Age records how long a message waited, from its publish timestamp.
func (r *Recorder) Age(ctx context.Context, d Dim, publishedAt, now time.Time) {
	if age := now.Sub(publishedAt).Seconds(); age >= 0 {
		r.messageAge.Record(ctx, age, metric.WithAttributes(attrs(d, "process", nil)...))
	}
}

The unit tests need no broker and fix the behaviour described above.

go
package msgtrace

import (
	"context"
	"errors"
	"log/slog"
	"strings"
	"testing"

	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/redis/go-redis/v9"
	"github.com/twmb/franz-go/pkg/kgo"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/baggage"
	"go.opentelemetry.io/otel/propagation"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"
	"go.opentelemetry.io/otel/trace"
)

func setup(t *testing.T, sampler sdktrace.Sampler) *tracetest.SpanRecorder {
	t.Helper()
	rec := tracetest.NewSpanRecorder()
	tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(rec), sdktrace.WithSampler(sampler))
	otel.SetTracerProvider(tp)
	Install()
	t.Cleanup(func() { _ = tp.Shutdown(context.Background()) })
	return rec
}

func attr(s sdktrace.ReadOnlySpan, key string) string {
	for _, kv := range s.Attributes() {
		if string(kv.Key) == key {
			return kv.Value.Emit()
		}
	}
	return ""
}

type fakeChannel struct{ got amqp.Publishing }

func (f *fakeChannel) PublishWithContext(_ context.Context, _, _ string, _, _ bool, msg amqp.Publishing) error {
	f.got = msg
	return nil
}

func TestAMQPRoundTripLinksProducerAndKeepsCorrelationSeparate(t *testing.T) {
	rec := setup(t, sdktrace.AlwaysSample())
	ch := &fakeChannel{}
	m := Meta{MessageID: "m-1", ConversationID: "order-42"}
	if err := PublishAMQP(context.Background(), ch, "orders", "created", m, []byte(`{}`)); err != nil {
		t.Fatal(err)
	}
	tp := AMQPHeaders(ch.got.Headers).Get("traceparent")
	if !strings.HasPrefix(tp, "00-") || !strings.HasSuffix(tp, "-01") {
		t.Fatalf("traceparent = %q", tp)
	}
	if ch.got.CorrelationId != "order-42" || ch.got.MessageId != "m-1" {
		t.Fatalf("ids = %q %q", ch.got.CorrelationId, ch.got.MessageId)
	}
	err := ProcessAMQP(context.Background(), amqp.Delivery{Headers: ch.got.Headers, MessageId: "m-1", CorrelationId: "order-42"},
		"orders.billing", Link, func(context.Context) error { return nil })
	if err != nil {
		t.Fatal(err)
	}
	spans := rec.Ended()
	prod, cons := spans[0], spans[1]
	if prod.SpanKind() != trace.SpanKindProducer || cons.SpanKind() != trace.SpanKindConsumer {
		t.Fatalf("kinds = %v %v", prod.SpanKind(), cons.SpanKind())
	}
	if cons.SpanContext().TraceID() == prod.SpanContext().TraceID() {
		t.Fatal("link mode must start a new trace")
	}
	if len(cons.Links()) != 1 || cons.Links()[0].SpanContext.SpanID() != prod.SpanContext().SpanID() {
		t.Fatalf("links = %+v", cons.Links())
	}
	if prod.Name() != "publish orders" || attr(cons, "messaging.operation.type") != "process" ||
		attr(prod, "messaging.operation.type") != "send" || attr(prod, "messaging.system.name") != "rabbitmq" {
		t.Fatalf("names/attrs: %q %q", prod.Name(), attr(cons, "messaging.operation.type"))
	}
	if attr(cons, "messaging.message.conversation_id") != "order-42" {
		t.Fatal("correlation id must be recorded as conversation id")
	}
}

func TestChildModeSharesTraceAndParent(t *testing.T) {
	rec := setup(t, sdktrace.AlwaysSample())
	h := amqp.Table{}
	_, span := StartSend(context.Background(), AMQPHeaders(h), "publish", Meta{System: "rabbitmq", Destination: "orders"})
	span.End()
	_ = ProcessAMQP(context.Background(), amqp.Delivery{Headers: h}, "orders", Child, func(context.Context) error { return nil })
	spans := rec.Ended()
	if spans[1].Parent().SpanID() != spans[0].SpanContext().SpanID() || len(spans[1].Links()) != 0 {
		t.Fatalf("parent=%v links=%v", spans[1].Parent(), spans[1].Links())
	}
}

func TestBaggageSurvivesLinkMode(t *testing.T) {
	setup(t, sdktrace.AlwaysSample())
	member, _ := baggage.NewMember("tenant", "acme")
	bag, _ := baggage.New(member)
	ctx := baggage.ContextWithBaggage(context.Background(), bag)
	h := amqp.Table{}
	_, span := StartSend(ctx, AMQPHeaders(h), "publish", Meta{System: "rabbitmq", Destination: "orders"})
	span.End()
	if got := AMQPHeaders(h).Get("baggage"); got != "tenant=acme" {
		t.Fatalf("baggage header = %q", got)
	}
	var seen string
	_ = ProcessAMQP(context.Background(), amqp.Delivery{Headers: h}, "orders", Link, func(ctx context.Context) error {
		seen = baggage.FromContext(ctx).Member("tenant").Value()
		return nil
	})
	if seen != "acme" {
		t.Fatalf("baggage in consumer = %q", seen)
	}
}

func TestKafkaHeadersReplaceInsteadOfDuplicate(t *testing.T) {
	setup(t, sdktrace.AlwaysSample())
	rec := &kgo.Record{Topic: "orders", Headers: []kgo.RecordHeader{{Key: "traceparent", Value: []byte("stale")}}}
	_, span := StartSend(context.Background(), KafkaHeaders{&rec.Headers}, "send", Meta{System: "kafka", Destination: "orders"})
	span.End()
	count := 0
	for _, h := range rec.Headers {
		if h.Key == "traceparent" {
			count++
		}
	}
	if count != 1 || string(rec.Headers[0].Value) == "stale" {
		t.Fatalf("headers = %+v", rec.Headers)
	}
}

func TestBatchSpanLinksEveryRecord(t *testing.T) {
	spans := setup(t, sdktrace.AlwaysSample())
	var recs []*kgo.Record
	for i := 0; i < 3; i++ {
		r := &kgo.Record{Topic: "orders"}
		_, s := StartSend(context.Background(), KafkaHeaders{&r.Headers}, "send", Meta{System: "kafka", Destination: "orders"})
		s.End()
		recs = append(recs, r)
	}
	recs = append(recs, &kgo.Record{Topic: "orders"}) // no context: no link, still counted
	if err := ProcessKafkaBatch(context.Background(), recs, "orders", "billing", func(context.Context) error { return nil }); err != nil {
		t.Fatal(err)
	}
	batch := spans.Ended()[3]
	if len(batch.Links()) != 3 || attr(batch, "messaging.batch.message_count") != "4" {
		t.Fatalf("links=%d count=%s", len(batch.Links()), attr(batch, "messaging.batch.message_count"))
	}
}

func TestStreamFieldsCarryContext(t *testing.T) {
	setup(t, sdktrace.AlwaysSample())
	fields := map[string]any{"order_id": "42"}
	_, span := StartSend(context.Background(), StreamFields(fields), "xadd", Meta{System: "redis", Destination: "orders"})
	span.End()
	if StreamFields(fields).Get("traceparent") == "" || fields["order_id"] != "42" {
		t.Fatalf("fields = %v", fields)
	}
	msg := redis.XMessage{ID: "1-0", Values: fields}
	if err := ProcessStream(context.Background(), msg, "orders", "billing", Link, func(context.Context) error { return errors.New("boom") }); err == nil {
		t.Fatal("handler error must propagate")
	}
}

func TestFailureRecordsLowCardinalityErrorType(t *testing.T) {
	rec := setup(t, sdktrace.AlwaysSample())
	_ = ProcessStream(context.Background(), redis.XMessage{ID: "1-0"}, "orders", "g", Link, func(context.Context) error {
		return errors.New("customer 42 card 4111 declined")
	})
	s := rec.Ended()[0]
	if attr(s, "error.type") != "*errors.errorString" || strings.Contains(s.Status().Description, "4111") {
		t.Fatalf("error.type=%q status=%q", attr(s, "error.type"), s.Status().Description)
	}
}

func TestUnsampledDecisionTravelsInFlags(t *testing.T) {
	setup(t, sdktrace.NeverSample())
	h := amqp.Table{}
	_, span := StartSend(context.Background(), AMQPHeaders(h), "publish", Meta{System: "rabbitmq", Destination: "orders"})
	span.End()
	if tp := AMQPHeaders(h).Get("traceparent"); !strings.HasSuffix(tp, "-00") {
		t.Fatalf("traceparent = %q", tp)
	}
}

func TestMalformedTraceparentIsIgnored(t *testing.T) {
	rec := setup(t, sdktrace.AlwaysSample())
	h := amqp.Table{"traceparent": "00-00000000000000000000000000000000-0000000000000000-01"}
	_ = ProcessAMQP(context.Background(), amqp.Delivery{Headers: h}, "orders", Link, func(context.Context) error { return nil })
	if s := rec.Ended()[0]; len(s.Links()) != 0 {
		t.Fatalf("links = %v", s.Links())
	}
}

func TestAMQPHeadersAcceptByteValues(t *testing.T) {
	if AMQPHeaders(amqp.Table{"traceparent": []byte("abc")}).Get("traceparent") != "abc" {
		t.Fatal("[]byte header not read")
	}
	var _ propagation.TextMapCarrier = AMQPHeaders{}
}

func TestLogAttrsHaveIDsButNoPayload(t *testing.T) {
	setup(t, sdktrace.AlwaysSample())
	ctx, span := tracer().Start(context.Background(), "x")
	defer span.End()
	var sb strings.Builder
	log := slog.New(slog.NewJSONHandler(&sb, nil))
	log.InfoContext(ctx, "handled", LogAttrs(ctx, Meta{System: "kafka", Destination: "orders", MessageID: "m-1", ConversationID: "c-9"})...)
	out := sb.String()
	for _, want := range []string{"trace_id", "span_id", `"messaging.message.id":"m-1"`, `"correlation_id":"c-9"`} {
		if !strings.Contains(out, want) {
			t.Fatalf("missing %s in %s", want, out)
		}
	}
}

type fakeProducer struct{}

func (fakeProducer) ProduceSync(_ context.Context, rs ...*kgo.Record) kgo.ProduceResults {
	return kgo.ProduceResults{{Record: rs[0]}}
}

func TestProduceKafkaInjectsHeader(t *testing.T) {
	setup(t, sdktrace.AlwaysSample())
	rec := &kgo.Record{Topic: "orders", Value: []byte("{}")}
	if err := ProduceKafka(context.Background(), fakeProducer{}, rec, Meta{MessageID: "m"}); err != nil {
		t.Fatal(err)
	}
	if (KafkaHeaders{&rec.Headers}).Get("traceparent") == "" {
		t.Fatal("no traceparent header")
	}
}

type fakeStream struct{}

func (fakeStream) XAdd(ctx context.Context, a *redis.XAddArgs) *redis.StringCmd {
	return redis.NewStringResult("1-0", nil)
}

func TestXAddTracedKeepsBusinessFields(t *testing.T) {
	setup(t, sdktrace.AlwaysSample())
	id, err := XAddTraced(context.Background(), fakeStream{}, "orders", Meta{}, map[string]any{"order_id": "42"})
	if err != nil || id != "1-0" {
		t.Fatal(id, err)
	}
}

A tiny program shows propagation in isolation.

go
// Command demo needs no broker. It injects a traceparent into AMQP-style
// headers, extracts it in a consumer, and prints how the two spans relate.
package main

import (
	"context"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"
	"go.opentelemetry.io/otel"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"

	"academy/messaging-observability/after/msgtrace"
)

func main() {
	// The SDK generates the ids; without it every span context is invalid and
	// nothing is injected. The sampler decides here, and the flag travels.
	rec := tracetest.NewSpanRecorder()
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSpanProcessor(rec),
		sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))),
	)
	defer func() { _ = tp.Shutdown(context.Background()) }()
	otel.SetTracerProvider(tp)
	msgtrace.Install()

	headers := amqp.Table{}
	_, send := msgtrace.StartSend(context.Background(), msgtrace.AMQPHeaders(headers), "publish",
		msgtrace.Meta{System: "rabbitmq", Destination: "orders", MessageID: "m-1"})
	send.End()
	fmt.Println("traceparent:", msgtrace.AMQPHeaders(headers).Get("traceparent"))

	_ = msgtrace.ProcessAMQP(context.Background(), amqp.Delivery{Headers: headers, MessageId: "m-1"},
		"orders.billing", msgtrace.Link, func(context.Context) error { return nil })

	spans := rec.Ended()
	producer, consumer := spans[0], spans[1]
	fmt.Println("same trace id:", producer.SpanContext().TraceID() == consumer.SpanContext().TraceID())
	fmt.Println("consumer links to producer:", len(consumer.Links()) == 1 &&
		consumer.Links()[0].SpanContext.SpanID() == producer.SpanContext().SpanID())
}

The Go angle ​

go.opentelemetry.io/otel splits API and SDK. Libraries call only the API; without an SDK installed in main, every span context is invalid and Inject writes nothing. propagation.TextMapCarrier has three methods (Get, Set, Keys), so any header-like structure can carry context. The module pins go 1.24 with OpenTelemetry 1.38.0, franz-go 1.19.5 and kadm 1.16.1; newer releases of kadm and kmsg raise the go directive, so the minimum that works is pinned. The franz-go ecosystem also ships kotel, a plugin that adds tracing hooks to a client; the snippet writes the header carrier by hand so the behaviour is visible and testable, but check kotel first if you want less code: its documentation says hooks create and close the “publish” and “receive” spans, while the “process” span needs a manual call (pkg.go.dev kotel).

Laravel ​

Before ​

A job logs a full customer array and has no id that ties it to the request.

php
<?php

namespace App\Jobs;

use App\Services\InvoiceGateway;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

// The request that dispatched this job is gone by the time it runs. The log
// line below has no id that ties it to that request, to the dispatching
// service, or to the message in the broker, and it prints a full payload.
class SendInvoice implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $orderId, public array $customer) {}

    public function handle(InvoiceGateway $gateway): void
    {
        Log::info('sending invoice', ['order' => $this->orderId, 'customer' => $this->customer]);

        $gateway->send($this->orderId);
    }
}

After ​

Laravel's Context facade is captured when a job is dispatched and restored when it runs; visible entries are appended to every log line. The middleware sets correlation_id and trace_id once, at the HTTP edge.

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use OpenTelemetry\API\Trace\Span;
use Symfony\Component\HttpFoundation\Response;

// Laravel's Context facade is captured when a job is dispatched and hydrated
// again when it runs, and it is added to every log line. Visible entries
// (add) appear in logs; hidden entries (addHidden) travel without being logged.
class CorrelationMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        Context::add('correlation_id', $request->header('X-Correlation-Id') ?? (string) Str::uuid());

        // The trace id is for joining logs to traces; it is not a correlation id.
        $traceId = Span::getCurrent()->getContext()->getTraceId();
        if ($traceId !== '00000000000000000000000000000000') {
            Context::add('trace_id', $traceId);
        }

        return $next($request);
    }
}

For trace context, a service provider writes the propagator output into hidden context when a job is dispatched (the callback receives the repository and must change only it).

php
<?php

namespace App\Providers;

use Illuminate\Log\Context\Repository;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\ServiceProvider;
use OpenTelemetry\API\Globals;

// Use this OR the OpenTelemetry Laravel auto-instrumentation, never both:
// that package already injects the context into the job payload.
class TraceContextBridge extends ServiceProvider
{
    public const PREFIX = 'otel.';

    public function boot(): void
    {
        // Runs when a job is dispatched. Only touch the repository argument,
        // as the Laravel documentation requires inside this callback.
        Context::dehydrating(function (Repository $context): void {
            $carrier = [];
            // Globals::propagator() is what OTEL_PROPAGATORS configured:
            // traceparent, tracestate and baggage by default.
            Globals::propagator()->inject($carrier);

            foreach ($carrier as $key => $value) {
                $context->addHidden(self::PREFIX.$key, $value);
            }
        });
    }
}

The job middleware reads it back, starts a CONSUMER span linked to the producer and ends it in finally.

php
<?php

namespace App\Jobs\Middleware;

use App\Providers\TraceContextBridge;
use Closure;
use Illuminate\Support\Facades\Context;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use Throwable;

// Attach with: public function middleware(): array { return [new RestoreTraceContext]; }
// The job must use InteractsWithQueue (Queueable jobs do) so $job->job is set.
class RestoreTraceContext
{
    public function handle(object $job, Closure $next): mixed
    {
        $carrier = [];
        foreach (Context::allHidden() as $key => $value) {
            if (str_starts_with($key, TraceContextBridge::PREFIX)) {
                $carrier[substr($key, strlen(TraceContextBridge::PREFIX))] = $value;
            }
        }

        // The producer's span context: link to it, do not parent under it.
        $creation = Span::fromContext(Globals::propagator()->extract($carrier))->getContext();
        $queueJob = $job->job;
        $connection = $queueJob->getConnectionName();

        $builder = Globals::tracerProvider()->getTracer('app.queue')
            ->spanBuilder('process '.$queueJob->getQueue())
            ->setSpanKind(SpanKind::KIND_CONSUMER)
            ->setParent(false)
            ->setAttribute('messaging.system.name', (string) config("queue.connections.$connection.driver"))
            ->setAttribute('messaging.destination.name', $queueJob->getQueue())
            ->setAttribute('messaging.operation.name', 'process')
            ->setAttribute('messaging.operation.type', 'process')
            ->setAttribute('messaging.message.id', $queueJob->uuid());

        if ($creation->isValid()) {
            $builder->addLink($creation);
        }

        $span = $builder->startSpan();
        $scope = $span->activate();

        try {
            return $next($job);
        } catch (Throwable $e) {
            $span->recordException($e);
            $span->setStatus(StatusCode::STATUS_ERROR);

            throw $e;
        } finally {
            $scope->detach();
            $span->end();
        }
    }
}

The job itself carries only an identifier and logs ids only.

php
<?php

namespace App\Jobs;

use App\Jobs\Middleware\RestoreTraceContext;
use App\Services\InvoiceGateway;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

// Carry identifiers, not data: the job holds the order id and loads the rest.
class SendInvoice implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $orderId) {}

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [new RestoreTraceContext];
    }

    public function handle(InvoiceGateway $gateway): void
    {
        // correlation_id and trace_id come from the hydrated Context and are
        // appended to this line automatically. No payload, no personal data.
        Log::info('sending invoice', [
            'order' => $this->orderId,
            'job_uuid' => $this->job->uuid(),
            'attempt' => $this->job->attempts(),
        ]);

        $gateway->send($this->orderId);
    }
}

The Laravel angle ​

You have three layers. Horizon is the dashboard for Redis queues: throughput, runtime, failures, wait times. Its documentation says to schedule horizon:snapshot every five minutes to populate the metrics graphs, and config/horizon.php waits sets the “long wait” threshold per connection and queue (a value of 0 disables it).

php
<?php

// routes/console.php: Horizon's metrics dashboard stays empty until this runs.
use Illuminate\Support\Facades\Schedule;

Schedule::command('horizon:snapshot')->everyFiveMinutes();
php
<?php

namespace App\Providers;

use Laravel\Horizon\Horizon;
use Laravel\Horizon\HorizonApplicationServiceProvider;

// Horizon watches Redis-backed queues only. It notifies when a queue's wait
// exceeds the "waits" threshold in config/horizon.php, for example:
//   'waits' => ['redis:default' => 60, 'redis:payments' => 15],
// and a threshold of 0 disables the alert for that queue.
class HorizonServiceProvider extends HorizonApplicationServiceProvider
{
    public function boot(): void
    {
        parent::boot();

        Horizon::routeSlackNotificationsTo((string) env('HORIZON_SLACK_WEBHOOK'), '#queue-alerts');
        Horizon::routeMailNotificationsTo((string) env('HORIZON_ALERT_MAIL'));
    }
}

Pulse adds application cards. Its Queues card shows jobs queued, processing, processed, released and failed; the Queues and Slow Jobs recorders accept a sample rate and ignore patterns, and the Redis ingest driver sends entries to a Redis stream instead of writing them straight to the database. Telescope is a development companion: its job watcher records job data and status; the docs warn that without pruning telescope_entries grows quickly and that production must set APP_ENV=production. Use it locally, not as the production metric source.

For distributed traces, the OpenTelemetry PHP Laravel instrumentation (package open-telemetry/opentelemetry-auto-laravel) hooks the queue: I read its source on the main branch, where Queue::createPayloadArray injects context into the job payload and the worker's process hook extracts it and starts a CONSUMER span named process {queue}. It sets the extracted context as the parent unless the job implements TracingLinked (link and new root) or TracingIsolated (no relationship). Use that package or the manual bridge, not both. The extension also needs OTEL_PHP_AUTOLOAD_ENABLED=true and an exporter configuration; installing the extension alone generates no traces, as the OpenTelemetry page says.

Broker differences ​

RabbitMQ ​

Context rides in the headers table of the message properties; message_id and correlation_id are separate properties. The Go wrapper starts a PRODUCER span named publish {exchange}, injects, and publishes persistent messages.

go
package msgtrace

import (
	"context"

	amqp "github.com/rabbitmq/amqp091-go"
)

// AMQPPublisher is the one method of *amqp.Channel used here.
type AMQPPublisher interface {
	PublishWithContext(ctx context.Context, exchange, key string, mandatory, immediate bool, msg amqp.Publishing) error
}

// PublishAMQP publishes with a PRODUCER span. MessageId identifies this
// message; CorrelationId carries the business conversation, not the trace.
func PublishAMQP(ctx context.Context, ch AMQPPublisher, exchange, key string, m Meta, body []byte) error {
	m.System, m.Destination = "rabbitmq", exchange
	headers := amqp.Table{}
	ctx, span := StartSend(ctx, AMQPHeaders(headers), "publish", m)
	defer span.End()
	err := ch.PublishWithContext(ctx, exchange, key, false, false, amqp.Publishing{
		ContentType:   "application/json",
		DeliveryMode:  amqp.Persistent,
		MessageId:     m.MessageID,
		CorrelationId: m.ConversationID,
		Headers:       headers,
		Body:          body,
	})
	Fail(span, err)
	return err
}

// ProcessAMQP runs handle inside a CONSUMER span built from the delivery.
func ProcessAMQP(ctx context.Context, d amqp.Delivery, queue string, mode Mode, handle func(context.Context) error) error {
	m := Meta{System: "rabbitmq", Destination: queue, MessageID: d.MessageId, ConversationID: d.CorrelationId}
	ctx, span := StartProcess(ctx, AMQPHeaders(d.Headers), mode, m)
	defer span.End()
	err := handle(ctx)
	Fail(span, err)
	return err
}

For metrics, enable the rabbitmq_prometheus plugin; it serves on port 15692. The default /metrics is aggregated, so it cannot tell you which queue is deep. Use /metrics/detailed?family=queue_coarse_metrics to get rabbitmq_detailed_queue_messages_ready, rabbitmq_detailed_queue_messages_unacked and rabbitmq_detailed_queue_messages (their sum), plus the consumers family. The management API on port 15672 returns messages, messages_ready and messages_unacknowledged per queue; its documentation recommends Prometheus for long-term storage and says statistics can be disabled, in which case the fields are absent (the probe treats that as unknown). redelivered is a flag on each delivery and redeliver a rate in message stats. RabbitMQ has no first-class “oldest message age”: stamp the AMQP timestamp property at publish and record the age at consume, as msgmetrics.Age does.

go
package lagprobe

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
)

// queueStats holds the queue fields of GET /api/queues/{vhost}/{name} that the
// management plugin documents: messages, messages_ready, messages_unacknowledged.
type queueStats struct {
	Messages  *float64 `json:"messages"`
	Ready     *float64 `json:"messages_ready"`
	Unacked   *float64 `json:"messages_unacknowledged"`
	Consumers *float64 `json:"consumers"`
}

// RabbitSamples reads ready, unacked and consumer counts for one queue. A
// field that is absent (for example when statistics are disabled) yields no
// sample rather than a misleading zero.
func RabbitSamples(ctx context.Context, client *http.Client, base, vhost, queue, user, pass string) ([]Sample, error) {
	endpoint := fmt.Sprintf("%s/api/queues/%s/%s", base, url.PathEscape(vhost), url.PathEscape(queue))
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
	if err != nil {
		return nil, err
	}
	req.SetBasicAuth(user, pass)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("management API returned %d", resp.StatusCode)
	}
	var q queueStats
	if err := json.NewDecoder(resp.Body).Decode(&q); err != nil {
		return nil, err
	}
	labels := map[string]string{"queue": queue, "vhost": vhost}
	var out []Sample
	add := func(name, help string, v *float64) {
		if v != nil {
			out = append(out, Sample{name, help, labels, *v})
		}
	}
	add(NameReady, "Messages ready to be delivered to consumers", q.Ready)
	add(NameUnacked, "Messages delivered to consumers but not yet acknowledged", q.Unacked)
	add(NameConsumers, "Consumers attached to the queue", q.Consumers)
	return out, nil
}

Laravel on RabbitMQ gets queue sizes the same way, through the management API with the HTTP client.

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

// The management API reports ready and unacknowledged messages separately,
// which queue size() on a Laravel connection cannot do.
class RabbitMqLag extends Command
{
    protected $signature = 'mq:lag:rabbit {queue} {--vhost=/} {--max-ready=10000}';

    protected $description = 'Print ready and unacked messages for a RabbitMQ queue';

    public function handle(): int
    {
        $queue = rawurlencode((string) $this->argument('queue'));
        $vhost = rawurlencode((string) $this->option('vhost'));

        $stats = Http::withBasicAuth((string) config('services.rabbitmq.user'), (string) config('services.rabbitmq.password'))
            ->timeout(5)
            ->get(config('services.rabbitmq.api')."/api/queues/{$vhost}/{$queue}")
            ->throw()
            ->json();

        // Statistics can be disabled; an absent field is "unknown", not zero.
        $ready = $stats['messages_ready'] ?? null;
        $unacked = $stats['messages_unacknowledged'] ?? null;
        $this->line('ready='.($ready ?? 'unknown').' unacked='.($unacked ?? 'unknown').' consumers='.($stats['consumers'] ?? 'unknown'));

        return $ready !== null && $ready > (int) $this->option('max-ready') ? self::FAILURE : self::SUCCESS;
    }
}

Kafka ​

Context rides in record headers, which are byte values; a retried producer must replace, not append, the header. The Go wrapper uses a header carrier with replace semantics.

go
package msgtrace

import (
	"context"

	"github.com/twmb/franz-go/pkg/kgo"
	"go.opentelemetry.io/otel/propagation"
)

// KafkaProducer is the one method of *kgo.Client used here.
type KafkaProducer interface {
	ProduceSync(ctx context.Context, rs ...*kgo.Record) kgo.ProduceResults
}

// ProduceKafka injects the context into the record headers and produces.
func ProduceKafka(ctx context.Context, cl KafkaProducer, rec *kgo.Record, m Meta) error {
	m.System, m.Destination = "kafka", rec.Topic
	ctx, span := StartSend(ctx, KafkaHeaders{&rec.Headers}, "send", m)
	defer span.End()
	err := cl.ProduceSync(ctx, rec).FirstErr()
	Fail(span, err)
	return err
}

// ProcessKafka runs handle inside a CONSUMER span built from the record.
func ProcessKafka(ctx context.Context, rec *kgo.Record, group string, mode Mode, handle func(context.Context) error) error {
	m := Meta{System: "kafka", Destination: rec.Topic, ConsumerGroup: group}
	ctx, span := StartProcess(ctx, KafkaHeaders{&rec.Headers}, mode, m)
	defer span.End()
	err := handle(ctx)
	Fail(span, err)
	return err
}

// ProcessKafkaBatch is one span for a poll result, linked to every record.
func ProcessKafkaBatch(ctx context.Context, recs []*kgo.Record, topic, group string, handle func(context.Context) error) error {
	carriers := make([]propagation.TextMapCarrier, len(recs))
	for i, r := range recs {
		carriers[i] = KafkaHeaders{&r.Headers}
	}
	ctx, span := StartBatchProcess(ctx, carriers, Meta{System: "kafka", Destination: topic, ConsumerGroup: group})
	defer span.End()
	err := handle(ctx)
	Fail(span, err)
	return err
}

Kafka's own documentation lists the client metric records-lag-max under kafka.consumer:type=consumer-fetch-manager-metrics,client-id={client-id} and describes it as “Number of messages the consumer lags behind the producer by. Published by the consumer, not broker.” The reference table adds that this value is based on the current offset, not the committed one, and a per-partition records-lag variant exists. Because it is published by the consumer, a dead consumer publishes nothing: pair it with a broker-side view. kafka_exporter computes kafka_consumergroup_lag and kafka_consumergroup_lag_sum from the brokers; Burrow evaluates committed offsets over a sliding window with “NO THRESHOLDS”; kafka-consumer-groups.sh --describe --group my-group prints CURRENT-OFFSET, LOG-END-OFFSET and LAG. The Go probe uses the kadm admin client and reports -1 as unknown. Age needs the timestamp of the record at the committed offset or a consumer-side histogram.

go
package lagprobe

import (
	"context"
	"strconv"

	"github.com/twmb/franz-go/pkg/kadm"
)

// KafkaSamples converts kadm's per-partition lag (log end offset minus the
// group's committed offset). kadm reports Lag = -1 when the commit or the
// end-offset lookup failed; that is "unknown", never zero and never negative.
func KafkaSamples(lags kadm.DescribedGroupLags) []Sample {
	var out []Sample
	for _, gl := range lags.Sorted() {
		for topic, parts := range gl.Lag {
			for partition, l := range parts {
				labels := map[string]string{"group": gl.Group, "topic": topic, "partition": strconv.Itoa(int(partition))}
				if l.Lag < 0 || l.Err != nil {
					out = append(out, Sample{NameLagUnknown, "Lag could not be determined (1 = unknown)", labels, 1})
					continue
				}
				out = append(out, Sample{NameLag, "Records the group has not yet committed past the log end", labels, float64(l.Lag)})
			}
		}
	}
	return out
}

// KafkaProbe asks the brokers through the admin API. It uses the group's
// committed offsets, so it measures what restart would redo, not what the
// consumer has fetched in memory (that is records-lag-max on the client).
func KafkaProbe(ctx context.Context, adm *kadm.Client, groups ...string) ([]Sample, error) {
	lags, err := adm.Lag(ctx, groups...)
	if err != nil {
		return nil, err
	}
	return KafkaSamples(lags), nil
}

In Laravel, mateusjunges/laravel-kafka documents withHeaders for publishing and getHeaders on the consumed message; lag comes from kafka_exporter.

php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
use OpenTelemetry\API\Globals;

// Record headers carry the trace context, exactly like the franz-go example.
final class KafkaTraced
{
    public function publish(int $orderId, string $messageId): void
    {
        $carrier = [];
        Globals::propagator()->inject($carrier);

        Kafka::publish()
            ->onTopic('orders')
            ->withKafkaKey((string) $orderId)
            ->withHeaders($carrier + ['message_id' => $messageId])
            ->withBody(['order_id' => $orderId])
            ->send();
    }

    public function __invoke(ConsumerMessage $message, MessageConsumer $consumer): void
    {
        $headers = $message->getHeaders() ?? [];

        // Extract with Globals::propagator()->extract($headers) to link to the producer.
        Log::info('order event received', [
            'message_id' => $headers['message_id'] ?? null,
            'partition' => $message->getPartition(),
            'offset' => $message->getOffset(),
        ]);
    }
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

// Lag is computed outside the consumers. danielqsj/kafka_exporter publishes
// kafka_consumergroup_lag per group, topic and partition; this command reads
// that endpoint so a deploy script or scheduled check can gate on it.
class KafkaLag extends Command
{
    protected $signature = 'mq:lag:kafka {group} {--max=10000}';

    protected $description = 'Fail when a Kafka consumer group is further behind than --max records';

    public function handle(): int
    {
        $text = Http::timeout(5)->get((string) config('services.kafka_exporter.url'))->throw()->body();
        $group = (string) $this->argument('group');
        $worst = 0;

        foreach (explode("\n", $text) as $line) {
            if (! str_starts_with($line, 'kafka_consumergroup_lag{')) {
                continue;
            }
            if (! str_contains($line, 'consumergroup="'.$group.'"')) {
                continue;
            }
            $worst = max($worst, (int) substr(strrchr($line, ' '), 1));
        }

        $this->line("max partition lag for {$group}: {$worst}");

        return $worst > (int) $this->option('max') ? self::FAILURE : self::SUCCESS;
    }
}

Redis Streams ​

A stream entry has no header section, so the trace context is two or three extra fields. Pick field names that cannot collide with the business schema, or prefix them.

go
package msgtrace

import (
	"context"

	"github.com/redis/go-redis/v9"
)

// StreamAppender is the one method of redis.Cmdable used to publish.
type StreamAppender interface {
	XAdd(ctx context.Context, a *redis.XAddArgs) *redis.StringCmd
}

// XAddTraced appends an entry whose fields include the trace context.
func XAddTraced(ctx context.Context, rdb StreamAppender, stream string, m Meta, fields map[string]any) (string, error) {
	m.System, m.Destination = "redis", stream
	values := StreamFields{}
	for k, v := range fields {
		values[k] = v
	}
	ctx, span := StartSend(ctx, values, "xadd", m)
	defer span.End()
	id, err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: map[string]any(values)}).Result()
	Fail(span, err)
	return id, err
}

// ProcessStream runs handle inside a CONSUMER span built from the entry.
func ProcessStream(ctx context.Context, msg redis.XMessage, stream, group string, mode Mode, handle func(context.Context) error) error {
	m := Meta{System: "redis", Destination: stream, ConsumerGroup: group, MessageID: msg.ID}
	ctx, span := StartProcess(ctx, StreamFields(msg.Values), mode, m)
	defer span.End()
	err := handle(ctx)
	Fail(span, err)
	return err
}

XINFO GROUPS returns, per group, pending (the PEL size), last-delivered-id, entries-read and lag. The Redis documentation defines lag as the number of entries still waiting to be delivered to the group, “or a NULL when that number can't be determined”. NULL happens after XDEL, trimming or an arbitrary XGROUP CREATE/SETID id; go-redis maps it to -1. XPENDING key group returns the pending count, the lowest and highest pending ids and a count per consumer; the extended form with IDLE shows how long each entry has been idle. The oldest undelivered entry is the first one after last-delivered-id (XRANGE with an exclusive start, Redis 6.2 or newer), and its id carries the creation time in milliseconds.

go
package lagprobe

import (
	"context"
	"strconv"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

// StreamReader is the subset of redis.Cmdable the probe needs.
type StreamReader interface {
	XInfoGroups(ctx context.Context, key string) *redis.XInfoGroupsCmd
	XRangeN(ctx context.Context, stream, start, stop string, count int64) *redis.XMessageSliceCmd
}

// EntryTime returns the creation time encoded in a stream ID ("ms-seq").
func EntryTime(id string) (time.Time, bool) {
	ms, _, _ := strings.Cut(id, "-")
	n, err := strconv.ParseInt(ms, 10, 64)
	if err != nil || n < 0 {
		return time.Time{}, false
	}
	return time.UnixMilli(n), true
}

// RedisSamples reports, per consumer group: lag (entries not yet delivered),
// pending (delivered, unacknowledged) and the age of the oldest undelivered
// entry. go-redis returns Lag = -1 when Redis reports NULL, which happens
// after XDEL or trimming broke the group's read counter; that is "unknown".
func RedisSamples(ctx context.Context, rdb StreamReader, stream string, now time.Time) ([]Sample, error) {
	groups, err := rdb.XInfoGroups(ctx, stream).Result()
	if err != nil {
		return nil, err
	}
	var out []Sample
	for _, g := range groups {
		labels := map[string]string{"stream": stream, "group": g.Name}
		out = append(out, Sample{NameUnacked, "Entries in the group's pending entries list", labels, float64(g.Pending)})
		if g.Lag < 0 {
			out = append(out, Sample{NameLagUnknown, "Lag could not be determined (1 = unknown)", labels, 1})
		} else {
			out = append(out, Sample{NameLag, "Entries added to the stream but not yet delivered to the group", labels, float64(g.Lag)})
		}
		// First entry after last-delivered-id: the oldest one nobody has seen.
		// The exclusive range start "(" needs Redis 6.2 or newer.
		next, err := rdb.XRangeN(ctx, stream, "("+g.LastDeliveredID, "+", 1).Result()
		if err != nil {
			return nil, err
		}
		age := 0.0
		if len(next) == 1 {
			if t, ok := EntryTime(next[0].ID); ok && now.After(t) {
				age = now.Sub(t).Seconds()
			}
		}
		out = append(out, Sample{NameOldestAge, "Age of the oldest entry not yet delivered to the group", labels, age})
	}
	return out, nil
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use OpenTelemetry\API\Globals;

// Stream entries are flat field/value pairs, so the context is extra fields.
final class RedisStreamTraced
{
    public function publish(string $stream, string $messageId, array $fields): string
    {
        $carrier = [];
        Globals::propagator()->inject($carrier);

        return Redis::xadd($stream, '*', $fields + $carrier + ['message_id' => $messageId]);
    }

    /** @param array<string,string> $fields one entry's fields from XREADGROUP */
    public function handle(string $entryId, array $fields): void
    {
        // Extract with Globals::propagator()->extract($fields) to link to the producer.
        Log::info('stream entry received', [
            'stream_entry' => $entryId,
            'message_id' => $fields['message_id'] ?? null,
        ]);
    }
}
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

// Assumes the phpredis client, whose XINFO GROUPS reply is a list of
// associative arrays; Predis returns a different shape.
class RedisStreamLag extends Command
{
    protected $signature = 'mq:lag:redis {stream}';

    protected $description = 'Print stream length, group lag and PEL size';

    public function handle(): int
    {
        $stream = (string) $this->argument('stream');
        $this->line("length={$stream}:".Redis::xlen($stream));

        foreach (Redis::xinfo('GROUPS', $stream) as $group) {
            // lag is null after XDEL or trimming broke the group's read
            // counter. That means "unknown", never zero.
            $lag = $group['lag'] === null ? 'unknown' : (string) $group['lag'];
            $this->line("group={$group['name']} lag={$lag} pending={$group['pending']} consumers={$group['consumers']}");
        }

        return self::SUCCESS;
    }
}

The probe binary joins the three brokers behind one /metrics endpoint and exits cleanly when no environment variables are set.

go
// Command lagprobe exposes broker backlog as Prometheus text-format gauges.
// It starts only the probes whose environment variables are set.
package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
	"github.com/twmb/franz-go/pkg/kadm"
	"github.com/twmb/franz-go/pkg/kgo"

	"academy/messaging-observability/after/lagprobe"
)

type probe struct {
	name string
	run  func(context.Context) ([]lagprobe.Sample, error)
}

func main() {
	var probes []probe
	if brokers := os.Getenv("KAFKA_BROKERS"); brokers != "" {
		cl, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...))
		if err != nil {
			log.Fatal(err)
		}
		defer cl.Close()
		adm, group := kadm.NewClient(cl), os.Getenv("KAFKA_GROUP")
		probes = append(probes, probe{"kafka", func(ctx context.Context) ([]lagprobe.Sample, error) {
			return lagprobe.KafkaProbe(ctx, adm, group)
		}})
	}
	if base := os.Getenv("RABBITMQ_API"); base != "" {
		user, pass, queue := os.Getenv("RABBITMQ_USER"), os.Getenv("RABBITMQ_PASS"), os.Getenv("RABBITMQ_QUEUE")
		client := &http.Client{Timeout: 4 * time.Second}
		probes = append(probes, probe{"rabbitmq", func(ctx context.Context) ([]lagprobe.Sample, error) {
			return lagprobe.RabbitSamples(ctx, client, base, "/", queue, user, pass)
		}})
	}
	if addr := os.Getenv("REDIS_ADDR"); addr != "" {
		rdb, stream := redis.NewClient(&redis.Options{Addr: addr}), os.Getenv("REDIS_STREAM")
		defer rdb.Close()
		probes = append(probes, probe{"redis", func(ctx context.Context) ([]lagprobe.Sample, error) {
			return lagprobe.RedisSamples(ctx, rdb, stream, time.Now())
		}})
	}
	if len(probes) == 0 {
		log.Println("set KAFKA_BROKERS, RABBITMQ_API or REDIS_ADDR to run this example")
		return
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
		defer cancel()
		var all []lagprobe.Sample
		for _, p := range probes {
			samples, err := p.run(ctx)
			up := 1.0
			if err != nil {
				log.Printf("probe %s failed: %v", p.name, err) // never log credentials or payloads
				up = 0
			}
			all = append(all, lagprobe.Sample{Name: lagprobe.NameProbeUp, Help: "1 when the last probe succeeded",
				Labels: map[string]string{"broker": p.name}, Value: up})
			all = append(all, samples...)
		}
		w.Header().Set("Content-Type", "text/plain; version=0.0.4")
		_ = lagprobe.WriteExposition(w, all)
	})
	srv := &http.Server{Addr: ":9101", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

The exposition code escapes label values and sorts samples so scrapes are stable.

go
// Package lagprobe turns broker-specific backlog numbers into Prometheus
// gauges. Each broker reports "work waiting" and "work delivered but not
// settled"; the probes keep those two ideas under one metric vocabulary.
package lagprobe

import (
	"fmt"
	"io"
	"sort"
	"strconv"
	"strings"
)

// Sample is one gauge line of the Prometheus text exposition format.
type Sample struct {
	Name   string
	Help   string
	Labels map[string]string
	Value  float64
}

// Metric names shared by every broker.
const (
	NameLag        = "messaging_consumer_lag_records"
	NameOldestAge  = "messaging_oldest_undelivered_age_seconds"
	NameReady      = "messaging_queue_ready_messages"
	NameUnacked    = "messaging_queue_unacked_messages"
	NameConsumers  = "messaging_queue_consumers"
	NameLagUnknown = "messaging_consumer_lag_unknown"
	NameProbeUp    = "messaging_probe_up"
)

var escaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`)

func labelString(l map[string]string) string {
	keys := make([]string, 0, len(l))
	for k := range l {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	parts := make([]string, 0, len(keys))
	for _, k := range keys {
		parts = append(parts, fmt.Sprintf(`%s="%s"`, k, escaper.Replace(l[k])))
	}
	return strings.Join(parts, ",")
}

// WriteExposition writes samples grouped by name, deterministically ordered,
// with one HELP and one TYPE line per name.
func WriteExposition(w io.Writer, samples []Sample) error {
	sorted := append([]Sample(nil), samples...)
	sort.SliceStable(sorted, func(i, j int) bool {
		if sorted[i].Name != sorted[j].Name {
			return sorted[i].Name < sorted[j].Name
		}
		return labelString(sorted[i].Labels) < labelString(sorted[j].Labels)
	})
	last := ""
	for _, s := range sorted {
		if s.Name != last {
			if _, err := fmt.Fprintf(w, "# HELP %s %s\n# TYPE %s gauge\n", s.Name, s.Help, s.Name); err != nil {
				return err
			}
			last = s.Name
		}
		if _, err := fmt.Fprintf(w, "%s{%s} %s\n", s.Name, labelString(s.Labels), strconv.FormatFloat(s.Value, 'g', -1, 64)); err != nil {
			return err
		}
	}
	return nil
}
FeatureRabbitMQKafkaRedis Streams
Context carrierheaders tableRecord headersExtra stream fields
Message idmessage_id propertyTopic, partition, offsetStream id
Correlation idcorrelation_id propertyHeaderField
Built-in metrics endpointPrometheus plugin, management APIJMX on clients and brokersINFO, XINFO commands
Lag exporterPlugin metricskafka_exporter, BurrowYour own probe
Unacked conceptmessages_unacknowledgedNot applicablepending
Unknown lagStatistics disabled-1 on errorNULL after trim or XDEL

In production systems ​

  • RabbitMQ documents that the aggregated Prometheus endpoint is the default and that per-object output “can result in very large payloads”; large estates scrape /metrics/detailed with a family filter.
  • Kafka documents records-lag-max as a consumer-published metric; teams that need lag when the consumer is down run kafka_exporter or Burrow against the brokers.
  • Redis documents that XINFO GROUPS lag becomes NULL after deletions; probes need an “unknown” state.
  • The OpenTelemetry Laravel instrumentation propagates context through the job payload; apps that already use it should not add a second bridge.
  • Laravel Horizon documents wait-time notifications and snapshot-driven metrics; Horizon is for Redis queues only.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Even with a database-backed queue the same problems exist. Add correlation_id at the request edge with Context, log ids only, and measure the jobs table with the SQL above. One Horizon dashboard or Pulse card is enough; no tracing backend is needed until a request crosses a process.

Modular monolith: shared worker pool ​

Modules publish to named queues. Use the destination name as the metric dimension and give each module its own wait threshold in config/horizon.php. Keep the module name in logs, not in span names, so the name set stays small.

Microservices: context across teams ​

Orders publishes OrderPlaced, Billing and Shipping consume it. Each consumer starts its own trace linked to the order's trace; the correlation id joins all of them in logs. Standardise one propagator, one set of header names and one semantic-convention version, otherwise a Java consumer's messaging.system and a Go producer's messaging.system.name never meet in one dashboard. A saga spans many traces by design; its correlation id is the only join key.

Distributed data: replicas, regions and clocks ​

Message age uses timestamps from two hosts; clock skew produces negative or inflated ages, so the snippet drops negative values and your NTP discipline matters. Cross-region mirroring (MirrorMaker, shovel, replication) can drop headers, and the lag you see per cluster is not the end-to-end lag. A replica that serves a read in the handler can make a message look “slow” for reasons that are not in the broker.

Scaling path ​

At 1x one Prometheus scrape and one Horizon dashboard suffice. At 10x, scrape detailed families, add the age histogram and burn-rate alerts, and move sampling to the collector. At 100x, use destination templates for dynamic names, tail sampling, a dedicated lag probe fleet, exemplars for the slow buckets and per-tenant counters instead of per-tenant series. Plan cardinality before traffic: a metric with a message id attribute is a bug at any scale.

Lab ​

All broker steps are expected output, not run; the Go tests and the offline demo can be run anywhere.

1. Offline propagation ​

bash
cd docs/snippets/messaging/messaging-observability/go
go test ./... && go run ./after/demo
# expected: ok for lagprobe, msgmetrics, msgtrace
# expected: traceparent: 00-<32 hex>-<16 hex>-01 / same trace id: false / consumer links to producer: true

2. RabbitMQ backlog and unacked ​

bash
rabbitmq-plugins enable rabbitmq_prometheus
curl -s -u monitor:secret 'http://localhost:15672/api/queues/%2F/orders.billing'
curl -s 'http://localhost:15692/metrics/detailed?family=queue_coarse_metrics&queue=^orders'
# stop the consumer, publish 100 messages
# expected, not run: messages_ready 100, messages_unacknowledged 0, consumers 0
# start a consumer with prefetch 10 that never acks
# expected, not run: messages_ready 90, messages_unacknowledged 10

3. Kafka lag from three views ​

bash
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
curl -s localhost:9308/metrics | grep kafka_consumergroup_lag
# stop the consumer, produce 1000 records, run the commands again
# expected, not run: LAG column 1000 total across partitions; kafka_consumergroup_lag_sum 1000

4. Redis NULL lag ​

bash
redis-cli XADD orders '*' k 1 ; redis-cli XGROUP CREATE orders billing 0
redis-cli XREADGROUP GROUP billing c1 COUNT 1 STREAMS orders '>'
redis-cli XINFO GROUPS orders
# expected, not run: pending 1, entries-read 1, lag 0
redis-cli XADD orders '*' k 2 ; redis-cli XADD orders '*' k 3
redis-cli XDEL orders <id-of-entry-2>
redis-cli XINFO GROUPS orders
# expected, not run: lag is nil: the probe must export "unknown", not 0 or -1

5. Laravel ​

bash
php artisan horizon:snapshot
php artisan pulse:check
# expected, not run: Horizon metrics tab shows throughput and wait time after two snapshots;
# the Pulse Queues card shows queued, processing, processed, released and failed counts

Common misconceptions ​

BeliefReality
The broker propagates trace context for meOnly a client library or your code writes it into the message
Queue depth is the health metricAge and burn rate say how late; depth only counts
The consumer span should be a child of the producerLinks are the default; parent-child only for one message outside another span
Trace id equals correlation idThe trace id is technical and sampled; the correlation id is business-owned
Unacked and lag are the sameUnacked is delivered but unfinished; lag is not yet delivered
records-lag-max shows everythingIt is published by the consumer; a dead consumer publishes nothing
Lag of zero means healthyUnknown lag is not zero; the consumer may be dead
More attributes make better metricsMessage ids and user ids explode cardinality
Debug logging of payloads is harmlessLogs outlive and out-spread the data's intended audience
The semantic conventions are stableThe messaging page is marked Development
Telescope is a production monitorIt is a development tool and needs pruning
Horizon covers every Laravel driverHorizon watches Redis queues
An unsampled message is invisibleCounters and logs still record it

Cheat sheet ​

TopicRemember
PropagationInstall propagators once; inject on publish; extract on consume
Headerstraceparent, tracestate, baggage; invalid values are ignored
Span kindsPRODUCER for send, CONSUMER for process, CLIENT for receive and settle
Span name{operation.name} {destination}
LinksDefault for consumers; one link per message in a batch
IdentifiersTrace id, correlation id and message id answer different questions
LagLog end minus committed, in records
AgeNow minus timestamp of the oldest undelivered message
UnackedDelivered, not settled
UnknownNever export unknown as zero
LogsIds and outcome, never payload or personal data
SamplingParent-based at consumers; tail sampling in the collector
AlertsBurn rate on an age SLO; no-consumers rule
RabbitMQPlugin on 15692, detailed families, management API on 15672
Kafkarecords-lag-max plus broker-side exporter or Burrow
RedisXINFO GROUPS lag, pending; NULL after trim
LaravelContext, Horizon snapshot, Pulse, Telescope only in development

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does a consumer trace start fresh when the producer sends no headers? Important ​

Answer

Answer: The consumer has no remote span context to extract, so its tracer creates a new root. Propagation has to be written into the message by the producer.

2 — Which fields make up traceparent? Important ​

Answer

Answer: Version, trace id, parent id and trace flags, separated by dashes; the sampled flag is bit 01 of the flags.

3 — When should a consumer span link instead of parenting under the producer span? Good to know ​

Answer

Answer: For batches, retries, fan-out and whenever another span is already active, because a span has one parent but many links.

4 — Why are trace id and correlation id different identifiers? Must-know ​

Answer

Answer: The trace id is technical, may be dropped by sampling and restarts under link-style consumers; the correlation id is business-owned and stays constant across all of that.

5 — Why is queue depth a poor alert? Must-know ​

Answer

Answer: It is a count with no time dimension. It fires on healthy peaks and misses a small queue with a stuck consumer; age and burn rate measure delay.

6 — What does RabbitMQ's management API return that a plain queue size does not? Important ​

Answer

Answer: messages_ready and messages_unacknowledged separately, plus consumer count.

7 — Why can records-lag-max mislead when a consumer dies? Important ​

Answer

Answer: The consumer publishes the metric, so a dead consumer publishes nothing; the series disappears instead of rising.

8 — How does Redis report lag that cannot be determined, and how should a probe handle it? Good to know ​

Answer

Answer: XINFO GROUPS returns NULL (go-redis maps it to -1) after deletions or arbitrary group ids. Export an unknown gauge, not zero.

9 — What should never appear in a message log line? Must-know ​

Answer

Answer: The payload body and personal data; log ids, destination, position, attempt and outcome class.

10 — What burn rate pages for 2 percent of a 30-day budget in one hour? Good to know ​

Answer

Answer: 14.4, evaluated over one hour and confirmed over a five-minute window.

Glossary ​

TermMeaning
ObservabilityAbility to explain system behaviour from its outputs
OpenTelemetryVendor-neutral API, SDK and conventions for traces, metrics and logs
W3C Trace ContextStandard for the traceparent and tracestate fields
traceparentField with version, trace id, parent id and flags
tracestateVendor-specific companion list
baggageApplication key/value pairs that travel with the trace
PropagatorComponent that injects and extracts context
CarrierMap-like structure (headers, fields) the propagator reads and writes
Trace idIdentifier of one trace
SpanOne timed operation in a trace
Span kindPRODUCER, CONSUMER, CLIENT, SERVER, INTERNAL
Producer spanSpan for creating or sending a message
Consumer spanSpan for processing a message
Span linkReference to another span context without parenting
Semantic conventionsStandard span, attribute and metric names
messaging.system.nameAttribute naming the broker technology
messaging.destination.nameAttribute naming the queue, topic or stream
messaging.operation.typecreate, send, receive, process or settle
Correlation idBusiness identifier shared by a conversation
Message idIdentifier of one physical message
Consumer lagRecords produced but not yet consumed
Oldest message ageAge of the first undelivered message
Queue depthReady plus unacknowledged messages
UnackedDelivered but not acknowledged
RedeliveredFlag or count for a message delivered again
Publish failureProducer-side error or negative confirmation
HistogramDistribution metric with buckets
ExemplarTrace id attached to a metric sample
SamplingChoosing which traces to keep
SLOTarget for a service level indicator
Burn rateSpeed of error-budget consumption
PrometheusPull-based metrics system
rabbitmq_prometheusRabbitMQ plugin exposing metrics on port 15692
Management APIRabbitMQ HTTP API on port 15672
JMXJava Management Extensions, used for Kafka metrics
kafka_exporterPrometheus exporter for consumer-group lag
BurrowThreshold-free Kafka lag monitor
records-lag-maxKafka consumer metric for maximum partition lag
XINFO GROUPSRedis command listing consumer groups with lag and pending
XPENDINGRedis command for the pending entries list
entries-readRedis group read counter used to compute lag
HorizonLaravel dashboard for Redis queues
PulseLaravel application performance cards
TelescopeLaravel debugging assistant for development
PIIPersonally identifiable information
Structured loggingLogs as key/value records

References ​

Built by Morteza Negahi