Skip to content
ImagineWorld

Monitoring with Metrics Using Grafana Mimir and Prometheus

node_idnode-book_observability-with-grafana_chapter-05-monitoring-with-metrics-using-grafana-mimir-and-prometheus
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleMonitoring with Metrics Using Grafana Mimir and Prometheus
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Monitoring with Metrics Using Grafana Mimir and Prometheus

Section titled “Chapter 5 — Monitoring with Metrics Using Grafana Mimir and Prometheus”

This chapter will introduce the Prometheus query language (PromQL). Like LogQL, PromQL can be used to select and filter metrics streams and process numeric data with operators and functions, enabling you to build quick and efficient queries that will support establishing an observable system. We will also explore and compare the various protocols that can be used to output metrics from systems. Finally, we will explore the architecture of Prometheus and Mimir to understand how Mimir fills the need for a highly scalable system.

We will cover the following main topics in this chapter:

  • Updating the OpenTelemetry collector for metrics
  • Introducing PromQL
  • Exploring data collection and metric protocols
  • Understanding data storage architectures
  • Using exemplars in Grafana

In this chapter, you will need the following:

  • The OpenTelemetry demo application set up in Chapter 3
  • The Grafana Cloud instance set up in Chapter 3
  • Docker and Kubernetes

You’ll find the code for this chapter in the GitHub repository at https://github.com/PacktPublishing/Observability-with-Grafana/tree/main/chapter5. You’ll find the Code in Action videos for this chapter at

Updating the OpenTelemetry demo application

Section titled “Updating the OpenTelemetry demo application”

For this chapter, we have prepared an updated version of OTEL-Collector.yaml, which will add additional labels to metrics for you to explore. Full details on this process are available from the Git repository in the README.md file. This process will apply the new version of the collector configuration to your demo application:

  1. Using Helm, we will apply the updated configuration file to our
    $ helm upgrade --version '0.73.1' --values chapter5/OTEL-Collector.yaml --values OTEL-Creds.yaml owg open-telemetry/opentelemetry-collector
    NAME: owg-otel-collector
    LAST DEPLOYED: Sun Mon 19 12:42:36 2023
    NAMESPACE: default
    STATUS: deployed
    REVISION: 2
    …
  2. Validate upgrade
    $ kubectl get pods --selector=component=standalone-collector
    NAME READY STATUS RESTARTS AGE
    owg-otel-collector-594fddd656-tfstk 1/1 Terminating 1 (70s ago) 2m8s
    owg-otel-collector-7b7fb876bd-vxgwg 1/1 Running 0 3s

This new configuration adds the collection of metrics from the Kubernetes cluster and the OpenTelemetry collector. The configuration also does some necessary relabeling.

Now that we are collecting more data from our local demo application, let’s introduce the language used to query that data.

Prometheus was initially developed by SoundCloud in 2012; the project was accepted by the Cloud Native Computing Foundation in 2016 as the second incubated project (after Kubernetes), and version 1.0 was released shortly after. PromQL is an integral part of Prometheus, which is used to query stored data and produce dashboards and alerts.

Before we delve into the details of the language, let’s briefly look at the following ways in which Prometheus-compatible systems interact with metrics data:

  • Ingesting metrics: Prometheus-compatible systems accept a timestamp, key-value labels, and a sample value. As the details of the Prometheus Time Series Database (TSDB) are quite complicated, the following diagram shows a simplified example of how an individual sample for a metric is stored once it has been ingested:

Figure 5.1 – A simplified view of metric data stored in the TSDB

  • The labels or dimensions of a metric: Prometheus labels provide metadata to identify data of interest. These labels create metrics, time series, and samples:
    • Each unique __name__ value creates a metric. In the preceding figure, the metric is app_frontend_requests.
      • Each unique set of labels creates a time series. In the preceding figure, the set of all labels is the time series.
      • A time series will contain multiple samples, each with a unique timestamp. The preceding figure shows a single sample, but over time, multiple samples will be collected for each time series.
      • The number of unique values for a metric label is referred to as the cardinality of the label. Highly cardinal labels should be avoided, as they significantly increase the storage costs of the metric. The following diagram shows a single metric containing two time series and five samples:

