liveBook · Manning

Correlation id

As explained in gRPC Microservices in Go

A trace ID is an identifier that correlates all operations belonging to one distributed request.

A correlation ID identifies operations that belong to one distributed request. In tracing, this is the trace ID: it lets you group activity across an API gateway and its downstream services instead of inspecting each service in isolation. A successful response can still hide latency, so the shared ID helps locate where time was spent. section 1.4.4 section 9.3.7

Put the trace ID in application logs so a logging backend can filter messages from one operation, even when many services write to it. In Go, a logrus formatter can read the current OpenTelemetry span from the log entry’s context and add `trace_id` and `span_id` fields. Initialize the formatter at startup and log with `log.WithContext(ctx)` so it receives the relevant context. section 9.3.7

...
type serviceLogger struct {
    formatter log.JSONFormatter                                    #1
}
 
func (l serviceLogger) Format(entry *log.Entry) ([]byte, error) {
    span := trace.SpanFromContext(entry.Context)                   #2
    entry.Data["trace_id"] = span.SpanContext().TraceID().String()
    entry.Data["span_id"] = span.SpanContext().SpanID().String()
    //Below injection is Just to understand what Context has
    entry.Data["Context"] = span.SpanContext()
    return l.formatter.Format(entry)                               #3
}
...

The formatter extracts tracing identifiers from the entry’s context and writes them as JSON log fields. section 9.3.7

Correlating asynchronous events

After an Order service publishes a payment command, a Payment service can return the bill ID through the specified reply channel. Adding a correlation ID to the events helps operators see that series of events as one operation. This is a related use of correlation, not a substitute for propagating tracing context through service calls. section 2.3.3 section 1.4.4

How gRPC Microservices in Go covers it

How deep it goes
Shows how to inject trace and span IDs into Go logs; mentions event correlation without implementing event propagation.
Examples
Uses an order-creation log entry and payment-command events with a reply channel.
What you can do after
Apply it via logrus and OpenTelemetry context to tag logs with identifiers for filtering one operation.
How it connects
Connects distributed tracing, application logging, OpenTelemetry, and asynchronous messaging.

Also explained in

Compare how 5 books explain correlation id →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of gRPC Microservices in Go. The section links point to the parts of the book it draws on.