Get Started with Datadog

Engineering

Bringing application context to full-host eBPF profiling

Published

Read time

21m

Bringing application context to full-host eBPF profiling
Ivo Anjo

Ivo Anjo

Staff Engineer

Scott Gerring

Scott Gerring

Senior Technical Advocate

A profiler can identify the hottest code and still be unable to tell you which request the code was handling. That’s because broad, consistent profiling coverage is often not enough to reconstruct context: By itself, it can’t connect resource use to a distributed operation or a higher-level construct such as an endpoint.

The OpenTelemetry Profiles signal is now in public alpha, and the OpenTelemetry eBPF Profiler can instrument a host to collect profiles from applications written in native languages, such as Rust and C++, and managed languages, such as Python, Java, and Go. However, making those profiles actionable requires a safe, low-overhead way to recover the application context that an out-of-process profiler cannot ordinarily see.

Over the past year, we worked with contributors from Elastic, Polar Signals, and the wider OpenTelemetry community to standardize how applications share process and thread context with external profilers. That work produced two accepted OpenTelemetry Enhancement Proposals (OTEPs) defining protocols that can work across SDKs and profilers. In this post, we explain how those protocols work, why process and thread context require different mechanisms, and how shared memory, ELF thread-local storage, and runtime-specific constraints shaped their design.

Process context identifies the resource a sample belongs to, including attributes such as service name, version, and instance ID. Thread context identifies the trace, span, and request metadata active at the instant the sample was collected. Nine Datadog tracing SDKs now publish process context by default.

Full-host profiling provides system-wide coverage but lacks application context

Traditional application profilers (“runtime profilers”) run inside the process they observe. That position gives them an important advantage: They understand the application runtime. A Java profiler can take advantage of Java Flight Recorder (JFR) events from the Java Virtual Machine (JVM). A Python profiler can walk interpreter frames and reconstruct the logical stacks of asyncio tasks that share an operating-system thread. 

This approach also gives profilers a direct path to associate samples with the request or trace that was active at the time. If you are running inside the JVM and know where OpenTelemetry stores request context, for example, you can read it when you collect a profiling sample using the in-process API.

The trade-off is coverage and consistency. Each language needs its own integration, and not every language or runtime has equivalent profiling support. An in-process profiler can also lose sight of work below the language runtime. A Python service doing machine-learning inference may spend most of its CPU time inside PyTorch’s native C and C++ implementation, for example. Looking only at Python frames leaves much of that work unexplained.

The full-host eBPF profiler reverses this arrangement. It observes execution from outside applications and can sample every process on a host, including uninstrumented native code. The same profiler and data model can cover a Java service, a Python application, a database, and the native libraries they call. The OpenTelemetry eBPF Profiler is an important step toward that consistent system-wide view.

That broader view comes at the cost of visibility into application context. From outside a process, the profiler sees process IDs, thread IDs, instruction pointers, stack frames, and other system-level facts. It doesn’t see the service.name generated by an OpenTelemetry SDK, the active trace ID stored in a runtime context object, or the HTTP route associated with the work. Although the profiler can make arbitrary reads into the profiled process’s memory, it still needs to know where to look for this information.

Full-host profiling needs a way to preserve its outside-in coverage while carrying forward the trace and request context that connects profiles to the rest of the application’s telemetry.

Why profiles need application context

Consider a service that handles checkout, catalog, and health-check requests in the same process. A process-wide flame graph can show that a JSON serialization function is consuming CPU. It can’t tell us whether that work came from checkout traffic, catalog traffic, or a background task. If one route is slow while the others are healthy, combining all of their samples can hide the distinction we care about. With request context, an engineer can filter that profile by endpoint or business operation instead.

This is why traces can act as connective tissue between telemetry signals. A trace ID can connect a profiling sample to the request that was active when the sample was taken. OpenTelemetry Resource attributes such as service.name, service.version, and deployment.environment.name connect that sample to the same logical service represented in traces, metrics, and logs. A runtime-generated attribute such as service.instance.id can distinguish two processes that otherwise look identical.

Container metadata and command-line inspection can recover some of this information, but they’re not substitutes for the SDK’s own view. They may not contain runtime-generated identifiers, and separately resolving configuration for each telemetry signal can produce inconsistent tags. More fundamentally, an out-of-process profiler struggles to infer the active span, the operation within a trace that represents the current unit of work, from a stack trace. That relationship exists inside the application and may change every time its runtime switches execution contexts.