Figure 5.2 – An example of samples from multiple time series

In Grafana, we can see a representation of the time series and samples from a metric. To do this, follow these steps:

  1. In your Grafana instance, select Explore in the menu.
  2. Choose your Prometheus data source, which will be labeled as grafanacloud-<team>-prom (default).
  3. In the Metric dropdown, choose app_frontend_requests_total, and under Options, set Format to Table, and then click on Run query. This will show you all the samples and time series in the metric over the selected time range. You should see data like this:

Figure 5.3 – Visualizing the samples and time series that make up a metric

Now that we understand the data structure, let’s explore PromQL.

In this section, we will take you through the features that PromQL has. We will start with an explanation of the data types, and then we will look at how to select data, how to work on multiple datasets, and how to use functions. As PromQL is a query language, it’s important to know how to manipulate data to produce alerts and dashboards.

PromQL offers three data types, which are important, as the functions and operators in PromQL will work differently depending on the data types presented:

  • Instant vectors are a data type that stores a set of time series containing a single sample, all sharing the same timestamp – that is, it presents values at a specific instant in time:

Figure 5.4 – An instant vector

  • Range vectors store a set of time series, each containing a range of samples with different timestamps:

Figure 5.5 – Range vectors

  • Scalars are simple numeric values, with no labels or timestamps involved.

PromQL offers several tools for you to select data to show in a dashboard or alert, or just to understand a system’s state. Some of these are described in the following table:

NameSyntaxOperatorsScope
Metric selectormetric_nameSelects a metric
Range selector[``5m]ms, s, m, h, d, w, and ySelects samples
Label selector{ label="value", foo!="bar"}=, !=, =~, and !~Selects and filters time series using labels
Offset modifieroffset 5mms, s, m, h, d, w, and yOffsets the evaluation time from the current point in time by the specified amount
@ modifier@ 1686561123@Sets the evaluation time to a specific time for instant or range vectors. This modifier uses epoch timestamps

Table 5.1 – The selection operators available in PromQL

In addition to the operators that allow us to select data, PromQL offers a selection of operators to compare multiple sets of data.

Some data is easily provided by a single metric, while other useful information needs to be created from multiple metrics. The following operators allow you to combine datasets.

NameSyntaxOperatorsScope
Arithmetic operatorsa + b+, -, *, /, %, and ^Arithmetic operations on instant vectors and scalars; scope depends on the data type of a and b. It’s important to note that vectors are matched on all labels.
Comparison operatorsa == b==, !=, >, <, >=, and <=Filters instant vectors and scalars based on the comparison; scope depends on the data type of a and b.
Aggregation operatorssum by (``label) (a)sum(), min(), max(), avg(), group(), stddev(), stdvar(), count(), count_values(), bottomk(), topk(), and quantile()Aggregation operations on a single instant vector. These operators offer the without and by clauses to modify how results are grouped by label.
One-to-one vector matchinga + on bon() and ignoring()Modifies vector matching to specific labels (on) or ignoring a label (ignoring)
One-to-many/many-to-one vector matching using group modifiersa + group_left bgroup_left() and group_right()Modifies the vector matching in cases of many-to-one or one-to-many matching. Grouping can use a label list to include a label in the results.
Many-to-many vector matching using logical operatorsa and band, or, and unlessModifies vector matching in cases of many-to-many matching, based on logical operations between labels and the values of a and b

Table 5.2 – The comparison operators available in PromQL

Vector matching is an initially confusing topic; to clarify it, let’s consider examples for the three cases of vector matching – one-to-one, one-to-many / many-to-one, and many-to-many.

By default, when combining vectors, all label names and values are matched. This means that for each element of the vector, the operator will try to find a single matching element from the second vector. Let’s consider a simple example:

  • Vector A:
    • 10{color=blue,smell=ocean}
      • 31{color=red,smell=cinnamon}
      • 27{color=green,smell=grass}
  • Vector B:
    • 19{color=blue,smell=ocean}
      • 8{color=red,smell=cinnamon}
      • 14{color=green,smell=jungle}
  • A{} + B{}:
    • 29{color=blue,smell=ocean}
      • 39 {color=red,smell=cinnamon}
  • A{} + on (color) B{} or A{} + ignoring (****smell) B{}:
    • 29{color=blue}
      • 39{color=red}
      • 41{color=green}

