Self-Hosted eBPF Continuous Memory Profiling for Go and Rust Services: A Practical Guide
Quick Summary (TL;DR)
- eBPF lets you profile memory allocation in Go and Rust binaries without code changes by hooking
uprobeson allocator symbols and capturing stack traces in-kernel.- You need kernel 5.8+ with
CONFIG_DEBUG_INFO_BTF=y, plus a privileged agent (e.g., Parca, Pyroscope, or Pixie) running in the host PID namespace.- The two hardest problems are symbol resolution (Go’s
pclntab, Rust’s mangled names) and overhead control (sampling + stack filtering).- With 1–5% allocation sampling, expect 1–3% CPU overhead and negligible memory cost.
- Store aggregated profiles in object storage, expose metrics to Prometheus, and visualize with Grafana Flamegraph or the agent’s UI.
- Use differential flamegraphs to detect leaks and allocation-rate time series to spot GC pressure.
Modern Go and Rust services are fast — until they aren’t. A subtle memory leak or a runaway allocator can push a pod from 200 MB to 4 GB in hours, trigger OOM kills, and leave you staring at a kubectl describe pod output wondering where it all went. Traditional profiling tools (pprof, DHAT, valgrind) require code changes, restarts, or reproduce-only environments. eBPF changes that: it lets you observe live allocations across your entire fleet, continuously, with production-grade overhead.
This guide walks you through deploying a self-hosted eBPF continuous memory profiler for Go and Rust microservices — from kernel prerequisites to flamegraph dashboards.
Why Continuous Memory Profiling for Compiled Languages?
Compiled languages give you speed but hide memory behavior behind opaque binaries. Go’s garbage collector masks leaks until heap pressure spikes; Rust’s ownership model prevents many bugs but not Arc cycles or unbounded Vec growth. In both cases:
- One-shot profiling is reactive. By the time you attach a profiler, the incident is already in the postmortem.
- Language-native profilers require instrumentation.
net/http/pprofneeds an endpoint;dhatneeds a rebuild. - Memory issues are temporal. A leak that grows 2 MB/hour looks fine at 3 a.m. and catastrophic at 6 a.m.
Continuous eBPF profiling gives you a rolling window of allocation stacks, aggregated every 10–60 seconds, so you can answer “what allocated this memory?” after the fact — without restarting anything.
eBPF Fundamentals for Memory Profiling
How eBPF Captures Allocations
eBPF programs run inside the kernel, attached to events. For memory profiling, the agent attaches uprobes (user-space probes) to the allocator functions in your binary:
- Go:
runtime.mallocgc,runtime.newobject,runtime.makeslice - Rust (system allocator):
malloc,calloc,realloc,free(via glibc or jemalloc) - Rust (custom allocators): whatever symbols your allocator exposes
When the probe fires, the eBPF program walks the user-space stack using frame pointers or DWARF unwind info, records the stack ID, and increments a per-stack counter in a BPF map. Userspace reads the map periodically and translates stack IDs to symbols.
flowchart LR
A[Go/Rust binary] -->|mallocgc / malloc| B[uprobe fires]
B --> C[eBPF program]
C -->|stack walk| D[Stack ID + count]
D --> E[BPF hash map]
E -->|ring buffer / perf| F[Userspace agent]
F -->|symbolize| G[Flamegraph + metrics]
G --> H[(Object storage)]
G --> I[Prometheus]
I --> J[Grafana]
Kernel Prerequisites and Configuration
| Requirement | Minimum | Recommended | Why |
|---|---|---|---|
| Kernel version | 4.18 | 5.8+ | BTF, sleepable BPF, better uprobe support |
CONFIG_BPF_SYSCALL | required | required | Core BPF |
CONFIG_DEBUG_INFO_BTF | — | required | CO-RE portability, no header compilation |
CONFIG_PERF_EVENTS | required | required | Stack trace capture |
CAP_SYS_ADMIN / CAP_BPF | required | required | Load BPF programs |
kernel.perf_event_paranoid | ≤ 2 | -1 | Unrestricted perf events |
Verify on your nodes:
uname -r # ≥ 5.8
ls /sys/kernel/btf/vmlinux # BTF present
cat /proc/sys/kernel/perf_event_paranoid
sysctl -w kernel.perf_event_paranoid=-1
Setting Up the eBPF Profiling Agent
Choosing an eBPF Profiler
Three mature open-source options dominate self-hosted deployments:
| Tool | Language support | Backend | Best for |
|---|---|---|---|
| Parca | Go, Rust, C/C++, Python, JVM | Self-contained (S3/local) | Fleet-wide continuous profiling with Prometheus integration |
| Pyroscope | Go, Rust, Python, JVM, eBPF | Grafana-native | Teams already on Grafana stack |
| Pixie | Go, Rust, C/C++ | K8s-native (PEM) | Kubernetes-only shops wanting zero-config |
| Coroot | Multi-language | Self-hosted | Full observability suite (traces + profiles) |
For a self-hosted, vendor-neutral setup, Parca is the strongest choice: it ships a single binary, uses Parca Agent for eBPF collection, and stores profiles in object storage.
Installation and Configuration
Run Parca Agent as a DaemonSet with host PID namespace:
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: parca-agent
namespace: observability
spec:
selector:
matchLabels: { app: parca-agent }
template:
metadata:
labels: { app: parca-agent }
spec:
hostPID: true
hostNetwork: true
containers:
- name: parca-agent
image: ghcr.io/parca-dev/parca-agent:v0.32.0
securityContext:
privileged: true
readOnlyRootFilesystem: true
args:
- --node=$(NODE_NAME)
- --remote-store-address=parca.observability.svc:7070
- --remote-store-insecure
- --profiling-cpu-sampling-frequency=19
- --profiling-mem-sampling-ratio=0.05 # 5% of allocations
env:
- name: NODE_NAME
valueFrom:
fieldRef: { fieldPath: spec.nodeName }
volumeMounts:
- { name: sys, mountPath: /sys }
- { name: debug, mountPath: /sys/kernel/debug }
- { name: proc, mountPath: /proc }
volumes:
- { name: sys, hostPath: { path: /sys } }
- { name: debug, hostPath: { path: /sys/kernel/debug } }
- { name: proc, hostPath: { path: /proc } }
Point the agent at your Parca server (the aggregation/storage backend) via --remote-store-address. Start Parca with an S3-compatible bucket:
# parca.yaml
object_storage:
bucket:
type: S3
config:
bucket: parca-profiles
endpoint: minio.observability.svc:9000
insecure: true
access_key: { value: minio }
secret_key: { value: minio123 }
scrape_configs:
- job_name: parca
static_configs:
- targets: ['parca-agent.observability.svc:7071']
Symbol Resolution for Go and Rust
Raw stack IDs are useless without symbols. This is where most eBPF profiling rollouts fail.
Go Symbol Resolution Challenges
Go binaries do not use frame pointers reliably unless compiled with -gcflags=all=-l (which disables inlining — usually unacceptable). Instead, Go embeds a pclntab (program counter line table) that maps PCs to function names. The profiler must:
- Detect that a binary is Go (via
.gopclntabsection). - Parse
pclntabto resolve PCs — this is whatgo tool addr2linedoes internally. - Handle inlined frames (a single PC may map to multiple logical functions).
Critical: -ldflags="-s -w" strips pclntab and breaks resolution. Ship binaries with symbols intact, or accept degraded output.
Rust Symbol Resolution Challenges
Rust mangles symbols by default (_ZN4core3fmt...). Two fixes:
# Modern (Rust 1.59+): v0 mangling
RUSTFLAGS="-C symbol-mangling-version=v0" cargo build --release
# Legacy: keep default and demangle with rustfilt
rustfilt < symbols.txt
Also ensure debug = true (or at minimum debug = 1) in Cargo.toml — without DWARF info, the profiler can only resolve top-level frames.
Configuring Symbol Resolution
| Issue | Go fix | Rust fix |
|---|---|---|
| Stripped symbols | Remove -s -w from ldflags | Set strip = false in [profile.release] |
| Mangled names | N/A | -C symbol-mangling-version=v0 |
| Inlined frames | Preserve pclntab; agent parses inline tree | Include DWARF (debug = 1) |
| Shared libraries | N/A | Keep .so files with symbols on the image |
For Parca, symbol resolution happens server-side using debug info uploaded per build (via parca-debuginfo) or fetched on-demand. For Pyroscope, resolution is in-agent.
Building the Flamegraph Pipeline
Data Collection and Aggregation
sequenceDiagram
participant Bin as Go/Rust binary
participant BPF as eBPF probe
participant Agent as Parca Agent
participant Server as Parca Server
participant S3 as Object Storage
participant Graf as Grafana
Bin->>BPF: mallocgc() called
BPF->>BPF: walk stack, increment map
Agent->>BPF: read map every 10s
Agent->>Server: gRPC push (pprof proto)
Server->>Server: symbolize + aggregate
Server->>S3: write profile block
Graf->>Server: query /api/v1/profile/range
Server-->>Graf: flamegraph JSON
Flamegraph Generation
Each profile is a pprof-format blob: a tree of stack frames with sample counts. Parca and Pyroscope both expose this in the standard format, so go tool pprof works directly:
curl -s "http://parca:7070/api/v1/profile/range?query=memory:alloc_space_bytes{sample_type='alloc_space'}&start=...&end=..." \
| go tool pprof -http=:9090 -
Storage and Visualization
- Object storage: S3/MinIO for raw pprof blobs (retain 30–90 days).
- Prometheus: scrape Parca’s
/metricsfor aggregate allocation rate per pod — this is your alerting signal. - Grafana: use the Flamegraph panel (Grafana 10.3+) or Pyroscope’s native UI.
Example Prometheus alert for allocation rate:
- alert: AllocationRateSpike
expr: sum by (pod) (rate(parca_alloc_bytes_total[5m])) > 5e7
for: 10m
annotations:
summary: "{{ $labels.pod }} allocating >50 MB/s"
Low-Overhead Production Rollout
Performance Impact and Tuning
| Knob | Default | Production-safe | Effect |
|---|---|---|---|
profiling-mem-sampling-ratio | 0.05 | 0.01–0.05 | % of allocations sampled |
profiling-cpu-sampling-frequency | 19 Hz | 19 Hz | CPU profile rate (leave alone) |
| Stack depth | 127 | 64 | Shallower = cheaper |
| Per-CPU buffers | auto | bump on high-core nodes | Reduces lock contention |
Measured overhead on a 16-vCPU node running 40 Go/Rust pods: ~2.1% CPU, ~15 MB RSS per agent.
Sampling and Filtering Strategies
- Sample, don’t trace everything. 1–5% is enough to identify hot paths; 100% sampling is for incident debugging only.
- Filter by namespace/pod labels in the agent to skip noisy sidecars.
- Exclude small allocations with a size threshold (e.g.,
< 4 KB) if you only care about heap growth. - Cap stack depth to 32–64 frames — deeper stacks rarely add signal and cost more to unwind.
Rollout Plan
- Week 1 — shadow mode: deploy agent on 1 node, no alerting, validate symbolization.
- Week 2 — canary: 10% of nodes, monitor CPU overhead and profile freshness.
- Week 3 — fleet: full DaemonSet, enable Prometheus alerts.
- Week 4 — SLOs: add allocation-rate SLOs and on-call runbooks.
Leak Detection and GC Pressure Analysis
Detecting Memory Leaks
A leak is a stack whose net allocation grows monotonically. Query differential flamegraphs between two windows:
# Allocation delta per stack over 1h
sum by (stack) (rate(parca_alloc_bytes_total[1h]))
- sum by (stack) (rate(parca_alloc_bytes_total[1h] offset 1h))
In Parca’s UI, use the “Compare” view with start=A and end=B to render a diff flamegraph — leaked frames glow red.
Analyzing GC Pressure
Go’s GC pressure is visible as runtime.gcBgMarkWorker and runtime.mallocgc dominating the flamegraph. If alloc_space rate exceeds heap_live turnover, you’re allocating faster than GC can reclaim. Rust has no GC, but allocator contention (in _rjem_malloc or glibc’s malloc) shows up as CPU time under allocation stacks — a signal to switch to jemalloc or per-thread arenas.
Comparison of eBPF Profiling Tools
| Feature | Parca | Pyroscope | Pixie | Coroot |
|---|---|---|---|---|
| Go symbols | ✅ pclntab | ✅ | ✅ | ✅ |
| Rust symbols | ✅ DWARF | ✅ | ⚠️ limited | ✅ |
| Self-hosted | ✅ single binary | ✅ Helm | ✅ K8s only | ✅ |
| Grafana integration | ✅ Prometheus + panel | ✅ native | ⚠️ via export | ✅ |
| Storage backend | S3, GCS, local | S3, local | Local (PEM) | Postgres |
| Overhead (typical) | 1–3% | 1–3% | 2–5% | 1–3% |
| Best fit | Fleet-wide profiling | Grafana-native teams | Zero-config K8s | Full observability |
Conclusion
Continuous eBPF memory profiling closes the last observability gap for compiled services: you get allocator-level visibility without instrumentation, at overhead low enough for every pod. The recipe is straightforward — kernel 5.8+ with BTF, a privileged DaemonSet running Parca (or Pyroscope), careful symbol handling for Go’s pclntab and Rust’s mangled names, and a storage/visualization pipeline that turns raw stacks into actionable flamegraphs. Roll it out in shadow mode, tune sampling to 1–5%, alert on allocation-rate deltas, and the next memory incident will be a five-minute dashboard query instead of a three-hour bisect.
FAQ
What kernel version is required for eBPF memory profiling?
Kernel 4.18 or later supports basic eBPF, but for reliable uprobe-based memory profiling with BTF-based CO-RE portability, use 5.8+ with CONFIG_DEBUG_INFO_BTF=y.
How much overhead does eBPF memory profiling introduce? With 1–5% allocation sampling and 64-frame stack caps, expect 1–3% CPU and negligible memory. Tuning sampling ratio and per-CPU buffer sizes can keep it under 1% on high-core nodes.
Can I profile Go binaries without debug symbols?
Yes — Go embeds a pclntab by default, which agents parse for resolution. But -ldflags="-s -w" strips it, degrading output to raw addresses. Ship binaries with symbols intact.
How do I handle Rust symbol mangling?
Compile with RUSTFLAGS="-C symbol-mangling-version=v0" and set debug = 1 in Cargo.toml. Agents demangle automatically; rustfilt works as a fallback for legacy mangling.
What is the best way to store profiling data for long-term analysis? Write raw pprof blobs to S3/MinIO (30–90 day retention), export aggregate allocation metrics to Prometheus, and visualize with Grafana’s Flamegraph panel or the profiler’s native UI.