Existing work from Elastic’s Universal Profiling integration and Polar Signals’ custom-labels protocol had already demonstrated ways to share trace and request context with external profilers. We used that prior art as the starting point for an OpenTelemetry mechanism that could work across profilers and SDKs rather than introducing another vendor-specific channel.

We split the problem into two layers because their update rates, data shapes, and performance constraints are fundamentally different:

  • Process context changes rarely and describes the application as a whole.

  • Thread context can change on every context attachment and describes what one thread is doing at one instant.

Process context makes an application discoverable from the outside

The first layer—process context—answers a basic question: Which application does this process represent?

OTEP 4719 defines a process-wide context built around the OpenTelemetry resource, the attributes that identify the entity producing telemetry. This lets an SDK share the service name, version, environment, and instance ID, along with the SDK’s own name and version, with an external profiler. This information changes infrequently or not at all once an application has started. 

The challenge is giving another process a reliable way to find and read these attributes. The mechanism has to work whether the application or profiler starts first, remain available when the application is idle or deadlocked, support updates, and avoid depending on features that are often unavailable in containers, such as a writable filesystem or long-lived socket. 

It also has to handle applications that make use of fork(), which creates a child process by copying a running parent. Web servers such as Python’s Gunicorn or Ruby’s Puma use this pattern to start workers. If a child were to inherit its parent’s context, both processes could incorrectly report the same service-instance identity.

The process context design serializes the context as a Protocol Buffers (protobuf) payload, usually a few KB in total, and publishes it through a Linux named memory mapping. The mapping is a specially allocated range of memory inside of the application’s virtual memory. It occupies one or a small handful of memory pages, typically about 4 KB per process.

To make that memory discoverable, the SDK creates a small memory mapping named OTEL_CTX. It prefers memfd_create(), which asks the kernel for a file-like object whose contents live only in memory, and falls back to an anonymous mapping if memfd_create() is unavailable. The OTEL_CTX name, supplied when creating the memfd and also applied to the mapping using prctl() where supported, gives the profiler a recognizable entry to find in Linux’s /proc/<pid>/maps file. Finally, MADV_DONTFORK tells the kernel not to copy the mapping into children created with fork(), preventing them from inheriting stale service identity. 

An outside profiler scans /proc/<pid>/maps for entries named OTEL_CTX, then uses process_vm_readv() to perform a remote read directly from the application’s memory. These reads remain subject to Linux’s normal process-inspection permissions. Context sharing doesn’t bypass process isolation.

Making a cross-process read consistent

Raw memory reads and writes between processes introduce a concurrency problem. The service can update resource attributes while the profiler is reading them. Without a concurrency-control protocol, the profiler might confuse fields from different updates and attach the wrong information to samples. 

To solve this, the specification has the writer mark a special field inside the memory mapping whenever there is an update in progress. The reader checks this special field before and after copying the payload. If it changed, the reader discards the copy and retries. 

The OTEP contains the memory-ordering details, including the careful placement of memory fences that we spent considerable time debating. The debate wasn’t entirely academic: Rust’s memory model doesn’t fully specify this cross-process case, so implementers still have to translate the contract carefully.

Working through how the profiler would discover the mapping also made us change tack. Initially we had moved away from memfd because Linux can assign names directly to anonymous mappings, but we soon realized that this feature arrived only in Linux 5.17 and can be disabled in some vendor kernels. 

We returned to memfd, but used the visibility of its mapping rather than keeping the file descriptor open. After several rounds of prototyping, we ended up back where we started—but with a better understanding of why.

The SDK also relies on prctl(), a general Linux interface for changing properties of a process, including names and life cycle behavior. Here, we use it only to label the mapping OTEL_CTX when the kernel supports that operation. 

Even when an older kernel can’t retain that label, the call itself is useful: The eBPF reader can observe it as an event announcing that context was published or updated. The OpenTelemetry eBPF Profiler now hooks these calls, avoiding continuous polling while retaining fallback discovery for processes that published their context before the hook was active. 

Once an SDK publishes process context, a profiler implementing the OTEP can carry the same service name, version, environment, and instance identity as the application’s traces, metrics, and logs. Users can group and filter profiles by service without reconstructing that identity from containers or command lines. 

