ByteGuideHub
Observability & Performance Engineering • • 11 min read

Self-Hosted eBPF Continuous Memory Profiling for Go and Rust Services: A Practical Guide

Deploy eBPF-powered continuous memory profiling for Go and Rust microservices. Step-by-step guide covering kernel prerequisites, symbol resolution, flamegraph pipelines, and low-overhead production rollout.

Sponsored / Ad Space

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 uprobes on 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/pprof needs an endpoint; dhat needs 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

RequirementMinimumRecommendedWhy
Kernel version4.185.8+BTF, sleepable BPF, better uprobe support
CONFIG_BPF_SYSCALLrequiredrequiredCore BPF
CONFIG_DEBUG_INFO_BTF—requiredCO-RE portability, no header compilation
CONFIG_PERF_EVENTSrequiredrequiredStack trace capture
CAP_SYS_ADMIN / CAP_BPFrequiredrequiredLoad BPF programs
kernel.perf_event_paranoid≤ 2-1Unrestricted 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:

ToolLanguage supportBackendBest for
ParcaGo, Rust, C/C++, Python, JVMSelf-contained (S3/local)Fleet-wide continuous profiling with Prometheus integration
PyroscopeGo, Rust, Python, JVM, eBPFGrafana-nativeTeams already on Grafana stack
PixieGo, Rust, C/C++K8s-native (PEM)Kubernetes-only shops wanting zero-config
CorootMulti-languageSelf-hostedFull 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:

  1. Detect that a binary is Go (via .gopclntab section).
  2. Parse pclntab to resolve PCs — this is what go tool addr2line does internally.
  3. 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

IssueGo fixRust fix
Stripped symbolsRemove -s -w from ldflagsSet strip = false in [profile.release]
Mangled namesN/A-C symbol-mangling-version=v0
Inlined framesPreserve pclntab; agent parses inline treeInclude DWARF (debug = 1)
Shared librariesN/AKeep .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 /metrics for 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

KnobDefaultProduction-safeEffect
profiling-mem-sampling-ratio0.050.01–0.05% of allocations sampled
profiling-cpu-sampling-frequency19 Hz19 HzCPU profile rate (leave alone)
Stack depth12764Shallower = cheaper
Per-CPU buffersautobump on high-core nodesReduces 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

  1. Week 1 — shadow mode: deploy agent on 1 node, no alerting, validate symbolization.
  2. Week 2 — canary: 10% of nodes, monitor CPU overhead and profile freshness.
  3. Week 3 — fleet: full DaemonSet, enable Prometheus alerts.
  4. 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

FeatureParcaPyroscopePixieCoroot
Go symbols✅ pclntab✅✅✅
Rust symbols✅ DWARF✅⚠️ limited✅
Self-hosted✅ single binary✅ Helm✅ K8s only✅
Grafana integration✅ Prometheus + panel✅ native⚠️ via export✅
Storage backendS3, GCS, localS3, localLocal (PEM)Postgres
Overhead (typical)1–3%1–3%2–5%1–3%
Best fitFleet-wide profilingGrafana-native teamsZero-config K8sFull 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.

Sponsored / Ad Space