0Pricing
System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) · 강의

컨텍스트 전파와 수하물

분산 작업을 연결하는 핵심 OpenTelemetry 개념인 컨텍스트 전파를 깊이 있게 살펴봅니다. 수하물을 사용해 서비스 간에 임의의 데이터를 전달하는 방법을 알아봅니다.

컨텍스트 전파와 수하물은(는) CoddyKit의 무료 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Linking Distributed Operations

In modern applications, a single user request often travels through many different services. Imagine an online store: your click goes to a frontend, then an order service, a payment service, and a shipping service.

How do we track this journey? If each service logs independently, it's like trying to follow a single thread in a tangled ball of yarn!

What is Context Propagation?

Context propagation is the magic that links these distributed operations together. It ensures that all parts of a request, no matter which service they touch, share a common understanding of that request.

Think of it like a relay race: the 'baton' (the context) is passed from one runner (service) to the next, linking all their efforts to a single goal.

The Trace Context Explained

The core of context propagation is the Trace Context. This usually contains two vital pieces of information:

  • Trace ID: A unique identifier for the entire request journey across all services.
  • Span ID: A unique identifier for the current operation within a service.

These IDs are crucial for OpenTelemetry to build a complete picture of your request's flow.

How Context Travels

Context doesn't just magically appear! OpenTelemetry uses 'propagators' to inject and extract this context.

Common ways context is propagated:

  • HTTP Headers: Standard headers like traceparent and tracestate.
  • gRPC Metadata: Similar to HTTP headers, but for gRPC calls.
  • Message Queue Properties: When sending messages between services.

These mechanisms ensure the Trace ID and Span ID follow the request.

Injecting Context Demo

When a service makes an outgoing call to another service, the current trace context needs to be 'injected' into the request. This example simulates adding trace context to headers.

import io.opentelemetry.api.trace.Span; 
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapSetter;
import java.util.HashMap;
import java.util.Map;

public class ContextInjector {

  public static void main(String[] args) {
    // Simulate an active span context
    SpanContext simulatedSpanContext =
        SpanContext.create(
            "0123456789abcdef0123456789abcdef", // Trace ID
            "fedcba9876543210", // Span ID
            io.opentelemetry.api.trace.TraceFlags.getDefault(),
            io.opentelemetry.api.trace.TraceState.getDefault());
    Span span = Span.wrap(simulatedSpanContext);
    Context context = Context.current().with(span);

    Map<String, String> headers = new HashMap<>();
    TextMapSetter<Map<String, String>> setter = Map::put;

    // OpenTelemetry usually handles this implicitly
    // Here, we simulate injecting context into headers
    // using a simplified representation.
    headers.put("traceparent", "00-" + simulatedSpanContext.getTraceId() + "-" + simulatedSpanContext.getSpanId() + "-01");
    
    System.out.println("Injected Headers:");
    headers.forEach((key, value) -> System.out.println(key + ": " + value));
  }
}

Extracting Context Demo

When a service receives an incoming request, it needs to 'extract' the trace context from the request. This allows it to continue the trace initiated by the upstream service.

import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import java.util.HashMap;
import java.util.Map;

public class ContextExtractor {

  public static void main(String[] args) {
    Map<String, String> incomingHeaders = new HashMap<>();
    incomingHeaders.put("traceparent", "00-112233445566778899aabbccddeeff00-aabbccddeeff0011-01");

    TextMapGetter<Map<String, String>> getter = new TextMapGetter<Map<String, String>>() {
      @Override
      public Iterable<String> keys(Map<String, String> carrier) {
        return carrier.keySet();
      }

      @Override
      public String get(Map<String, String> carrier, String key) {
        return carrier.get(key);
      }
    };

    // In a real app, OpenTelemetry.getGlobalPropagators() would be used
    TextMapPropagator propagator = OpenTelemetrySdk.builder().build()
        .getPropagators().getTextMapPropagator();

    Context extractedContext = propagator.extract(Context.current(), incomingHeaders, getter);
    SpanContext spanContext = Span.fromContext(extractedContext).getSpanContext();

    System.out.println("Extracted Trace ID: " + spanContext.getTraceId());
    System.out.println("Extracted Span ID: " + spanContext.getSpanId());
  }
}

Carrying Extra Data: Baggage

Beyond just trace and span IDs, sometimes you need to carry arbitrary key-value data across services that's relevant to the business logic, but not directly for tracing.

This is where Baggage comes in! It's a collection of key-value pairs that travel alongside the trace context.

Baggage vs. Trace Context

It's important to understand the difference:

  • Trace Context: Essential for linking spans and building the trace graph. It's structural.
  • Baggage: Carries application-specific data. Examples include a user_id, tenant_id, or an A/B test variant. It's informational.

Baggage is propagated using the same mechanisms as trace context (e.g., HTTP headers), often in a header like baggage.

Using Baggage Demo

Here's how you can add an item to Baggage in one part of your application and retrieve it in another, potentially downstream, service. This data travels with the request.

import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.context.Context;

public class BaggageUsage {

  public static void main(String[] args) {
    // --- Service A: Add to Baggage ---
    System.out.println("--- Service A ---");
    Context contextWithBaggage = Baggage.current()
        .toBuilder()
        .put("user.id", "12345")
        .put("ab.test.group", "variantA")
        .build()
        .make   Current(); // Make this baggage active in current context

    System.out.println("Added user.id: " + Baggage.current().getEntryValue("user.id"));
    System.out.println("Added ab.test.group: " + Baggage.current().getEntryValue("ab.test.group"));
    
    // Simulate passing context (and thus baggage) to Service B
    // In a real app, this would be via HTTP headers, etc.
    callServiceB(contextWithBaggage);
  }

  public static void callServiceB(Context parentContext) {
    // --- Service B: Retrieve from Baggage ---
    System.out.println("\n--- Service B ---");
    // Activate the context from Service A
    try (io.opentelemetry.context.Scope scope = parentContext.makeCurrent()) {
      Baggage currentBaggage = Baggage.current();
      System.out.println("Retrieved user.id: " + currentBaggage.getEntryValue("user.id"));
      System.out.println("Retrieved ab.test.group: " + currentBaggage.getEntryValue("ab.test.group"));
    }
  }
}

Context Propagation Check

You're debugging a distributed system. A user reports an issue, and you have their user_id. You want to see all logs and traces related to this user across multiple services.

Context & Baggage Summary

You've learned how context propagation is fundamental to distributed tracing, using Trace IDs and Span IDs to link operations across services.

You also explored Baggage, a powerful mechanism to carry custom, application-specific data (like a user_id or A/B test group) alongside your trace context, enriching your observability data.

These concepts are vital for building a complete and actionable view of your distributed applications!

자주 묻는 질문

“컨텍스트 전파와 수하물” 강의는 무료인가요?

네 — “컨텍스트 전파와 수하물” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 강의 전체를 잠금 해제할 수 있습니다. System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 강의에는 총 4개의 강의가 포함되어 있습니다.

“컨텍스트 전파와 수하물”에서 뭘 배우나요?

분산 작업을 연결하는 핵심 OpenTelemetry 개념인 컨텍스트 전파를 깊이 있게 살펴봅니다. 수하물을 사용해 서비스 간에 임의의 데이터를 전달하는 방법을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“컨텍스트 전파와 수하물” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 자동 계측 기법
  2. 수동 계측 모범 사례
  3. 컨텍스트 전파와 수하물
  4. 스팬 속성, 이벤트와 상태
← System Observability: Logging, Metrics & Tracing (ELK + OpenTelemetry)(으)로 돌아가기