Process context still can’t tell us which request produced an individual sample. That requires a second mechanism on a much hotter path.

Thread context connects profiling samples to requests 

The thread-context problem sounds simple: When the profiler samples a thread, read the trace ID and span ID currently associated with it. Users have told us that this is a high-priority feature for the full-host profiler. The difficult part is making those IDs visible outside the process without making every span activation noticeably more expensive. 

Diagram with one OS thread switching among Contexts A through E, with attach and detach events at each context boundary. The eBPF profiler takes a single sample while Context D is active.
Thread context is updated at every attach and detach, even though the profiler samples the thread much less frequently.
Diagram with one OS thread switching among Contexts A through E, with attach and detach events at each context boundary. The eBPF profiler takes a single sample while Context D is active.
Thread context is updated at every attach and detach, even though the profiler samples the thread much less frequently.

A busy service, especially one using an asynchronous runtime, can attach and detach context hundreds of thousands of times per second as it switches between logical requests. We wanted to use a native thread-local variable to store this information so we could easily discover and read it from the eBPF profiler, but we needed to be careful: For many managed languages, updating native thread-local state requires crossing a foreign function interface (FFI), and putting that boundary crossing on every switch makes a single generic implementation impractical.

A key detail is that this publication code is intended to run inside applications on every part of the span life cycle, whether or not the profiler takes a sample. Because this code runs on every span attach and detach in production, its overhead must be low enough not to materially affect application performance.

To put a number on the constraint, we measured our initial Java implementation using the Java Native Interface (JNI) to enter native code on every span and found that it cost roughly 146 ns per update to the span. At 100,000 span life cycles per second, that initial path alone would consume approximately 1.5% of one CPU core, which is already above the cost budget of the entire profiler. 

OTEP 4947 addresses this with a compact Thread-Local Context Record and an exported ELF thread-local storage symbol named otel_thread_ctx_v1. For each operating-system thread, the symbol points to the record for the currently active context. Attaching context can be as small as preparing or selecting a record and changing one thread-local pointer. Detaching it clears the pointer or marks the record invalid.

Each record contains:

  • A 16-byte trace ID and 8-byte span ID

  • A validity byte and a trace-flags byte

  • A 2-byte length for optional attribute data

  • Compact key and value entries for request attributes such as an HTTP route or method

The required portion is only 28 bytes. A typical record with two short attributes fits within one 64-byte cache line, so the CPU can keep the data together rather than loading scattered fields. 

This locality of reference can save time as well as space: Following pointers creates serial dependencies because the address of each read isn’t known until the previous read finishes, and a cache miss at any step stalls the CPU’s pipeline. Our format recommends a maximum record size of 640 bytes to match the OpenTelemetry eBPF Profiler’s read budget.

To reduce overhead further, we use the process context to deduplicate keys used in thread context. For this, it includes a dictionary that maps one-byte indexes to attribute names. A thread record can store an index instead of repeating strings such as http.route, reducing both the bytes copied with each sample and the work needed to decode them. 

Static metadata stays in the process context, where protobuf provides flexibility and updates are rare. Per-request data stays in the fixed binary record, where writers can avoid allocations and minimize cache traffic.

ELF TLS is harder than it looks

Storing thread-local data from inside an application is easy. Finding that data from another process, across different compilers, linkers, C runtimes, native libraries, and managed runtimes, is not.

Thread-local storage (TLS) gives every operating-system thread its own instance of a variable. On Linux, a register always holds the thread pointer, and this acts as the starting point for locating those variables. We began with a simple mental model: Compile the library using TLSDESC, export otel_thread_ctx_v1, and let the reader recover a fixed offset from the thread pointer. 

That model fell apart when we began testing against the different build and environment setups that Datadog tracers and OpenTelemetry SDKs encounter in practice.

The first complication is where the runtime stores the variable. Modules loaded before main can use the static TLS block, where a variable sits at a fixed offset from the thread pointer. A library loaded later with dlopen, as dynamic libraries loaded into Java through JNI often are, may instead use the dynamic thread vector (DTV), a per-thread table that points to each loaded module’s TLS storage. 

This is the pointer-chasing path described above: The reader must first find the DTV, then its module entry, then the variable. The writer pays for dynamic TLS resolution too. Those dependent reads happen in the SDK’s context-change hot path, so a cache miss can make every attach or detach more expensive.

