[Example] Trace correlation between microservices using context #2281
-
Hello ! I'm a little bit lost on how to correlate traces between microservices using golang's context. My use case is very simple: I have a backend and a frontend, the frontend sends request to the backend shipping the context with
The backend, receives the request and start a new span using the context from this request.
I figured this would simply work, but it doesnt', I can retrieve traces for the two services separately, but can't correlate them. Could you provide more examples or point me to the proper architecture documentation which will help me implement this ? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
For this to work you need the tracer := otel.Tracer("hello-world-frontend")
// Register a propagator
otel.SetTextMapPropagator(propagation.TraceContext{})
// Span Starts Now
ctx, span := tracer.Start(ctx, "client")
// Span Ends at the end of the function
defer span.End()
// Adding event to this spawn for follow up in the backend
span.AddEvent("Launching Request to backend")
req, _ := http.NewRequestWithContext(ctx, "GET", "http://127.0.0.1:3000", nil)
// Include a tracing transport
httpclient := &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
resp, err = httpclient.Do(req)
// etc... Then, when you register your HTTP handler you wrap it with otelHandler := otelhttp.NewHandler(http.HandlerFunc(handler), "API call") |
Beta Was this translation helpful? Give feedback.
For this to work you need the
propagation
API and an implementation of aPropagator
to be used by the HTTP client and server at each end. The stdlib HTTP client doesn't serialize and ship acontext.Context
when you create aNewRequestWithContext()
, it only makes it available to thehttp.Client
and its associatedRoundTripper
. We provide theotelhttp.Transport
andotelhttp.Handler
types to assist with propagating trace context across HTTP requests. Its example is hopefully helpful, but your implementation requires very little change to incorporate them.