Header Banner Image
Your
Trusted
Get Fully AWS Funded
Cloud Migration

Debugging Python Memory Usage in Kubernetes with Memray

In our effort to monitor and debug memory usage in Python applications running inside Kubernetes, we explored several tools and strategies. Here's a breakdown of what worked, what didn't, and what to consider next.

The Goal

We aimed to:

  • Attach to a running Python process inside a Kubernetes pod

  • Profile its memory usage

  • Export insights (ideally to Grafana)

  • Avoid code changes or developer involvement where possible

What Worked: Memray from Within the Container

Using Memray for memory profiling turned out to be effective when executed inside the same container as the Python application.

Steps to Debug with Memray
  1. Connect to container via sidecar/debug container

  2. Install Memray and Dependencies:

  3. Find the Python Process:

  4. Attach Memray:

    Note: Attaching from a sidecar or ephemeral container did not work due to namespace isolation. Running inside the same container was required.

  5. View Summary:

Limitations
  • memray is best for on-demand profiling, not continuous monitoring

  • Cannot run from a sidecar or ephemeral container unless shareProcessNamespace: true and the memory namespace is somehow shared (not typical)

  • Output is not in a form Grafana can consume directly

Continuous Monitoring Options

Since Memray isn’t suited for long-term monitoring or Grafana integration, we explored other paths:

Pyroscope (to be explored)

Pyroscope is a continuous profiling tool that integrates with Grafana. It supports Python via:

  • pyroscope-python (requires code change)

  • py-spy in Pyroscope agent mode (code-free, works like strace)

However, Pyroscope's strength lies in CPU profiling. Memory profiling is more limited or indirect. Further investigation is needed to evaluate if it can replace or supplement Memray for memory metrics.

Next Steps
  • Explore py-spy with Pyroscope for code-free CPU profiling

  • Consider writing a lightweight Prometheus exporter using psutil to track RSS memory

  • Possibly batch export Memray data into a Grafana-compatible format (e.g., Prometheus scrape)


Stay tuned for a follow-up article on Pyroscope and profiling Python memory and CPU usage over time!

Resources