<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leogcrocha on Medium]]></title>
        <description><![CDATA[Stories by Leogcrocha on Medium]]></description>
        <link>https://medium.com/@leogcrocha?source=rss-1a6b4981be2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*04j2QaSNA5TY3IQC</url>
            <title>Stories by Leogcrocha on Medium</title>
            <link>https://medium.com/@leogcrocha?source=rss-1a6b4981be2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:41:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leogcrocha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Context Propagation in Distributed Applications and Microservices]]></title>
            <link>https://medium.com/@leogcrocha/context-propagation-in-distributed-applications-and-microservices-34242b90c06d?source=rss-1a6b4981be2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/34242b90c06d</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Leogcrocha]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 12:45:39 GMT</pubDate>
            <atom:updated>2025-12-26T23:11:13.043Z</atom:updated>
            <content:encoded><![CDATA[<p>In distributed applications or microservices based on message broker communication, it is difficult to observe the entire lifetime of a request across all logical processes. Imagine a scenario where a request is processed in event-driven system: the user creates a new order wich trigger events on differents system and the process is taking longer than expected. Without unified tracing, you would need to manualy correlate inidivudal traces across multiple services, which quickly becomes unmanageable.</p><p>Because of this, I’ll discuss something essential but often ignored: Context Propagation (CP). Even applications that uses OpenTelemetry for distributed tracing don’t take advantage of all the available features.</p><p>I’ll demonstrate this through a hands-on project, providing a practical guide to implementing Context Propagation and showing its real effects. For this example, we’ll use a simple environment composed of three distributed applications provisioned with Aspire. Each application has a clear purpose and works as part of a chain: Application A sends a message to Application B, and Application B sends a message to Application C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEtsus8TDSxCs1ps8VTzgg.png" /><figcaption>Distributed Tracing on Microservices</figcaption></figure><p>I will assume that you already have an understanding of Open Telemetry concepts; if not, I recommend reading: <a href="https://opentelemetry.io/docs/languages/dotnet/">Open Telemtry Documentation</a>.</p><p>Before walking through the code, we need to have an understanding of <em>traceparent.</em></p><blockquote>Traceparent is a W3C Trace Context header that carries trace and span identifiers across service boundaries, allowing distrubted traces to remain connected. When using messaging, it is propagated by injecting the traceparent value into the message headers on publishing and extracting it on consume to continue the same trace.</blockquote><p>The first thing we need to do is inject the context when publishing a new message. In the picture below, we can see that the current context is injected into the message headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*w66e-w4GUNhOjUS6kS_A5g.png" /></figure><p>The code responsible for injecting the context is shown bellow. The main workflow is as follows:</p><ol><li>Get the current activity, if it exists.</li><li>Inject into the message headers using OpenTelemetry’s <em>TextMapPropagator, </em>which ensures the <em>traceparent </em>format is respected.</li></ol><pre>public static void InjectTraceContext(this IBasicProperties properties, TextMapPropagator propagator)<br>{<br>    var activity = Activity.Current;<br>    <br>    if (activity is null)<br>        return;<br><br>    properties.Headers ??= new Dictionary&lt;string, object&gt;();<br>    <br>    // Baggage is used to pass key-value pairs (tags) from one trace to another.<br>    // In some cases, you shouldn&#39;t use it.<br>    propagator.Inject(<br>        new PropagationContext(activity.Context, Baggage.Current),<br>        properties.Headers ??= new Dictionary&lt;string, object&gt;(), <br>        (carrier, key, value) =&gt;<br>        {<br>            carrier[key] = value;<br>        });<br>}</pre><p>To get a proper understanding of how these methods are used, I strongly recommend reviewing the complete code implementation of the following parts: <a href="https://github.com/LeoGCRocha/context-propagation-lab/blob/master/Shared/Observability/ContextPropagationExtensions.cs#L12">context propagation</a> and <a href="https://github.com/LeoGCRocha/context-propagation-lab/blob/94cd85c17a7d13b4bc6f0cf75afc231ae1010004/Shared/Infra/RabbitMqProducer.cs#L38">RabbiMQ message publishing</a>.</p><p>After doing that, our message will carry a traceparent, as shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*TdotEEz7rvMV2AOUFv5J7A.png" /></figure><p>Furthermore, we now need to consume the message, extract the headers, and create a new context that refers to the parent context. To demonstrate this, I’ll show two snippets that illustrate the process.</p><p>The first snippet is the RabbitMQ message consumer. As shown below, it contains two main methods.</p><p>StartAsync is responsible for defining the skeleton of the message consumption process. For each consumed message, we create an activity by extracting the parent context from the <em>traceparent</em> header.</p><p>As shown in the <em>StartActivityFromMessage </em>method, we use the message headers to extract the context and then create a new activity using <em>Activity Source,</em> explicitly linking it to the parent context.</p><pre>public Task StartAsync(CancellationToken cancellationToken)<br>{<br>    var consumer = new AsyncEventingBasicConsumer(_channel);<br><br>    consumer.Received += async (_, args) =&gt;<br>    {<br>        using var activity = StartActivityFromMessage(args.BasicProperties);<br><br>        try<br>        {<br>            var json = Encoding.UTF8.GetString(args.Body.ToArray());<br>            var message = JsonSerializer.Deserialize&lt;T&gt;(json)<br>                          ?? throw new InvalidOperationException(&quot;Failed to deserialize message&quot;);<br><br>            await HandleAsync(message, cancellationToken);<br><br>            _channel.BasicAck(args.DeliveryTag, multiple: false);<br>            activity?.SetStatus(ActivityStatusCode.Ok);<br>        }<br>        catch (Exception ex)<br>        {<br>            activity?.RecordException(ex);<br>            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);<br><br>            _channel.BasicNack(<br>                args.DeliveryTag,<br>                multiple: false,<br>                requeue: false);<br>        }<br>    };<br><br>    _channel.BasicConsume(<br>        queue: _queueName,<br>        autoAck: false,<br>        consumer: consumer);<br><br>    return Task.CompletedTask;<br>}<br><br>  private Activity? StartActivityFromMessage(IBasicProperties properties)<br>  {<br>      var parentContext = properties.ExtractTraceContext(Propagator);<br><br>      Baggage.Current = parentContext.Baggage;<br><br>      var activity = ActivitySource.StartActivity(<br>          $&quot;Consume message from {_queueName}&quot;,<br>          ActivityKind.Consumer,<br>          parentContext.ActivityContext);<br><br>      activity?.SetTag(&quot;message.system&quot;, &quot;rabbitmq&quot;);<br>      activity?.SetTag(&quot;rabbitmq.queueName.source&quot;, _queueName);<br><br>      return activity;<br>  }</pre><p>The method responsible for extracing header values is quite simple. We use the current <em>TextMapPropagator </em>from the OpenTelemetry library and iterate through each key in the headers, as shown below.</p><pre>public static PropagationContext ExtractTraceContext(this IBasicProperties properties, TextMapPropagator propagator)<br>{<br>    var headers = properties.Headers ?? new Dictionary&lt;string, object&gt;();<br><br>    return propagator.Extract(default, headers, ExtractFromHeaders);<br>}<br><br>private static IEnumerable&lt;string&gt; ExtractFromHeaders(IDictionary&lt;string, object&gt; carrier, string key)<br>{<br>    if (carrier.TryGetValue(key, out object value))<br>    {<br>        if (value is byte[] bytes)<br>        {<br>            return new[] { Encoding.UTF8.GetString(bytes) };<br>        }<br>        <br>        return new[] { value?.ToString() };<br>    }<br><br>    return Enumerable.Empty&lt;string&gt;();<br>}</pre><p>Using the Aspire Telemetry dashboard, we can see the interaction between all services as a single trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ipoGdriegcn_S5bfik2Mg.png" /><figcaption>Context Propagation</figcaption></figure><p>Distributed tracing without a propor context propagation provides only partial visibility into a system’s behavior. In EDA and microservices, where communication is mostly asynchronous and decoupled, Context Propagation must be a requirement, not a bonus. Teams adopting OpenTelemetry should treat CP as a first-class concern, to achieve truly end-to-end observability.</p><p>If you want to see more details about the implementation, you can find the code on GitHub: <a href="https://github.com/LeoGCRocha/context-propagation-lab">ContextPropagationLab</a><em>.</em></p><p>Futhermore, if you have any question, you can send me a message on my professional LinkedIn profile:<a href="https://www.linkedin.com/in/leonardo-rocha-9806501b9/"> Leonardo Rocha</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34242b90c06d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>