When color=blue and smell=ocean, A{} + B{} gives 10 + 19 = 29, and when color=red and smell=cinnamon, A{} + B{} gives 31 + 8 = 29. The other elements do not match the two vectors so are ignored.

When we sum the vectors using on (color), we will only match on the color label; so now, the two green elements match and are summed.

This example works when there is a one-to-one relationship of labels between vector A and vector B. However, sometimes there may be a many-to-one or one-to-many relationship – that is, vector A or vector B may have more than one element that matches the other vector. In these cases, Prometheus will give an error, and grouping syntax must be used. Let’s look at another example to illustrate this:

  • Vector A:
    • 7{color=blue,smell=ocean}
      • 5{color=red,smell=cinamon}
      • 2{color=blue,smell=powder}
  • Vector B:
    • 20{color=blue,smell=ocean}
      • 8{color=red,smell=cinamon}
      • 14{color=green,smell=jungle}
  • A{} + on (color) group_left B{}:
    • 27{color=blue,smell=ocean}
      • 13{color=red,smell=cinamon}
      • 22{color=blue,smell=powder}

Now, we have two different elements in vector A with color=blue. The group_left command will use the labels from vector A but only match on color. This leads to the third element of the combined vector having a value of 22, when the item matching in vector B has a different smell. The group_right operator will behave in the opposite direction.

The final option is a many-to-many vector match. These matches use the logical operators and, unless, and or to combine parts of vectors A and B. Let’s see some examples:

  • Vector A:
    • 10{color=blue,smell=ocean}
      • 31{color=red,smell=cinamon}
      • 27{color=green,smell=grass}
  • Vector B:
    • 19{color=blue,smell=ocean}
      • 8{color=red,smell=cinamon}
      • 14{color=green,smell=jungle}
  • A{} and B{}:
    • 10{color=blue,smell=ocean}
      • 31{color=red,smell=cinamon}
  • A{} unless B{}:
    • 27{color=green,smell=grass}
  • A{} or B{}:
    • 10{color=blue,smell=ocean}
      • 31{color=red,smell=cinamon}
      • 27{color=green,smell=grass}
      • 14{color=green,smell=jungle}

Unlike the previous examples, mathematical operators are not being used here, so the values of the elements are the values from vector A, but only the elements of A that match the logical condition in B are returned.

Now that we understand the operators, let’s quickly introduce PromQL functions before we look at a practical example of writing PromQL. We will explore a practical example of their use in the Writing PromQL section.

PromQL offers about 60 different functions. The full list of functions can be found on the Prometheus w ebsite: https://prometheus.io/docs/prometheus/latest/querying/f unctions.

Now that we’ve looked at the functions available in PromQL, let’s explore writing a PromQL query.

While technical descriptions of a language are useful for reference, this section will follow the process of building a query so that the language can be seen in context. Having your Grafana instance open in Explorer will help you follow along. In the following sections, we’ll write practical examples using the selectors, operators, and modifiers we introduced in the previous section.

When we looked at metric labels, we saw how you can select metrics in PromQL with the metric_name{} syntax. This can be typed directly into a query using the Code button in the top-right corner of the query panel, or as we did earlier in the Introducing PromQL section, you can use Builder. In Builder, you will see the PromQL in the query panel below your selection, it should currently say app_frontend_requests_total. If it does not, use the Metric dropdown to select this metric. You should see results like in Figure 5*.3*. This method of selection returns an instant vector, as described in Figure 5*.4*.

The syntax is similar for returning a range vector, as described in Figure 5*.5*. We just need to add the range we are interested in – metric_name[range]. The range must include the time units, which can range from milliseconds (ms) to years (y). It’s important to note that queries using range vectors need to be run with a query type of Instant. If a query type of Range or Both (the default) is selected, then you will receive an error. Here is an example of the error you will see:

