---
title: How RailQL works
description: Understand event sources, series, labels, time steps, aggregation, and transformations in RailQL.
---
RailQL queries read events or metric samples. Filters select the input data, rollups aggregate it over time, and stages transform the resulting series.

<Banner variant="primary">RailQL is available through <a href="/platform/priority-boarding">Priority Boarding</a>. Breaking changes may occur.</Banner>

<RailqlDiagram type="execution" />

## Series and event streams

An [event source](/observability/railql/data-sources#sources) provides individual events. Logs, HTTP requests, DNS queries, network flows, spans, and traces are event sources. Each event records one thing happening, with its timestamp, labels, and fields. An HTTP request, for example, has a path, host, duration, status code, and response size. Reading an event source returns an event stream.

A metric provides time series: sequences of samples that already summarize a measurement over time, such as CPU time used or memory in use. Each sample has a timestamp and a value. You can read how much CPU time a replica used during an interval, but you can't recover the individual operations that used it.

### Labels

Labels are name and value pairs that describe events and series, such as `service=api` or `replica=abc`. A log event can have `service`, `deployment`, and `level` labels; an HTTP request can have `method` and `http_status_class` labels.

A series is identified by its combination of labels. A memory metric with `service` and `replica` labels has a separate series for each replica of each service. Two replicas therefore produce two sequences of memory samples, even if they report at the same times.

You use labels to filter events and series, group events into series, and choose which series to combine.

## Filter what a query reads

A [filter](/observability/railql/language-reference#filters) in braces after the source keeps only matching data. Event sources and metrics use the same filter syntax: each term has a name, an operator, and a value. Multiple terms in a filter are conjunctive by default: they all need to be true for the filter to match.

```railql
http{service=api http_status>=500}
```

This reads HTTP requests from the `api` service whose status is at least 500. The result still contains individual events and their details.

```railql
metric railway.memory.usage{service=api}
```

This selects memory series labeled `service=api`, keeping each replica's series separate.

A filter only selects which series or events to read. It doesn't combine multiple series or events into one series.

The labels and fields you can filter depend on the source. Bare names such as `service` and `http_status` are Railway's own labels and fields. Names starting with `@` read your own data, such as JSON log keys or span attributes. See [Labels and fields](/observability/railql/data-sources#labels-and-fields).

## Return events or roll up into time series

After filtering an event source, you can inspect the matching events or aggregate them into time series. Metrics already contain series, but their recorded samples also need to be combined to produce the points in a chart.

### Return raw events

An event query without a rollup returns individual events. For example, `http{service=api http_status>=500}` shows the failed requests as rows, with their paths, statuses, durations, and other details. A trace can also be shown as a waterfall, and `traces` as a list of traces. This answers questions about what happened in a particular request.

To count failed requests over time, add a rollup. Both an event rollup and a series rollup produce time series with one output sample per series, per time step.

### Steps and the query range

The query range is the selected time period. It is configured separately from the RailQL query, through the explorer's time range picker, a dashboard panel's settings, or an API call.

RailQL divides the range into intervals called steps. Each series has one calculated output sample per step. For example, a six-minute range with two-minute steps has three steps and three output samples per series.

RailQL picks the step from the range, aiming for about 300 points, and rounds it to a whole step: 30 seconds, 1 minute, 2, 5, 10, 15, or 30 minutes, 1, 2, 3, 4, 6, 8, or 12 hours, or whole days. A 1-hour range has steps of 30 seconds or a minute, and a 30-day range has steps of a few hours.

Because the step follows the range, the same query works on a 15-minute range and a 30-day one without changes. When a value must cover a fixed time, such as a 5-minute average, a [window](/observability/railql/language-reference#windows) can be used.

Steps align to round time boundaries, rather than starting exactly when your selected range starts. A range can therefore include partial first and last steps. Queries that read metrics use a minimum step of one minute.

A Number panel treats the whole selected range as one step. The rollup calculates one value per series across that range, rather than a separate value for each smaller step. See [Number values](/observability/railql/explorer-and-dashboards#understand-number-values) for how the rollup determines that value.

### Combine series samples within a step

A sample is one recorded or calculated value at a timestamp. Each series can have multiple recorded samples within a step, depending on how often the metric is reported. A [series rollup](/observability/railql/language-reference#series-rollups) combines those samples into one output value per series, per step. This is also called temporal aggregation because it combines samples over time.

In this example, two replicas each record a memory sample every 30 seconds. Each two-minute step contains four samples from each series. The arrows show how `rollup avg` combines each group into one output value: replica A's first four samples average to 50 MiB, while replica B's average to 30 MiB. The step boundaries are shared, but each series is rolled up separately.

<RailqlDiagram type="steps" />

A series rollup preserves the series' labels and kind. Each [kind](#kinds-of-series) has a default rollup, so most metric queries don't need an explicit one.

For memory, the default average can hide short spikes within a step. Use `rollup max` to keep the highest sample in each step instead:

```railql
metric railway.memory.usage{service=api} rollup max
```

Only rollups supported by the series' kind are allowed. For example, memory samples can be averaged, but can't be added together over time.

### Kinds of series

Every series has a kind that describes what its samples hold and how they can be combined. A sample can hold a number or a distribution. The kind names come from OpenTelemetry.

| Kind | What it measures | Examples | Default series rollup |
|---|---|---|---|
| Counter | An amount added during an interval | Requests handled, bytes sent, CPU time used | Sum the samples |
| UpDownCounter | An amount that can go up or down | Memory in use, open connections, a rate per second | Average the samples |
| Gauge | A value that can't be added up | A configured limit, a temperature, a ratio, a percentile | Keep the latest sample |
| Histogram | A distribution of values | Request durations, response sizes | Merge the distributions |

Counters hold delta values: each sample records an amount added during an interval, not a lifetime total. For memory, adding ten samples would report ten times the memory in use, so its default rollup averages them instead. A Histogram's output sample is one combined distribution per step, rather than one number.

### Roll up events into series

An [event rollup](/observability/railql/language-reference#event-rollups) collects the events in each step and calculates one output sample. For example, `count` counts the matching requests in each step:

```railql
http{service=api} rollup count
```

Three requests in the first minute and two in the second become a single series with values `3` and `2`. The individual request details are no longer in the result.

<RailqlDiagram type="event-rollup" />

Add `by` to group the events before calculating each step's value. For example, `rollup count by http_status_class` produces one series per status class. Each output series has an `http_status_class` label and one count per step.

The aggregation determines the output kind: `count` and `sum` produce Counters, `histogram` produces Histograms, and functions such as `avg` and `max` produce Gauges. You can then combine or transform these series in the same way as series read from metrics.

### Use a sliding window

A window is the trailing period of data aggregated for each output sample. In this example, one memory sample is recorded each minute. A three-minute window averages three samples at a time, and a one-minute step produces a new average every minute:

<RailqlDiagram type="windows" />

The first window averages 40, 60, and 80 MiB into 60 MiB. The next window averages 60, 80, and 100 MiB into 80 MiB, reusing two samples from the previous window. The engine reads earlier data to fill a window at the start of the selected range, subject to retention.

```railql
metric railway.memory.usage{service=api} rollup avg over 3min
```

If you zoom out until the step exceeds three minutes, RailQL widens the window to the step and warns you. A fixed window therefore doesn't guarantee an identical line at every zoom level. See [Windows](/observability/railql/language-reference#windows) for syntax and rate behavior.

<Banner variant="warning">
For Counter sums, a window without `rate` produces misleading per-step totals. Each output contains the total for the whole window, and overlapping windows count the same increments repeatedly. Don't interpret these values as totals for individual steps or add them together to calculate a total for the range. Use `| rate` to divide each window's total by its duration.

For example, at 60 requests per minute, a three-minute window contains 180 requests. With a one-minute step, the output is 180 at each step, not 60. Treating that as a per-minute count would overstate traffic threefold. Adding `| rate` divides 180 by the window's 180 seconds, giving 1 request per second:

```railql
http{service=api} rollup count over 3min | rate
```

</Banner>

## Combine series

Replica metrics are tagged with the service and replica that recorded them. Often you're interested in a single value across all replicas, such as the memory a service uses in total, rather than one series per replica. Combining multiple series with different labels into one is a spatial aggregation, and can be done in RailQL using a [stage](/observability/railql/language-reference#stages):

```railql
metric railway.memory.usage | sum by service
```

This query adds up the series of every replica of a service into one series per service. The labels you name after `by` are kept, and the others, such as `replica`, are dropped.

Temporal aggregation first combines each replica's samples over time. Spatial aggregation then combines replicas at the same step:

<RailqlDiagram type="spatial" />

The order matters: spatial aggregation operates on the values already calculated for each step. See [aggregation order pitfalls](/observability/railql/errors-and-limits#understand-aggregation-order) for examples involving peaks and averages.

The kind decides which aggregations make sense:

- Counters and UpDownCounters add up across series. The memory of three replicas is the memory of the service.
- Gauges use `max`, `min`, or `avg` across series. RailQL rejects `sum` for this kind. To compare memory utilization, divide usage by the limit per replica before aggregating the ratios.
- Histograms merge. The p99 of a service is the p99 of all its replicas' durations merged together, not the average of each replica's p99.

RailQL refuses aggregations that don't fit the kind, such as `sum` of a Gauge, and warns about ones that are usually wrong, such as the average of percentiles.

## Transform series

A [stage](/observability/railql/language-reference#stages) follows a pipe (`|`) and operates on the preceding result. Stages chain from left to right. In addition to spatial aggregation, stages can change values, convert units, or turn counts into rates.

### Arithmetic

Arithmetic with a number changes every value in each series. For example, `| * 2` doubles the values while preserving their labels and units.

Arithmetic between two queries combines their values at each step, using labels to pair the series. This query divides failed requests by total requests separately for each service:

```railql
((http{http_status>=500} rollup count by service) /
 (http rollup count by service))
```

<RailqlDiagram type="matching" />

Each result keeps its service label. Series with different service values don't match, and unmatched series are omitted. More generally, one side's label names must be a subset of the other's; the values on shared labels must match. See [Match series by labels](/observability/railql/language-reference#match-series-by-labels).

For missing points or absent series, see [Missing data and empty results](/observability/railql/errors-and-limits#missing-data-and-empty-results).

### Units

Series carry units as well as values. Use `to` to convert both together:

```railql
metric railway.memory.usage{service=api} | to GiB
```

Dividing bytes by `1024` changes the number but leaves the unit as bytes. `to GiB` performs a unit conversion. A ratio, such as failed requests divided by total requests, is dimensionless; append `| to %` to show `0.05` as `5%`.

### Rates

A Counter holds a total for each step. The `rate` stage divides that total by the step's duration in seconds:

```railql
http{service=api} rollup count | rate
```

A one-minute step with 120 requests becomes 2 requests per second. Each series keeps its labels, and its kind becomes UpDownCounter. Rates make counts easier to compare when changing the selected range also changes the step size.

For a rollup with an explicit window, `rate` divides by the window duration instead. It doesn't subtract one cumulative counter reading from the next. See [Windows](/observability/railql/language-reference#windows) for the relationship between windows and rates.

## Extract values from histograms

A Histogram series holds one distribution per step. You can display those distributions as a heatmap, or extract a number from each one to plot a line:

```railql
http{service=api} rollup histogram(total_duration) by path | p99
```

The rollup collects request durations into a distribution for each path and step. `p99` extracts the 99th percentile from each distribution, producing a Gauge series per path with one duration per step. The path labels are preserved.

Other extraction stages include `p50`, `avg`, `min`, `max`, `sum`, and `count`. On Histograms, `avg` extracts each distribution's mean; it doesn't average across series. To calculate a percentile or mean across multiple distributions, combine them with `merge` first, then extract the value. See [Stage input and output kinds](/observability/railql/language-reference#stage-input-and-output-kinds).

Extracting a mean or percentile discards information needed to combine the original distributions. See [why averaging averages or percentiles gives the wrong overall value](/observability/railql/errors-and-limits#averaging-averages-or-percentiles-gives-the-wrong-overall-value).