Deploying Grafana Pyroscope on Kubernetes: Continuous Profiling for Microservices

DevOps tutorial - IT technology blog
DevOps tutorial - IT technology blog

The Observability Blindspot in Distributed Microservices

At 2:00 AM, PagerDuty fires: an order-processing pod is pinned at 100% CPU. Simultaneously, a billing service steadily consumes RAM until the Linux OOM killer terminates it at 2.1 GB. Prometheus graphs confirm the resource saturation. Distributed tracing in Jaeger or Tempo reveals that p99 latency spiked from 110ms to 4.8 seconds on the /checkout route. Yet when you inspect your application logs, you find zero errors.

Metrics, logs, and distributed traces form the backbone of modern observability, but they leave an expensive blind spot. Metrics show that a container is burning CPU.

Traces show which network hop stalls. Neither reveals the exact function or code line consuming 75% of CPU cycles or hoarding hundreds of megabytes of uncollected heap memory. Running ad-hoc pprof commands or capturing JVM thread dumps during a live production outage is clumsy, disruptive, and usually happens long after the spike subsided.

Continuous Profiling: The Fourth Telemetry Pillar

Continuous profiling closes this gap by sampling stack traces across running processes 24/7. Because modern profilers run with minimal overhead—typically between 0.5% and 1.5% CPU—you can safely run them in high-throughput production clusters. Instead of scrambling for a 30-second snapshot mid-incident, you gain an unbroken historical record of execution across every node.

How Grafana Pyroscope Operates

Pyroscope aggregates stack samples into flame graphs. On a flame graph, the horizontal X-axis represents 100% of the sampled profile population (such as total CPU clock cycles or allocated heap bytes), sorted alphabetically to group similar call stacks. The vertical Y-axis visualizes call stack depth from root to leaf. Wider blocks directly signify greater resource consumption inside that function and its downstream callees.

On Kubernetes, Pyroscope collects data through two primary mechanisms:

  • eBPF Auto-Profiling: A DaemonSet hooks into Linux kernel tracepoints to sample compiled and native binaries (Go, Rust, C/C++, JVM, and Python runtimes) with zero code modifications or pod restarts.
  • Runtime Scrapers and SDKs: Language-level agents that scrape runtime endpoints, such as Go’s net/http/pprof, capturing granular memory allocations, goroutine counts, and mutex contention.

Deploying Pyroscope on Kubernetes

The following walkthrough sets up Pyroscope in monolithic mode for small-to-medium clusters (up to roughly 500 pods), followed by cluster-wide eBPF profiling and runtime memory scraping.

Step 1: Install the Grafana Pyroscope Server

Register the Grafana Helm repository and create a dedicated namespace:

helm repo add grafana https://grafana.github.io/helm-charts
helm repo update
kubectl create namespace pyroscope

For workloads generating under 2,000 active profile streams, a single-replica monolithic deployment backed by a 50 GB persistent volume offers reliable ingestion without the operational complexity of microservice mode:

cat <<EOF > pyroscope-values.yaml
pyroscope:
  persistence:
    enabled: true
    size: 50Gi
    storageClass: "gp3" # Adjust to your cluster storage class
  resources:
    requests:
      cpu: 500m
      memory: 1Gi
    limits:
      cpu: 2000m
      memory: 4Gi
EOF

helm install pyroscope grafana/pyroscope \
  --namespace pyroscope \
  -f pyroscope-values.yaml

Step 2: Deploy the Pyroscope eBPF DaemonSet

To capture CPU profiles across every container without rebuilding images, deploy the Pyroscope eBPF agent across your worker nodes:

cat <<EOF > pyroscope-ebpf-values.yaml
agent:
  config:
    server:
      endpoint: "http://pyroscope.pyroscope.svc.cluster.local:4040"
    ebpf:
      enabled: true
      collect_kernel_profile: false
      targets:
        - service_name: "k8s-workloads"
          kubernetes:
            enabled: true
EOF