Figure 5.6 – An error when using a range vector in a range query

As time series are made up of a unique set of labels, we can expand our query to only look at specific data – for example, only requests that target the cart API of the OpenTelemetry demo application. The following steps will filter our query to show only the requests that target the / api/cart endpoint:

  1. Switch to the Table view at the top right of the Results panel:

Figure 5.7 – Using the Table view in the PromQL results

  1. Hover your mouse over a value for the target; you should see this icon:

Figure 5.8 – Filter for value

  1. Click on the plus icon, and you will see that we have a new label filter and our PromQL now says the following: app_frontend_requests_total{target="/api/cart"}.
  2. Let’s only show the GET method requests as well; you can do this by using the filters selector in the query panel, or the table in the Results panel. Like LogQL, we have different operators available to filter labels. The operators we can use are as follows:
    • =: Checks for an exact match of a string. For example, target="/api/cart" will match only when the target label is /api/cart/.
      • !=: Checks for anything other than an exact match. target!="/api/cart" will match everything except when the target label is /api/cart/.
      • =~: Checks for a regex match. For example, target=~"/api/.*" will match when the target label starts with /api/. This includes /api/cart/, /api/horse/, and /api/cart/foo/bar/.
      • !~: Checks for anything other than a regex match. target!~"/api/.+" will match when the target label is /api/ or /checkout/ but will not match /api/cart/, /api/horse/, and /api/cart/foo/bar/.

While we’re looking at the table, you should also see a column titled __name__; this is a special label that can be used as an alternative during search, for instance, metric_name{} is equivalent to {__name__="metric_name"}.

We’ve now selected data and filtered it to the endpoint we’re interested in, but a raw count of the requests that were made is difficult to interpret. Let’s look at how to transform this count into something more useful, using a function.

PromQL is a nested language, so to apply a function to a selected set of data, you simply enclose the data selection with the function. Our query so far looks like this:

app_frontend_requests_total{target="/api/cart",method="GET"}

This query returns the count of requests at each sample point. For most purposes, we are more interested in the rate of requests that hit that endpoint. This will allow us to answer questions such as what the peak rate is, or whether the rate is higher now or lower than at another point in time. The function to get this information is the rate() function. We can plug our current query into the function like this:

rate(app_frontend_requests_total{target="/api/cart",method="GET"}[$__rate_interval])

The rate function takes an input of a range vector, so we have added the special [$__rate_interval] time variable. This is a Grafana feature that instructs Grafana to pick an appropriate interval, based on the scrape interval of the data source we have selected. This feature simplifies the technicalities of selecting the correct rate interval. A similar process is used for aggregation and other operators.

Now that we know how to get the rate of requests to the /api/cart endpoint, let’s have a look at another example query.

A common Service Level Indicator (SLI) for a web application is the success rate of HTTP requests. In plain language, this is the number of successful HTTP requests/total HTTP requests. We will discuss the process of choosing good SLIs in Chapter 9.

A PromQL query like the following will produce the success rate SLI for the app_frontend_requests_total metric:

sum by (instance) (rate(
app_frontend_requests_total{status=~"2[0-9]{2}"}[5m]))
/
sum by (instance) (rate(app_frontend_requests[5m]))

We can break this code down as follows:

  • Using app_frontend_requests_total{status=~"2[0-9]{2}"}[5m], we select samples of the app_frontend_requests metric that have the status label, with a value between 200 and 299. This uses regex to select the label range, and it is a range vector over a five-minute range. For those of you familiar with regex, Grafana requires the escaping of backslashes.
  • The rate() function calculates the per-second average rate of successful requests. This function returns an instant vector.
  • The previous functions have left all data grouped into the initial time series from it. However, for this query, we are not interested in the method, target, or any other labels. Instead, we are interested in knowing whether a particular instance of the application is failing, as a failing instance could be masked by many good instances. To achieve this, we use the sum by (instance) () aggregation.
  • The last line of the query mirrors the first line but removes the label selector, so we get the total requests.
  • Finally, we use the arithmetic operator (/) to divide the successful requests by the total requests. The output of this query gives us a number that will be close to 1 when most requests are successful; as we see failures, this will trend downward to 0 when every request fails.