The second complication is how compiled code expects to find the variable. Compilers emit different TLS access models based on what they know at build and link time. If a variable is guaranteed to exist at startup, the compiler can use a fixed offset from the thread pointer, which is always available in a CPU register. This is the fastest possible path to resolve a TLS variable. 

If a library may arrive later, it emits a more general dynamic lookup. TLSDESC is a descriptor-based form of that dynamic lookup: When the loader manages to place the variable in static TLS, it can rewrite the descriptor to use the cheap fixed-offset path.

This optimization depends on the libc runtime: glibc, for instance, reserves 512 bytes of extra static TLS space, so a small library loaded late can often still receive static placement. If that surplus is exhausted, the variable falls back to the DTV.

Yet, the profiler can’t assume which approach the compiler and linker selected. A linker may also relax TLS access, meaning it replaces a general dynamic lookup with a cheaper static form when it can prove the variable’s location earlier. 

We built a demo repository covering glibc, musl, static linking, dynamic linking, dlopen, and JNI, and found that the reader needs to recognize three outcomes:

  • TLSDESC global-dynamic access: The recommended writer path. An optimized descriptor exposes a thread-pointer-relative offset that the reader can cache.

  • Legacy global-dynamic access: The older dynamic form. The reader uses loader metadata and, when necessary, follows the DTV to the module’s storage.

  • Static access: The compiler and linker have reduced the lookup to the initial-exec or local-exec form, and the reader derives a fixed thread-pointer-relative offset.

The less common local-dynamic model isn’t supported by the OTEP. The profiler identifies the model once when configuring a process, then each sample uses either a cached offset or the DTV fallback.

Once we thought we had a reasonably complete view, testing it broke it in three ways:

  • Java wasn’t using TLSDESC. When we first enabled thread context in dd-trace-java, we discovered the native library hadn’t been compiled with the TLSDESC dialect at all. The recommended fast path was never active, but the profiler could still read the resulting legacy TLS access. 

We changed the spec to recommend TLSDESC rather than require it. TLSDESC is difficult to produce consistently across the build and runtime combinations SDKs encounter, so the reader follows the pragmatic rule of being liberal in what it accepts and recognizes every access model it can resolve. We also built self-test support into our libdatadog Rust library so that any SDK can detect at startup which TLS model it actually got and warn if it ended up on the slow path.

  • Rust can’t export a TLS symbol. LLVM doesn’t currently support emitting a TLS symbol into the ELF dynamic symbol table (.dynsym) from “pure Rust” code. After a couple of iterations, Datadog’s own Rust implementation now uses inline assembly to get one symbol consistently visible to external readers. It’s not as terrifying as it sounds and is easy to exhaustively test, but it means the implementation can’t consist entirely of Rust code and increases the cognitive load of working on this module. 

  • You can’t rely on the extra 512-byte space kept by glibc. For libraries loaded via dlopen (the JNI case), TLSDESC can optimize to static placement only if glibc’s surplus TLS space hasn’t already been consumed by other libraries (and musl has no surplus at all). In practice, for glibc, this works well, but we can’t guarantee it. The spec acknowledges this: DTV resolution is the correct fallback, and readers must support it.

We documented each of these sharp edges and built test coverage for them before the OTEP was merged. The ctx-sharing-demo repository now contains writer and reader examples for every combination we encountered, serving as both a test suite and a reference for implementers.

Avoiding synchronization on the hot path

The consistency model is also different from process context and worth highlighting. A profiler reads thread context only while that thread is stopped or interrupted for sampling. The thread isn’t mutating its own record at the same time. 

Writers need compiler fences and volatile writes to stop the compiler from reordering thread-context publication, but they don’t need runtime CPU barriers on every context update. Those compiler fences don’t generate CPU instructions themselves, and this detail keeps CPU synchronization off an already hot path.

An SDK can choose between two publication patterns: It can build records associated with logical contexts and swap the TLS pointer as they become active, or keep one record per thread and clear its valid flag while updating it in place. Both reuse storage, avoiding an allocation on every attachment.

Validating the design in Java

