Application Performance with Grafana Pyroscope and k6
local graph
Chapter 13 — Application Performance with Grafana Pyroscope and k6
Section titled “Chapter 13 — Application Performance with Grafana Pyroscope and k6”This chapter will explore two tools, Pyroscope and k6. Pyroscope is a continuous profiling tool that allows users to collect very detailed information about the usage of system resources such as CPU and memory. k6 is a load testing tool that can be used to interact with an application via endpoints, or via a browser session in a scripted way.
With Pyroscope, we will see how to search data, which will give you a good understanding of how to make use of the data available. We will then show how to add instrumentation to collect this data using both an installed client and by adding a native language SDK to the application code. Finally, we will see how the new version of the Pyroscope architecture leverages Grafana’s knowledge of highly scalable storage platforms, using inexpensive block storage to set Pyroscope on a path toward offering truly continuous profiling for developers. This functionality will allow those of you who need visibility of code execution to improve operational cost or end user performance.
k6 will move a little away from observability into the very closely related field of load or performance testing. We will discuss the general principles of load testing and look at the different categories of load tests that you may need. Then, you will be introduced to the scripting language used by k6 to easily write tests that validate the application is performing as expected. We will see how k6 uses virtual users (VUs) to scale tests and create a significant load on an application, so you can use it to prove your applications are running as expected. Finally, we’ll see how k6 can be installed, and how it is versatile enough to even run as part of a CI pipeline, ensuring your applications are continuously load tested.
In this chapter, we’re going to cover the following main topics:
- Using Pyroscope for continuous profiling
- Using k6 for load testing
Using Pyroscope for continuous profiling
Section titled “Using Pyroscope for continuous profiling”First, let’s address the question of what continuous profiling is. As we outlined at the start of this book, a system is observable when the internal state of the system can be inferred from its external outputs. We have seen three types of output telemetry: logs, metrics, and traces. Profiling data is another form of telemetry. Profiling data is very low-level data that relates to a workload’s use of resources, such as the use of CPU or memory. As profiling tools analyze very low-level system data, they capture information such as the running time or the number of objects in memory of a specific application function. This is very powerful for domain experts to inspect how an application behaves, and this power can lead to significant performance and cost improvements. Profiling has been around for a long time, as anyone who has produced a stack trace will know. Pyroscope offers the ability to capture this profiling data continuously, with a default interval of 15 seconds. The ability to collect this telemetry continuously over the lifetime of an application can give insight into how an application runs over time, which can link the inner workings of the code base to specific user actions seen in logs, metrics, and traces.
In this section, we will briefly introduce Pyroscope. You will be shown how to search the data collected by Pyroscope. We will talk about configuring the client to collect profiles, and we will look at the architecture of the Pyroscope server.
A brief overview of Pyroscope
Section titled “A brief overview of Pyroscope”Pyroscope, also known as Grafana Cloud Profiles, was founded in 2020 and acquired by Grafana Labs in 2023. The Pyroscope team joined the team from a Grafana Labs experimental product called Phlare, and the product is now a standard offering from Grafana Cloud. Some of the key features of Pyroscope are as follows:
- Great horizontal scalability using the same architecture as Loki, Mimir, and Tempo
- Cheap storage for profile data
- Can store data locally or using Grafana Cloud
- High frequency of sampling, which produces very granular data
Now, let’s explore how we can examine the data collected by Pyroscope.
Searching Pyroscope data
Section titled “Searching Pyroscope data”Profile telemetry can be viewed using the Explore view in the Grafana UI by selecting a Pyroscope source. While the view is similar to Loki, Mimir, and Tempo, the query language is limited by the nature of the telemetry type; effectively, only selection functionality is available to select a signal from an application or group of applications by tag. This is the view you will see to select data from a Pyroscope source:

Figure 13.1 – Pyroscope query pane
The first view to look at is the Top Table view, as shown in Figure 13*.2*. For those of you who know the Linux top command, this view will be familiar. The view lists every function and the amount of time that has been spent on the function. The Self column shows the time spent on that function. The Total column shows the total time each function takes to run. This allows users to see functions that have a long running time. Long runtimes could indicate an inefficient function, but it could also indicate a function that is central to the application. Domain expertise is needed to understand where improvements could be made. This screenshot shows the Top Table view:

Figure 13.2 – Pyroscope Top Table view
The second view is the Flame Graph view. This chart is specifically designed to visualize profile data. Flame graphs were invented to be able to visualize stack trace output from applications to make debugging easier. Before we look at the view in Pyroscope, let’s take a look at a sample application stack trace:

Figure 13.3 – Example application stack trace
We can see there is a main() function, which is started when the application is run. This function calls the child functions, foo() and bar(), in order, and bar() also calls the baz() and qux() functions. A flame graph captures the hierarchical nature of these stack calls by grouping child functions under their parent. This allows us to see how deep the call stack is by looking at the y axis. The total population of functions is shown in the x axis; importantly, this does not represent the time but rather each function that was seen on the call stack during the sampling period. The visualization of duration is shown in a flame graph by the width of the box for each function, which shows the total time spent on a function during the sampling period. Let’s have a look at how this looks in practice:

Figure 13.4 – Example flame graph from the stack trace
In this example flame graph, we can see that the baz() function takes up a significant portion of the operating time. In some applications, this may be completely expected behavior; in other applications, this may indicate a function that needs to be optimized.
Very few applications are as simple as this example. Let’s look at a real flame graph from the OpenTelemetry Demo application:

Figure 13.5 – A real flame graph
We’ve seen how continuous profiling tools such as Pyroscope can be valuable in creating efficient code and debugging issues. Let’s now look at how to collect profile data.
Continuous profiling client configuration
Section titled “Continuous profiling client configuration”There are currently three separate ways to collect data for Pyroscope, although we expect this to evolve as Pyroscope is quite a new piece of technology. We would recommend the Grafana Labs blog for those of you who want to keep up to date with the latest developments from this exciting technology (https://grafana.com/blog/). Let’s explore how to set up each one:
- Extended Berkeley Packet Filter (eBPF) client: The first way to collect profile data for Pyroscope is to make use of a Linux kernel-level tool called eBPF. This tool allows the profiling client to view the trace information for all applications running on the server or node. The eBPF client combines this data with metadata on the data source (for example, a Kubernetes Pod or namespace) and then sends this profile information to a Pyroscope backend. The following diagram shows a simplified view of how eBPF stores data for the Pyroscope client to collect:

Figure 13.6 – eBPF client process
With eBPF, the kernel collects profile data, as well as several other types of data, and stores it in eBPF maps. Pyroscope links into the eBPF maps, packages the data, and then sends it for storage in the configured backend.
- Native language instrumentation: The second way to collect profile data is to use a language-specific Pyroscope SDK to add instrumentation to your application. SDKs are currently provided for Go, Java,.NET, Python, Ruby, Rust, and Node.js. Apart from the Go SDK, all these libraries only support a push mode of operation. Go supports both a push and a pull mode of operation; the pull mode allows the Grafana agent to collect profile data from a scraping endpoint published by the application. In push mode, it is currently necessary to add the Pyroscope server address, basic authenticated username, and password at the application level, although as this tool matures, we’re sure this will become easier to manage in an operational environment.
- Instrumenting Lambda functions: Pyroscope also provides tooling for AWS Lambda functions. This consists of a Lambda extension that is loaded as a layer when the function is triggered. This allows the profiling tooling to collect the required profile telemetry asynchronously without impacting the operation of your Lambda function. Like the native language instrumentation, environment variables must be provided with the remote address for the Pyroscope backend and the relevant authentication tokens. For teams running serverless functions, this adds the capability to look inside the Lambda function black box and allows teams to answer questions such as, Why is my Lambda costing so much?, Why do I have such high latency?, and Why is my function failing so often?
There are benefits and drawbacks to the eBPF client, the SDK, and the Lambda approaches: their usage is dependent on the use case. Here are some benefits and drawbacks for each method:
| Instrumentation method | Benefits | Drawbacks |
|---|---|---|
| eBPF | System-wide whole system profiles are easy to collect. Infrastructure metadata is easy to add (for example, Kubernetes Pod or namespace). Easy to manage a multi-language or large system. Can combine with native language instrumentation. | Linux kernel constraints. Limited ability to tag user-level code. Some profile types are not performant to collect (for example, memory use). More complex for local development environments. |
| Native language | Flexible tagging of code. Detailed profiling of specific parts of code. Ability to profile other types of data (for example, memory use). Simple to use in local development environments. | Managing a multi-language or large system is difficult. Difficult to auto-tag infrastructure metadata (for example, Kubernetes Pod or namespace). |
| Lambda functions | Allows for collection of trace data from serverless functions. Links with the native language support to instrument the function. | Currently only available for AWS Lambda. |
Table 13.1 – Advantages and drawbacks of Pyroscope instrumentation methods
We’ve looked at the different ways to set up applications and clients to collect profile data. Now, let’s consider the storage and search architecture of Pyroscope.
Understanding the Pyroscope architecture
Section titled “Understanding the Pyroscope architecture”Pyroscope 1.0 has introduced a major change to the architecture of Pyroscope. This leverages the Grafana knowledge of Cortex architectures to make the architecture horizontally scalable. This is a breaking change from previous versions so we will only be considering the architecture from this change onward.
Similar to Loki, Mimir, and Tempo, Pyroscope uses low-cost, highly available block storage such as Amazon S3, Google Cloud Storage, or Microsoft Azure Storage to provide massive scalability. Here’s a diagram of the Pyroscope architecture:

Figure 13.7 – Pyroscope architecture
When data is written, it is sent to the Ingester, which persists the data to Object Storage. On the Reads side, queries are split and sharded to instances of the Querier, which grabs the necessary data from the Ingester and/or the long-term storage.
There are several alternatives to Pyroscope on the market that may be of interest to you. The open source tools include OpenTelemetry eBPF, Parca, and profefe, and several observability vendors include similar profiling tools. These tools can be found at https://github.com/open-telemetry/opentelemetry-ebpf, https://www.parca.dev/, and https://github.com/profefe/profefe. We’ve now seen how Pyroscope functions. Another tool that is helpful for developers and testers is k6 load testing. Let’s take a look at this next.
Using k6 for load testing
Section titled “Using k6 for load testing”Load testing is the practice of applying a known, artificial load to an application to see how it behaves. The term is often used interchangeably with performance testing, and we will follow the k6 documentation in using average load to differentiate a specific type of test.
Several different types of load tests can be applied; they differ on two axes – the load throughput and the duration. They may also differ in the content of the tests that are performed. Some common types of tests are shown in the following table:
| Test | Description | Purpose | Runtime and volume |
|---|---|---|---|
| Smoke tests | These are designed to validate that the system works. They can also be known as sanity or confidence tests. They are called smoke tests after testing a device by powering it on and checking for smoke. | These are designed to quickly say that things look as expected or that something is wrong | These should run quickly, in minutes not hours. They should be low volume. |
| Average load tests | These tests show how the system is used in most conditions. | These are designed to simulate the most frequent level of load on the system. | These should run relatively quickly, but slower than smoke tests. They should simulate average volumes of traffic. |
| Stress tests | These tests stress the system with higher-than-average peak traffic. | These are designed to simulate what would happen if peak traffic were experienced for an extended duration. | These should run in less than a day. They should simulate high volumes of traffic. |
| Spike tests | These tests should show how the system behaves with a sudden, short, massive increase in traffic, as might be seen during a denial of service (DoS) attack. | These are designed to test how the system would handle a sudden overwhelming spike in traffic, such as a DoS attack. | These should run quickly. They should simulate unrealistic amounts of traffic. |
| Breakpoint tests | These tests gradually increase traffic until the system breaks down. | These are designed to understand when the system will fail with added load. | These can run for extended periods. They should simulate steadily increasing rates of traffic. |
| Soak tests | These tests assess the performance of the system over extended periods. They are like an average load test over a significantly longer period. | These are designed to demonstrate how the system will function during real operations for extended periods. They are good for identifying issues such as memory leaks. | These will run over extended periods such as 48 hours. They should simulate average volumes of traffic. |
Table 13.2 – Types of load tests
The following graph shows the different tests for reference:

Figure 13.8 – Visual representation of the different load test types
In the preceding figure, we can see the different types of tests graphed by the test throughput and the test duration. Try correlating what you can see in the graph with what you’ve just learned about these tests in Table 13.2.
You can see that load testing and observability are very closely linked. The data collected from a live system will show what average and unrealistic loads look like. The data injected by a smoke test can show a system is working as expected, for example, after a new version is deployed. The data collected from the load testing environment can give critical insights into the operation of the system under load.
It is good practice to separate the observability data collected from load testing from other data. Due to the nature of the tests that are being tried, very large volumes of data can be generated, which can be a very costly thing to collect. One huge advantage of open source systems such as Grafana is the ability to run the data storage system as part of the load testing environment while using the same visualization as in production.
There are several load testing tools on the market, both open source and commercial. The open source offerings include JMeter, k6, Gatling, Locust, Artillery, Tsung, Vegeta, Hey, and Siege. As this book focuses on Grafana tools, we will only discuss k6 here. Let’s have a look at some of the features of k6.
A brief overview of k6
Section titled “A brief overview of k6”k6 is the load testing tool developed by Grafana Labs after they acquired LoadImpact. k6 offers several key features:
- A command-line interface (CLI) that allows tests to be run, paused, resumed, or scaled.
- The ability to start tests locally, from a Kubernetes cluster, or in the cloud with the CLI. k6 supports distributed running via a Kubernetes operator.
- Scripting support using JavaScript.
- The ability to load additional modules into scripts, although this does not include support for Node.js modules.
- A browser module that adds browser-level APIs for full frontend testing.
- Support for goal-oriented load testing using checks and thresholds.
- Great supporting tools, such as the following:
- Reference projects
- Tools to convert scripts from other tools to k6
- Tools to convert k6 output to other common formats
- A GUI for test building
- Reference projects
Let’s now look at the process of writing a simple test.
Important note
As k6 requires a test file to run, we have included the installation and usage instructions after these instructions on writing a test.
Writing a test using checks
Section titled “Writing a test using checks”Tests are written in k6 using JavaScript. A very simple test to submit a GET request to the acme website would look like this:
import http from 'k6/http';export default function () { http.get('http://www.acme.com');}This script would just submit a request to the web page, but it would not validate that the request was successful. The check functionality would be used to confirm that this is the case, like this:
import { check } from 'k6';import http from 'k6/http';export default function () { const res = http.get('http://www.acme.com'); check(res, { 'is status 200': (r) => r.status === 200, }, { company: 'Acme' } );}The check() function takes a value, an object containing the checks that will be run against the value, and an object containing any tags. If all the checks pass, then the function returns true; otherwise, it will return false. The check functionality makes it very simple to check for simple conditions in a script. It is common to want to check that an endpoint is meeting specific expectations, and k6 offers thresholds for this goal.
Writing a test using thresholds
Section titled “Writing a test using thresholds”Thresholds are checked against all requests made in the script, and it is good practice to use the service-level objectives (SLOs) set by the team as a starting point for testing. Here is an example of a threshold test:
import http from 'k6/http';export const options = { thresholds: { http_req_failed: ['rate<0.01'], // http errors should be less than 1% http_req_duration: ['p(95)<200'], // 95% of requests should be below 200ms },};export default function () { http.get('http://www.acme.com');}This test would make a call to the acme website and check that the built-in http_req_failed and http_req_duration HTTP metrics meet the threshold expression specified. These metrics are collected from all the requests made in the script; in this case, there is only a single request made. If needed, it is possible to use groups and tags to evaluate HTTP requests independently.
Now that we know how to write basic scripted tests, let’s look at how we can use options to scale.
Adding scenarios to a test to run at scale
Section titled “Adding scenarios to a test to run at scale”In the previous section, we mentioned that the test would only make a single HTTP request. By using options, it is easy to manage the behavior of the default function in complex ways. Let’s consider a simple example in which we create 100 VUs, and each VU will execute the default function repeatedly for 30 minutes:
import http from 'k6/http';export const options = { vus: 100, duration: '30m'};export default function () { http.get('http://www.acme.com');}You might notice that we are using the same options constant as we used when we created the test thresholds in the previous section. The options configuration option offers a lot of flexibility for defining the behavior of a test. It is a common requirement to share data with each of the VUs that will run the tests. Let’s have a look at how the test life cycle can manage these requirements.
Test life cycle
Section titled “Test life cycle”There are four stages to the k6 test life cycle. These stages are explicitly set in the ordering of a test file:
- Initialization code: This is any code that appears at the top of the test script, before the setup code. It is run once per VU and is used to load files, import modules, configure the options used in the test, and for similar operations.
- Setup code: The code runs once and is used to set up data that is shared by all the VUs that are running the tests. This code uses the following syntax:
export function setup() { } - VU code: The code is run as many times as needed on each VU and is used to define the functions that will be run during a test. This code uses the following syntax:
export default function (data) { } - Teardown code: The code is run once, but it will not run if the setup ends abnormally. It is used to process results and stop the test environments. This code uses the following syntax:
export function teardown (data) { }
Now that we have a good understanding of using k6 to run tests, we need to consider the different ways we can install and run k6.
Installing and running k6
Section titled “Installing and running k6”k6 is available in several package formats:
- Linux (
.rpmand.deb) - macOS
- Windows
- Containerized image
- Standalone binary for all platforms
Installation is very simple on all platforms, and full instructions can be found on the k6 website at https://k6.io/docs/get-started/installation/.
Running k6 is also very easy as all processes are triggered from the CLI. This is very well documented via the -- help flag:
$ k6 --help /\ |‾‾| /‾‾/ /‾‾/ /\ / \ | |/ / / / / \/ \ | ( / ‾‾\ / \ | |\ \ | (‾) | / __________ \ |__| \__\ \_____/ .ioUsage: k6 [command]Available Commands: archive Create an archive cloud Run a test on the cloud completion Generate the autocompletion script for the specified shell help Help about any command inspect Inspect a script or archive login Authenticate with a service pause Pause a running test resume Resume a paused test run Start a test scale Scale a running test stats Show test metrics status Show test status version Show application versionThe k6 run and k6 cloud operations are used to run tests locally or via the k6 cloud, respectively. Here are some example commands using a test file called test.js:
- Run a single VU once:
k6run test.js - Run 10 VUs with 20 iterations of the test being run across these VUs:
k6 run -u 10 -i20 test.js - Ramp VUs from
0to50over 20 secs, maintain the50VU count for 60 secs, then ramp down to0over 10 secs:k6 run -u 0 -s 20s:50 -s 60s:50 -s10s:0 test.js
These commands could all have k6 run replaced with k6 cloud to use a k6 cloud runner instead of running the tests from the local machine.
Now that we’ve seen how to use k6 to perform load testing, let’s wrap up.
Summary
Section titled “Summary”In this chapter, we have explored two of the tools that Grafana offers as part of its observability platform: Pyroscope and k6. We learned how to search the profile data collected by Pyroscope and how to configure the client to collect that profile data. We also learned how to instrument applications, both using a native language SDK and using Lambda layers for serverless applications. Finally, we explored the new Pyroscope architecture and saw how it is very similar to Loki, Mimir, and Tempo. This new scalability should give Pyroscope the space to grow into a vital fourth telemetry type, making systems more observable.
With k6, we learned about various types of load or performance tests. We saw how we can easily write tests using the JavaScript language, using checks and thresholds to articulate vital measures for an application. We saw how to use options to manage how k6 runs its tests, and how to add the correct data and functions to our scripts to best make use of the test life cycle. Finally, we saw the process for installing and running k6, and how the simple operation even allows us to run the tool as part of a CI/CD pipeline to continuously load test applications to validate that their performance is meeting SLOs.
In the next chapter, we will bring together all of the tools, APIs, and knowledge to understand how to best support DevOps principles using Grafana.