Another common item to measure is the duration of requests made to the service. Durations are frequently represented as histogram data, and PromQL offers us many statistical tools we can use to understand our user’s experience. Let’s look at the following query:

histogram_quantile(
0.95, sum(
rate(
http_server_duration_milliseconds_bucket{}[$__rate_interval])
) by (le)
)

The http_server_duration_milliseconds_bucket metric is a histogram, which is indicated by the naming convention of _bucket. The histogram_quantile() function takes this histogram data and gives us the 95th percentile duration. This is calculated using the le (less than or equal to) label in the histogram data. While it might be tempting to use averages for this kind of calculation, percentiles offer us a more nuanced understanding of the data. The 95th percentile means that 95% of samples have a duration less than or equal to the value returned.

Grafana offers several helpful functions to understand a query:

  • Above the query component is a slider titled Explain. Toggling this on will present a step-by-step breakdown of what a query is doing.
  • Also, above the query component is a button titled Kick start your query. Clicking this will give a number of starter queries.
  • Below the Options section is the query Inspector. This will give detailed information about the query, such as its total request time and the data returned.

Here is a screenshot showing the location of these options:

Figure 5.9 – Helpful functions for queries

Hopefully, you have a good grasp of the fundamentals of PromQL now and know what resources you have available to learn more. Whilst querying data is a major part of the day-to-day work in Grafana, it is good to have an understanding of how metrics data is collected.

The OpenTelemetry demo that has been set up also produces metrics from the single-node Kubernetes cluster, the kubelet instance on the node, and the underlying host. We encourage you to explore these metrics and see what you can find.

We’ve seen how to query the data stored in Prometheus-compatible systems. Now, let’s see how to collect data from your services.

Exploring data collection and metric protocols

Section titled “Exploring data collection and metric protocols”

In Chapter 2, we introduced four common protocols in use to collect data from today’s software – StatsD and DogStatsD, OpenTelemetry Protocol (OTLP), and Prometheus. We also introduced Simple Network Management Protocol (SNMP), which is used in the networking and compute spaces. In this section, we’ll explore some of the features of these protocols.

There are two methods that metrics can be collected, push and pull. In a push protocol, the application or infrastructure must be configured with a destination to send metrics. In a pull protocol, the application or infrastructure is configured to expose metrics for another service to request. Both methods have advantages and disadvantages, it is also important to be aware of the potential security implications. In the following subsections, let’s delve into each protocol.

We have grouped StatsD and DogStatsD together, as they are identical for the purposes of what we are discussing in this chapter.

StatsD is a push protocol, so each application producing metrics needs to be aware of the destination for these metrics. StatsD uses User Datagram Protocol (UDP) over port 8125 in its default settings. These are things to consider when using StatsD:

  • StatsD uses UDP for transmission. This favors the speed of transmission over the guarantee of delivery.
  • The protocol offers no support for authentication between the application and the receiving service. Depending on the environment, this could be a security concern.

It’s worth noting that common practice, especially in Kubernetes, is to expose the StatsD receiver on localhost:8125, thus limiting exposure and offering a standard for applications to use.

StatsD has quite wide support in data collection agents, usually via contributed receivers. The OpenTelemetry collector, FluentBit, Vector, Beats, Telegraf, and the StatsD daemon all support the protocol. Prometheus offers an exporter that takes StatsD format metrics and exposes them as a Prometheus scrape endpoint; this is recommended as an intermediate step to a full Prometheus migration.

DogStatsD is less well supported than the StatsD format it is derived from; it provides an expanded set of metrics to StatsD. The data collection agents that natively support DogStatsD are Vector and Datadog’s own agent. The OpenTelemetry collector currently has no support, but there are discussions in progress on adding this, and Datadog is an active participant in the OpenTelemetry project, so this is likely to change.

OTLP is also a push protocol, so destination knowledge is necessary. Like StatsD, OTLP is often implemented using the standard receiving endpoint of localhost:4317 (Google Remote Procedure Call (gRPC)) or localhost:4318 (HTTP). OTLP supports both gRPC and HTTP and offers support for the authentication and acknowledgment between the client and server. OTLP also offers several quality-of-life items, such as server-controlled throttling and GZIP compression.

OpenTelemetry is in very active development, so this information is liable to change. As the project is a collaboration between several major vendors, agents from those vendors are increasingly supporting OTLP metrics. While other collection tools do not support OTLP input, the OpenTelemetry collector supports input from many sources. This means the OTEL collector is ideal for supporting a mixed estate. The vector collection agent also offers this versatility, and most things said about the OTEL collector can be applied to it as well.

Unlike StatsD and OTLP, Prometheus is a pull protocol. A client application needs to be configured to serve metrics on an endpoint, and then a Prometheus-compatible scraper is configured to collect those metrics at specific intervals. These metrics are commonly exposed on the /metrics endpoint, although some frameworks implement this differently (e.g., /actuator/Prometheus for Spring Boot).

It may seem that using a pull configuration increases the configuration steps required. However, using a pull method does reduce the information needed by the application of its running environment. For example, the application configuration would remain the same if 0 or 10 clients read its metrics. This pull pattern also matches very closely with the pattern of liveness and readiness endpoints for applications in Kubernetes.

To assist in the server configuration, Prometheus offers a wide range of service discovery options, across many different platforms, including Kubernetes, DNS, and Consul. These discovery options include matching a specific name and collecting data if a label is present, and this range of options allows for quite complex architectures where needed.

The Prometheus format has good collector support; Prometheus, the OTEL Collector, Grafana Agent, Vector, Beats, and Telegraf all support the collection of these metrics.

SNMP is more complex than the other protocols discussed here, as it includes a lot of functionality for the management and monitoring of network-connected devices, such as switches and physical servers. The monitoring aspect of SNMP is a pull protocol, where a manager instance connects to agent software on devices and pulls data. There is additional functionality in SNMP traps, which allow a device to inform the manager about items as a data push. These traps are often of interest to track metrics from. It is worth noting that security can be a concern using SNMP, depending on how it is configured. SNMP offers a significant attack surface if configured incorrectly.

SNMP is very well supported, as the protocol has been active since 1988 and has good support from hardware vendors.

We’ve now covered querying data using PromQL, and how data is produced and collected, so let’s now explore how Grafana stores metric data.

Time Series Databases (TSDBs) are ideally suited to handle metric data, as metrics need to record data at specific points in time, and TSDBs are structured to make this data easy to record and query. There are several TSDBs available, but as this book is focused on Grafana, we will only discuss Graphite, Prometheus, and Mimir in this section. This is aimed at giving you an understanding of the structure of data as it is stored, as well as an overview of how Mimir allows organizations to scale their data beyond the capabilities of Graphite and Prometheus.

Graphite has several components; we will discuss the storage component Whisper here. The Whisper TSDB uses a flat file structure, where each unique time series is a fixed-size file. This size is determined by the configuration of resolution and retention configured in Whisper. Gathering this data for a search requires each of these files to be read, which quickly becomes expensive in disk I/O. As there are no inbuilt items that manage data redundancy, Graphite is also unable to guarantee that data written to it will be protected from loss or corruption.

However, the protocols introduced by Graphite to write data are still relevant although aging, so Grafana Cloud offers a Graphite ingest endpoint and query endpoint for teams that are already using this technology.

Graphite was an early example of metrics, introduced in 2008; the limitations of query speed and data integrity outlined previously led to the creation of Prometheus, which we will discuss next.

Prometheus stores data in an immutable block, which covers a fixed time range (by default, two hours). Inside a block are several chunks, which are capped at 512 MB; these files contain the sampled value. Alongside these chunks are metadata files – index and meta.json. The index file contains a table that records the labels contained in the block and a reference to the position of all samples, with these labels in the associated chunks. Highly cardinal metric labels cause a huge increase in the size of the index file and degrade read performance. The meta.json file contains metadata such as the min and max timestamp contained in the block and stats on the samples, series, and chunks contained and the version used.

To process data as it’s received, Prometheus also uses a head block, which is similar to the block used for storage, but it allows writes. This allows for the collection of a full two-hour block of data, ready for the index and metadata to be created when the block is finished. This process includes functionality to persist data on disk to prevent data loss. The head block consists of a Write-Ahead Log (WAL) that contains the raw data as it is received and a meta.json file that records what has been received. When the end of the two-hour time block is reached, a new head block is created, and the old head block is transformed into a standard block, with the creation of an index and chunks.

The following figure shows the structure of a fictional Prometheus TSDB, with the blocks, chunks, index, and metadata files and the WAL highlighted:

Figure 5.10 – The Prometheus TSDB

The implementation of the Prometheus TSDB in Prometheus itself is limited, as it uses local storage, which is not clustered or replicated natively. While it is possible to improve the aspects of this, there is a fundamental limitation of only a single node carrying out reads and writes. These limitations are perfectly acceptable in the correct circumstances. However, when scaling the TSDB to accept many active time series, changes are needed. Handling these situations is what Mimir was designed to do.

Mimir uses the same fundamental TSDB storage structures. However, unlike Prometheus, Mimir natively supports object stores for block files. The supported stores include Amazon S3, Google Cloud Storage, Microsoft Azure Storage, and OpenStack Swift.

By leveraging object storage, which is massively scalable, Mimir can handle the scaling problem experienced with Prometheus by adding new instances of the data-ingesting service. Mimir separates the incoming streams of data to a specific per-tenant TSDB, and each of these is assigned to an instance of the ingesting service. Like Prometheus, data is written to memory and the WAL by the ingester, and when the block is complete, it is written to object storage. To provide resilience Mimir will write each of these streams to multiple ingesters, and a compactor service will handle the process of merging the redundant blocks in object storage and removing duplicate samples.

Like the horizontal scalability of the write pathway, Mimir also scales the read pathway. It does this by splitting an incoming query into shorter time ranges. Then, it distributes these smaller units of the query to multiple querier instances. By doing this, Mimir again leverages the benefits of the underlying object storage for a quick return of data.

The following diagram shows the read and write pathways for Mimir:

Figure 5.11 – Mimir architecture

Metrics show us aggregated data, such as the total count of requests. It is helpful when exploring an odd metric value to be able to look at an example. In applications that are instrumented with traces and metrics, exemplars allow us to record a sample trace in our metric data. Let’s see this capability in action.

Exemplars are functions in Grafana that allow us to pivot from an aggregated view of the system, given by metrics, to a detailed view of a single request, given by traces. Exemplars need to be configured at the collection layer and then sent to the storage layer.

When they are available, you can view exemplars by doing the following:

  1. Open Options under the query, and toggle the Exemplars slider:

Figure 5.12 – The Exemplars toggle

  1. Exemplars will appear as stars on the metrics chart:

Figure 5.13 – An exemplar in metrics

Hovering over an individual exemplar will expand on the metrics data by showing information from the exemplar trace in the metrics view. We will explain these fields in more detail in Chapter 6, but some notable fields are the name and version of the process runtime and span_id, which would not usually be available in a purely metric view:

Figure 5.14 – Exemplar information

  1. From an exemplar, you can also pivot from viewing metric data to looking at the trace in question by clicking on the **Query with Tempo (**Tempo) button:

Figure 5.15 – Opening an exemplar in Tempo

We’ll discuss the details of tracing in more detail in Chapter 6, but this should give you a good introduction to using this kind of data in your metrics.

In this chapter, we explored metrics in detail. We saw all the operators available in PromQL and wrote two queries using the language. With that foundation of querying knowledge, we looked at the tools available to collect data and the various protocols with which applications can share data. We then looked at the architecture for Prometheu, and saw how Mimir takes the concepts of Prometheus and turns them into a highly scalable data processing tool, able to meet the needs of organizations of any size. Our final exploration was of Exemplars, giving us a concrete data example to add context to the aggregated data seen in metrics.

The next chapter will explore how traces work in Grafana Tempo, which will show you how powerful the use of exemplars and logging trace and span information can be to create a truly observable system for your organization’s customers.