Continuous Profiling in Go: Using eBPF and Pyroscope with OTel
In the world of high-performance Go microservices, the difference between a sub-100ms response time and a cascading failure often hides in the CPU cycles we can't see. Traditional observability—metrics, logs, and traces—tells us that a service is slow, but it rarely tells us exactly why at the function level. While Go developers have long relied on pprof for ad-hoc profiling, the shift toward continuous profiling is changing how we manage production performance.
By combining the efficiency of eBPF (Extended Berkeley Packet Filter) with the standardization of OpenTelemetry and the storage capabilities of Pyroscope, we can achieve a "holy grail" of observability: always-on, low-overhead profiling that identifies CPU hotspots without modifying a single line of application code.
The Limitations of Ad-hoc Profiling
Most engineers are familiar with the reactive workflow: a Prometheus alert fires, we notice high CPU usage on a specific pod, and we manually trigger a go tool pprof capture. This approach has three major flaws:
- The "Heisenbug" Problem: By the time you connect to the pod and start the profile, the spike may have passed.
- Lack of Context: A 30-second profile doesn't tell you if the current CPU usage is an anomaly or a slow trend over several days.
- Instrumentation Overhead: Manual
pprofendpoints require code changes and expose internal diagnostic ports, which can be a security concern if not managed correctly.
Continuous profiling solves this by treating profile data like metrics—sampled constantly, stored historically, and searchable across your entire fleet.
The Architecture: eBPF meets OpenTelemetry
The modern profiling stack relies on three core components: the eBPF Profiler, the OpenTelemetry Collector, and a Profiling Backend (Pyroscope).
Why eBPF?
eBPF is a kernel technology that allows us to run sandboxed programs in the Linux kernel without changing kernel source code or loading modules. For profiling, this is revolutionary. An eBPF-based profiler can observe the stack traces of every process running on a host by periodically interrupting the CPU and recording the instruction pointer.
Because it operates at the kernel level, it has visibility into both user-space code (your Go service) and kernel-space execution (syscalls, network processing). Most importantly, it requires zero instrumentation. You don't need to import a library or restart your service.
The Role of OpenTelemetry
OpenTelemetry (OTel) is the industry standard for telemetry data. While OTel initially focused on traces, metrics, and logs, the Profiling Signal is the fourth pillar currently being standardized. Using OTel as the transport layer ensures that your profiling data follows the same tagging and metadata conventions as your traces, allowing for seamless correlation.
Setting Up the Stack
To implement this, we typically deploy a Pyroscope agent (which uses eBPF) alongside our Go applications, or we use the OpenTelemetry Collector with the Pyroscope receiver.
1. The Go Microservice (The Target)
Consider a standard Go microservice performing heavy JSON processing. Even with Go's efficient encoding/json, high-volume services often spend 30-40% of their CPU time in reflection-based marshaling.
func processRequest(w http.ResponseWriter, r *http.Request) { // Imagine a large, nested struct being marshaled repeatedly data := fetchLargeDataset() payload, _ := json.Marshal(data) w.Write(payload) }
In a traditional setup, you wouldn't know this is a hotspot until the CPU hits 90%. With continuous profiling, this function will immediately stand out in a flame graph.
2. Configuring the OpenTelemetry Collector
The OTel Collector acts as the intermediary. It receives profiles from the eBPF agent and exports them to Pyroscope. This decoupling allows you to switch backends or redact sensitive data before it leaves your infrastructure.
receivers: pyroscope: endpoint: 0.0.0.0:8080 exporters: pyroscope: endpoint: "http://pyroscope-server:4040" sending_queue: enabled: true service: pipelines: profiles: receivers: [pyroscope] exporters: [pyroscope]
3. Deploying the eBPF Profiler
The Pyroscope eBPF profiler (often deployed as a DaemonSet in Kubernetes) monitors the host. It uses the perf_event_open system call to attach to CPU cycles. Every time a sample is taken (e.g., 100 times per second), the profiler unwinds the stack for the currently running process.
For Go services, the profiler is smart enough to read the Go symbol table (even if the binary is stripped, though keeping symbols is recommended) to map memory addresses back to human-readable function names like runtime.mallocgc or main.processRequest.
Identifying CPU Hotspots: A Real-World Scenario
Once the data flows into Pyroscope, you are presented with a Flame Graph. For a Go engineer, this is where the magic happens.
Case Study: The Hidden Cost of Regex
I recently worked on a service where CPU usage would gradually climb over 24 hours. Metrics showed high CPU, but traces showed normal latency for the database. By looking at the continuous profile in Pyroscope, we saw a massive "plateau" in the flame graph under regexp.(*Regexp).doExecute.
It turned out a junior developer was calling regexp.Compile inside a for loop instead of defining the regex as a global variable.
// The Hotspot Found by Profiling func validateInput(input string) bool { re := regexp.MustCompile(`^[a-z0-9]+$`) // Re-compiling on every call! return re.MatchString(input) }
In a local test, this might take microseconds. In production, under 10k requests per second, the overhead of re-parsing the regex state machine was consuming 15% of the total cluster CPU. Without continuous profiling, identifying this would have required a lucky pprof capture during a peak period.
Deep-Diving into the Go Runtime
Continuous profiling also reveals issues within the Go runtime itself. You might notice significant time spent in runtime.gcBgMarkWorker. This indicates high GC Pressure. While this is a CPU hotspot, the root cause isn't CPU-bound logic—it's excessive heap allocations. By switching to the "Allocated Memory" view in your profiler, you can identify which functions are creating the most garbage, leading to the CPU spikes you see in the "CPU Time" view.
Handling Overhead and Security
A common concern with "always-on" profiling is the performance hit. Fortunately, eBPF is incredibly efficient.
- Sampling Frequency: By default, profiling at 100Hz (100 samples per second per CPU core) typically results in less than 1% CPU overhead. For most production environments, this is a negligible price to pay for the visibility gained.
- Stack Unwinding: Unwinding Go stacks is slightly more complex than C because of how Go manages its stacks, but modern eBPF profilers use Frame Pointers or DWARF info to do this efficiently without pausing the application.
- Security: Since the eBPF profiler runs in the kernel, it requires
CAP_SYS_ADMINorCAP_BPFprivileges. In locked-down Kubernetes environments, this requires careful configuration of SecurityContexts. However, because it is passive (it only reads state), it is generally considered safer than active debuggers that can modify memory.
Correlating Profiles with Traces
The real power of the OpenTelemetry ecosystem is correlation. When a trace shows a specific request took 2 seconds, you can click on that trace and see the exact profile for the thread that handled that request.
This is achieved by "tagging" the profile samples with the trace_id. While Go doesn't natively support passing metadata to the kernel for eBPF to pick up, the OpenTelemetry community is working on "pprof labels" and eBPF maps to bridge this gap. This allows you to filter your flame graph to show only the CPU cycles consumed by a specific high-priority customer or a specific API endpoint.
Best Practices for Production
If you're ready to implement continuous profiling in your Go stack, follow these senior-level guidelines:
- Keep Symbols in Binaries: Avoid using the
-s -wflags ingo buildfor production binaries. While they reduce binary size, they strip the symbol table and DWARF information, making profiles much harder to read. - Start in Staging: Deploy the eBPF agent to a staging environment first to baseline the overhead. Monitor the
node-exportermetrics for the hosts where the profiler is running. - Use Descriptive Labels: Ensure your OTel Collector attaches labels like
service.name,deployment.environment, andhost.name. This makes filtering the data in Pyroscope significantly easier. - Focus on the "Big Wins": Use the "Diff" view in Pyroscope. Compare the flame graph of "Today" vs. "Yesterday" after a deployment. This is the fastest way to catch performance regressions before they trigger an alert.
Conclusion
Continuous profiling is no longer a luxury reserved for the likes of Google or Netflix. With the maturity of eBPF and the standardization provided by OpenTelemetry, it has become a practical necessity for any team running Go microservices at scale.
By moving away from reactive, ad-hoc pprof sessions and embracing always-on profiling with Pyroscope, you gain a transparent view into your application's execution. You stop guessing why the CPU is spiking and start seeing the exact lines of code responsible. Start small: deploy an OTel-compatible profiler to one service, analyze the flame graph, and you’ll likely find that the first optimization you make pays for the implementation effort ten times over.