helm install pyroscope-ebpf grafana/pyroscope-ebpf \
  --namespace pyroscope \
  -f pyroscope-ebpf-values.yaml

Once deployed, verify that the agent pods are healthy across all nodes using kubectl get daemonset -n pyroscope. The agent immediately attaches to kernel tracepoints and ships 15-second profile aggregates to port 4040.

Step 3: Scrape In-Depth Memory Profiles for Go and JVM

eBPF shines for CPU execution, but finding memory leaks requires runtime-level memory accounting. In Go services, import net/http/pprof to expose diagnostic endpoints, then use Kubernetes annotations to direct Pyroscope’s scraper or Grafana Alloy to poll them:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: payment-service
  namespace: production
spec:
  replicas: 3
  template:
    metadata:
      annotations:
        pyroscope.io/scrape: "true"
        pyroscope.io/application-name: "payment-service"
        pyroscope.io/port: "8080"
        pyroscope.io/profile-cpu: "true"
        pyroscope.io/profile-mem: "true"
    spec:
      containers:
        - name: payment-service
          image: myregistry/payment:v1.4.2
          ports:
            - containerPort: 8080

With this configuration, Pyroscope scrapes profile endpoints every 15 to 60 seconds. Developers can inspect heap states during live production incidents without restarting containers with specialized debug flags.

Step 4: Isolating Production Bottlenecks

Once profiles populate Grafana, two primary inspection workflows uncover the vast majority of performance regressions:

1. Diagnosing CPU Spikes with Diff Flame Graphs

When an unexpected CPU surge hits, switch the Pyroscope panel in Grafana to Diff View. Set your baseline to a normal traffic window (e.g., yesterday 14:00–14:30) and the comparison to the active incident window.

  • Red frames highlight functions consuming a larger percentage of CPU relative to baseline.
  • Green frames highlight functions that consumed less relative CPU share.
  • Frequent production culprits: In Go and Node.js microservices, wide red bars often pinpoint uncompiled regular expressions (such as calling regexp.MatchString inside tight HTTP loops), unbounded JSON deserialization of large payloads via json.Unmarshal, or lock contention in synchronized shared maps.

2. Unmasking Memory Leaks: alloc_space vs inuse_space

When tracking memory growth in Pyroscope, toggle between these two profile types:

  • alloc_space / alloc_objects: Measures the cumulative bytes allocated since process launch, including memory already reclaimed by garbage collection. Use this view to find allocation churn that strains the GC and triggers millisecond-long stop-the-world pauses.
  • inuse_space / inuse_objects: Measures the active memory retained in RAM. Compare two points on your service timeline. If a function’s inuse_space steadily expands over six hours without plateauing, you have pinpointed the exact slice append or unclosed connection cache leaking memory.

Field Tips for Production Stability

  • Verify Kernel Compatibility: eBPF profiling requires Linux kernel 4.18 or higher with BPF Type Format (BTF) enabled. Distributions like Ubuntu 22.04 LTS, Amazon Linux 2023, and Debian 12 run this out of the box. Kernels older than 5.4 may struggle with symbol resolution for dynamic runtimes.
  • Configure Storage Retention: Profiling generates dense telemetry. Retain 7 to 14 days of raw profiles on fast block storage, or configure Pyroscope’s compactor to offload compressed blocks to S3 or Google Cloud Storage for long-term capacity planning.
  • Enable Trace-to-Profile Pivoting: Link Pyroscope profiles with Grafana Tempo traces. When an engineer flags a checkout_process trace span taking 3,200ms, a single click opens the flame graph for that precise pod and timestamp, showing exactly which SQL driver or parsing function caused the stall.

Summary

Continuous profiling bridges the gap between high-level service metrics and raw source code. By pairing eBPF CPU auto-profiling with runtime memory scrapers in Grafana Pyroscope, engineering teams identify resource-hungry functions and memory leaks within minutes, keeping microservices fast and infrastructure costs predictable.

Share: