Hmm, this is a complex and highly technical request about building a production-grade eBPF-based continuous profiling system for container fleets. The user is clearly a systems engineer or SRE looking for architectural guidance, not just a tutorial.
I need to address all four aspects they mentioned: sampling strategy, data transport, privacy boundaries, and tuning. But first, I should acknowledge the inherent tension between profiling depth and system overhead - that's critical context.
For sampling, the key is hierarchical strategies: process-level for noise reduction, CPU-time based for fairness, and adaptive triggers for anomalies. The transport layer needs to consider both the volume (protobufs) and security (mTLS, per-tenant isolation). Privacy requires kernel-hardened filtering with eBPF before data leaves the node, plus optional redaction. Tuning is about observability into the profiler itself - metrics, dynamic adjustments, and burn-in periods.
The response should be structured but dense with operational details. I'll avoid basic eBPF explanations since the user likely knows them. Instead, focus on fleet-scale patterns and trade-offs. The conclusion should emphasize that this is a platform engineering effort, not just a tool installation.
Excellent question. Building a continuous profiling mesh (like a lightweight, always-on Pyroscope/Parca/Grafana Phlare) across a large container fleet using eBPF is a powerful but non-triral systems engineering challenge. It sits at the intersection of observability, security, performance, and cost.
Here is a comprehensive architecture and operational guide, structured around your four pillars.
Overarching Philosophy & Core Tension
The primary tension is resolution vs. overhead. eBPF can capture stack traces with nanosecond precision and minimal per-event overhead (~100ns), but doing so for every CPU cycle on every core in a large fleet is computationally and network-prohibitively expensive. The solution is a hierarchical, adaptive, and policy-driven sampling strategy, combined with efficient, secure, and tiered data transport.
1. Sampling Strategy: "Smart, Not Dumb"
The goal is to collect a statistically representative, low-noise sample of CPU time spent in user/kernel space, correlated with container/process identity.
| Strategy Layer | Mechanism & eBPF Hook | Purpose & Tuning Knobs |
|---|
| a) Process/Container Filtering | bpf_get_current_pid_tgid() + cgroup v2 (/proc/self/cgroup) maps. | Exclude system/kube processes. Start with a deny-list (kubelet, containerd, OS daemons). Use cgroup path whitelisting (only pods in kubepods.slice). |
| b) CPU-Time Based Sampling | perf_event-style periodic sampling (bpf_perf_event_output).Hook: sched:sched_switch (context switch) or cpu-clock raw tracepoint. | Capture stack when a process actually uses CPU.- sample_rate: Hz per CPU (e.g., 100Hz = 1 sample/10ms CPU time). Start low (49Hz to avoid packet coalescing).- stack_depth: e.g., 127 or 255 (balance depth vs. perf ring buffer pressure). |
| c) Frequency Control & Throttling | Global eBPF map rate_limit keyed by (cgroup_id, comm). | Prevent noisy containers from dominating.- Max samples/sec per container (e.g., 1000).- Max samples/sec per node (e.g., 100k). Violations drop samples. |
| d) Adaptive/Trigger-Based | Custom eBPF programs on sched:sched_stat_runtime (tracking runtime) or OOM/sigkill signals. | Increase sampling for "hot" or "dying" containers.- If a container's thread exceeds X ms runtime in Y seconds, temporarily boost its rate (10x for 30s).- On imminent OOM kill (via oom_score_adj), capture high-frequency sample burst. |
| e) On-Demand / Debug | User-space request via BPF map. A sidecar can write a (pid, duration) request to a map. eBPF program switches that PID's sampling to Fury Mode (e.g., 9999Hz) for N seconds. | For incident response. Triggered via kubectl debug, Prometheus alert, or operator command. Must be authenticated/authorized. |
Key Design: The sampling decision is made in-kernel, in the eBPF program. It checks the cgroup ID, consults the rate-limit map, and decides before capturing a stack whether to output it. This is the only way to avoid overwhelming user-space.
2. Data Transport: "Tiered, Secure, Efficient"
Collected stacks (stack_trace_id, cgroup_id, timestamp, cpu) must be shipped off-node.
| Tier | Component | Technology Choices | Considerations |
|---|
| 0. Kernel → User-space | eBPF Ring Buffer (bpf_ringbuf) | Mandatory. Over perf_buffer. Supports multiple consumers, less lock contention. | - Size: Critical. Needs to burst for 1-2 secs at peak (e.g., 256MB).- BPF_RB_NO_WAKEUP to avoid thundering herds.- Consumer polls continuously (busy-wait with EPOLL), never blocks. |
| 1. Node Agent Buffer | Local Buffer + Batcher | In-memory ring/queue (e.g., channel in Rust/Go). Batch size: ~500-5000 profiles/10-100KB. | - Backpressure: If agent is too slow, ring buffer overflows → track and expose dropped_samples_total metric.- Batch Compression: Snappy/LZ4 before network send. |
| 2. Transport Protocol | HTTP/2 gRPC or protobuf over TCP | Avoid HTTP/1.1 per-profile. Use streaming API (profiling.WriteProfiles). | - Connection pooling to central store.- TLS/mTLS mandatory.- Set-Cello (Write v. Flush): Buffer aggressively on agent, flush every N seconds or M bytes. |
| 3. Central Ingestion | Profile Store (Parca, Thanos Receive, Grafana Mimir) | Must support Prometheus remote write or similar bulk format. | - Shard by tenant/cgroup namespace.- High cardinality warning: cgroup_id is a 64-bit int, not a label. Store as __value__ in Parca format. |
| 4. Fallback Path |
Security: mTLS everywhere. Agent→Store auth via Kubernetes ServiceAccount JWT or SPIFFE. Network policies must restrict agent egress to only the store's port.
3. Privacy Boundaries: "Kernel-First Filtering"
The principle: Never let private data leave the node unfiltered.
| Boundary | Mechanism | Implementation |
|---|
| Kernel → User-space | eBPF pre-filtering. | - Symbol Stripping: eBPF program never captures kernel pointers. Use bpf_get_func_ip + bpf_probe_read_kernel_str to resolve to symbol name/offset only if in kernel space. User-space stack: resolve to module+offset or symbol name only if in a whitelisted binary (e.g., app_binary, libc). Never emit raw addresses from non-whitelisted binaries. |
| Node Agent → Store | Tenant/Cgroup Isolation. | - Agent runs as DaemonSet with hostPID: true, but uses cgroup v2 to identify pod.- Map pod UID/namespace to a tenant ID via downward API or CSI. All profiles are labeled with tenant ID at ingestion.- Store enforces per-tenant RBAC & quotas. |
| Store → UI | RBAC & Data Redaction. | - Grafana/Parça UI respects tenant isolation.- Optional advanced: Integrate with OpenTelemetry Semantic Conventions for service.name, use hash of pod name if PII concern.- Never expose raw inodes, filenames, or environment pointers. |
| Compliance (GDPR, etc.) | Right-to-be-Forgotten. | - Store must support deletion by tenant ID/pod UID.- Retention policy: Aggressive for raw profiles (e.g., 7 days), automated aggregation to flamegraphs (30-90 days).- No cross-tenant aggregation unless explicitly configured (e.g., "all services in namespace X"). |
Critical eBPF Code Pattern for Privacy:
// Inside eBPF stack capture helper
if (is_user_mode(ip)) {
// Resolve to binary name only if binary is in allowed list
if (!is_binary_allowed(pid)) {
// Mark as "unknown_app" and don't capture symbol
record_stack(ip, "unknown_app");
} else {
// Safe to resolve symbol
resolve_and_record(pid, ip);
}
} else {
// Kernel: resolve to [kernel.kallsyms] + offset (safe)
record_kernel_stack(ip);
}
4. Tuning & Observability: "You Can't Manage What You Can't Measure"
The profiling system itself must be profiled and tuned.
| Metric | Where to Export | Alert Thresholds & Tuning |
|---|
profiler_samples_collected_total | Node-exporter / Prometheus | Baseline. Sudden drop → agent crash, eBPF unload. |
profiler_samples_dropped_total | Critical. | > 1% of attempted → increase sample_rate? No! Decrease rate-limit or increase buffer. Usually indicates ring buffer overflow or agent backpressure. |
profiler_ringbuf_entries_avail | eBPF map via bpftool or agent | Should be > 10k. Near 0 → increase BPF ringbuf size (requires daemon restart). |
profiler_build_id_misses_total | Agent | Count of unknown build IDs (stripped binaries). Action: Ensure debug symbols (-dbg packages) are available or configure symbol resolution separately. |
profiler_oncpu_vs_offcpu_ratio | Calculated | Should reflect workload. 90% on-CPU for compute service, 10% for I/O wait service. Drastic change = sampling skew or workload change. |
| Agent Latency | Agent → Store (profiling_latency_seconds) | P99 should be < 5s. Spike = network congestion or store overload. |
| Per-Container Rate | Agent metrics with pod label | Watch for noisy neighbor. Use rate_limit map to throttle. |
Operational Tuning Loop:
- Day 1: Deploy with low default rate (e.g., 49Hz). Monitor
samples_collected vs. node_cpu_seconds_total. Target < 0.1% total CPU overhead.
- Week 1: Identify low-activity services (low samples). Tune up their rate via
CgroupProfileConfig CRD (e.g., 98Hz for payment-service).
- Continuous: Watch
dropped_samples. If >0.5%, either:
- Increase node agent resources.
- Reduce global
sample_rate (least desirable).
- Add more
replicas to the profiling store.
- Incident Mode: Trigger
on-demand high-rate profiling for affected services via kubectl annotate pod <name> profiling-mode=fury.
Putting It All Together: Architecture Diagram
[Container Pods]
│ (cgroup v2 ID)
▼
[eBPF Programs (in kernel)]
├─► Rate Limit Map (per-cgroup)
├─► Allow-list Map (binaries)
└─► Ring Buffer (batched stacks)
│ (polled continuously)
▼
[DaemonSet pod: profiling-agent]
├─► De-aggregate by cgroup → (pod UID, namespace)
├─► Resolve Build IDs (via container `/proc/<pid>/map_files` or central symbol store)
├─► Batch & Compress (Snappy)
├─► mTLS → gRPC stream
└─► ***Metrics & Debug Endpoints*** (`/metrics`, `/debug/pprof`)
│
▼ (HTTPS, authorized)
[Central Store (Parca/Thanos)]
├─► Index by: (tenant_id, namespace, pod, timestamp, function)
├─► Long-term Storage (TSDB/Columnar)
└─► Query API (Flamegraph, Top, Diff)
│
▼
[UI: Grafana / Parca UI]
└─► RBAC: User sees only their tenant's profiles
Critical Operational Requirements
- Kernel Version: Requires 5.5+ for full
bpf_ringbuf and cgroup v2 attach. 5.10+ is ideal.
- Container Runtime: Must support cgroup v2 (containerd 1.6+, CRI-O 1.24+). Kubernetes 1.24+ defaults to it.
- Privileges: DaemonSet needs
privileged: true or cap_sys_admin to load eBPF programs and read /sys/kernel/btf. This is the biggest security hurdle. Consider:
- Running agent as a node-local daemon (not in k8s).
- Using KSOCK or Cilium eBPF if already deployed.
- Symbol Resolution:
- In-cluster: Mount host's
/usr/lib/debug and container /proc/<pid>/root into agent. Complex.
- Out-of-band: Ship
build IDs to a central symbol server (like debuginfod). Agent sends (build_id, offset) and server responds with (binary_name, function_name).
- Cost: Profile data is high-cardinality. Estimate ~100-500 bytes per profile. At 1k profiles/sec/node, that's ~8-40 GB/node/day. Storage and network costs dominate.
Conclusion
This is not a "drop-in" tool but a platform engineering project. Start with a single-node proof-of-concept, measure overhead obsessively, then expand fleet-wide with a phased rollout (canary nodes, then namespaces). The key is the in-kernel sampling policy—it must be adaptive and fair to survive in a multi-tenant environment. The privacy model must be kernel-enforced, not just an application-level filter.
Recommended Stack to Build Upon: Don't start from scratch. Fork and extend Parca (best open-source agent/store) or Grafana Pyroscope, adding your custom eBPF sampler and cgroup-aware rate limiter as a plugin. Their ingestion APIs and UIs are already built. Your value-add is the fleet-scale, secure, and tunable eBPF policy layer.