Datadog’s Java implementation of the specification demonstrates what these design choices buy in practice. The current implementation uses JNI to locate and update the current carrier thread’s native context record, with cached attribute encodings to avoid repeated string conversion and dictionary lookups. An earlier version wrote directly through a DirectByteBuffer, but we replaced it to address a use-after-free risk when virtual threads migrated.

We measured the previous Datadog-specific implementation and the OpenTelemetry thread context implementation on the same Linux x86_64 host with an Intel Xeon Platinum 8175M, Temurin 25.0.3. Java Microbenchmark Harness (JMH) reported average time across two forks, each with three one-second warmup iterations and five two-second measurement iterations. The standalone Set one attribute measurement used six forks.

The result:

OperationPrevious Datadog-specific implementationOpenTelemetry thread context implementation
Set trace context37.5 ns31.3 ns
Set one attribute (cache hit)172.4 ns60.9 ns
Set context and one attribute226.4 ns91.2 ns

At 91.2 ns for setting context and one cached attribute, 100,000 such updates per second would consume approximately 0.9% of one CPU core, based on these microbenchmarks. Per-operation cost also stayed nearly constant from one to four threads, with no evidence of false-sharing overhead on this host.

These results demonstrate the layout’s intended hot-path use: Java can publish trace context and request attributes with low overhead. The new OpenTelemetry implementation also replaced the Datadog-specific mechanism previously used to connect traces and profiles.

One record format, several runtime-specific discovery paths

Not every runtime directly maps managed threads to operating-system threads—or even exposes threads at all. We designed the TLS publication mechanism and the Thread-Local Context Record as separable pieces so runtimes can share most of the logic even when they might need different mechanisms to discover where the context lives.

Java publishes context through a native component invoked from the runtime, as described above. For Ruby, Python, .NET, and other Datadog SDKs, the shared Rust library libdatadog provides the write path. 

That implementation has gone through its own rounds of performance work: cross-language link-time optimization (LTO) to inline across Rust and C boundaries, and replacing a C code dependency with inline assembly to eliminate a Rust-to-C hop entirely. Together, these changes reduce the work performed across language boundaries during span activation.

Python can use the same native component, but detecting asynchronous context changes differs by Python version. Python 3.14 introduced context watchers through PyContext_AddWatcher. Older versions require runtime instrumentation to republish context when an asynchronous framework switches tasks. Ruby and .NET use native extensions or FFI bindings into libdatadog.

Go needs a different path. Goroutines move between operating-system threads, so OS-thread-local storage can’t reliably represent the context of a goroutine. The OpenTelemetry eBPF Profiler already understands Go’s pprof labels, so a Go SDK can announce that schema through process context and let the profiler read goroutine labels directly.

Node.js presents a similar mismatch for a different reason. Its asynchronous execution model can change logical context repeatedly on the same operating-system thread, and a design that crossed Node-API on every attach and detach would put a native boundary crossing on one of the runtime’s hottest paths. Work with Polar Signals showed a better direction: Discover the active context through Node.js-specific runtime structures while reusing the same Thread-Local Context Record layout. The reader keeps one parser even though Node.js uses a different route to reach the bytes.

This is the balance the OTEP tries to strike. It standardizes enough to make SDKs and profilers interoperable, but it doesn’t pretend that Java threads, Python contexts, Go goroutines, and Node.js asynchronous resources are the same abstraction.

We’ve also validated how these pieces work together end to end with Java in an integration test environment, from SDK publication through the full-host profiler and profiling backend. That validation was important because each individual component can appear correct while the final profile still loses an attribute between formats or systems.

Context turns system-wide profiles into application telemetry

Full-host profiling gives us a consistent view across applications, runtimes, and native libraries without requiring a separate profiler integration for every process. Process context identifies the application, while thread context connects individual samples to the work happening at that moment. Together, these two sources of information give profilers and SDKs a common foundation for connecting profiles to application telemetry without giving up system-wide coverage.

Our next steps are to expand support across Datadog and OpenTelemetry SDKs, validate overhead across runtimes, and continue the Node.js-specific design. Longer term, the same pattern could support out-of-process observability components beyond profilers and operating systems beyond Linux.

Ultimately, the goal isn’t merely to collect more stacks. It’s to make profiles collected once at the host level as connected and actionable as the rest of an application’s telemetry. 

We’re hiring! If solving low-level systems and observability problems like these interests you, explore open roles at Datadog.

Start monitoring your metrics in minutes