---
title: RailQL language reference
description: Reference for RailQL syntax, filters, rollups, windows, stages, arithmetic, and units.
---
RailQL queries select a source, filter its data, and optionally aggregate and transform the result.

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

## Query structure

A query starts with a source and an optional filter. An event rollup aggregates matching events into time series. Stages then transform those series in order from left to right.

```railql
http{service=api} rollup count by http_status_class over 5min | rate
```

This query reads HTTP requests for the `api` service, counts them over a five-minute window separately for each status class, and converts each count to requests per second.

The grouping precedes the window: `rollup count by label over duration`. The rollup and each stage can appear on separate lines without changing the query's meaning.

Comments start with `--` and continue to the end of the line.

[Data sources](/observability/railql/data-sources) lists source names, labels, fields, and metric units.

## Filters

A filter appears in braces immediately after the source. A comparison term consists of a label or field name, an operator, and a value:

```railql
http{service=api http_status>=500 path=/checkout/*}
```

This filter selects requests from the `api` service with a status of at least 500 and a path beginning with `/checkout/`. All three conditions must match.

### Operators

Spaces around operators are optional: `service=api` and `service = api` are equivalent, as are `name:checkout` and `name : checkout`.

| Operator | Meaning |
|---|---|
| `=` | Equal to the specified value, with wildcard matching for text |
| `!=` | Not equal to the specified value, with wildcard matching for text |
| `=~` | Text equality or wildcard matching, ignoring case |
| `!~` | Negated text equality or wildcard matching, ignoring case |
| `:` | Contains the specified text, with case-sensitive matching |
| `:~` | Contains the specified text, ignoring case |
| `>`, `>=`, `<`, `<=` | Numeric comparison |
| `= *` | A value exists |
| `!= *` | No value exists |

There is no `!:` operator. To exclude a substring, put `-` before the term: `-path:/health`.

### Values

Text values can be unquoted or enclosed in quotes. Quoting doesn't change the comparison: `service=api` and `service="api"` are equivalent. Values containing spaces, parentheses, braces, or quotation marks require quotes.

For `=`, `!=`, `=~`, and `!~`, `*` matches any sequence of characters. For example, `host=*.example.com` matches hosts ending in `.example.com`. Quoting alone doesn't disable wildcards; a literal asterisk must be escaped as `\*` inside a quoted value. With `:` and `:~`, an asterisk is always literal. The editor warns about an asterisk in a substring comparison and offers `=` instead.

`=` is case-sensitive for text, except for labels whose values Railway normalizes to a consistent case, such as `level`, `kind`, `status`, `qtype`, and `direction`. `=~` performs a case-insensitive comparison. Labels with a fixed set of allowed values, such as `level`, reject unknown values and report the allowed values in the error.

### Numbers and units

For a built-in numeric field, a number without a unit uses the field's declared unit. A number with an explicit unit is converted to that unit before comparison.

For example, `total_duration` is measured in milliseconds. The filter `total_duration>2000` means greater than 2,000 milliseconds. The filter `total_duration>2s` converts two seconds to 2,000 milliseconds, so both select the same requests.

Numeric comparisons use UCUM units, the unit notation used by OpenTelemetry. Time units include `ms`, `s`, `min`, and `h`; size units include `kB`, `MB`, `KiB`, `MiB`, and `GiB`. Use `min` for minutes in comparisons and [window durations](#windows).

### Message search

On `logs` and `build_logs`, a quoted string without a field name searches the log message for that text, ignoring case. A leading `-` excludes matching messages:

```railql
logs{service=api "connection refused" -"health check"}
```

This selects log messages from `api` containing “connection refused” and excluding “health check”. An unquoted word isn't a message search; the editor suggests adding quotes.

A message search on its own reads every log line in the selected range, so add a term such as `service=api` to narrow it. Message search isn't supported on other sources. For span names, the equivalent text comparison is `name:~"checkout"`.

### Combine terms

Multiple terms separated by whitespace are combined with AND: every term must match. The explicit `AND` keyword has the same meaning. For example, `service=api level=error` and `service=api AND level=error` both select error logs from `api`.

`OR` matches when at least one of its conditions matches. A leading `-` negates a comparison, message search, or parenthesized group:

```railql
logs{(service=api OR service=worker) level=error -"health check"}
```

This selects error logs from either service, excluding messages containing “health check”. Both `AND` and `OR` must be uppercase. RailQL has no `NOT` keyword; negation uses `-`, while inequality comparisons use `!=` or `!~`.

Parentheses are required when AND and OR are combined. RailQL rejects ambiguous expressions rather than assigning precedence between them. For example, `level=error service=api OR service=worker` is ambiguous. These two groupings have different meanings:

| Filter | Meaning |
|---|---|
| `(level=error service=api) OR service=worker` | Error logs from `api`, or any logs from `worker` |
| `level=error (service=api OR service=worker)` | Error logs from either `api` or `worker` |

The editor offers both groupings as fixes; the appropriate grouping depends on the intended filter.

### Custom fields and attributes

Names without an `@` prefix refer to built-in labels and fields. The `@` prefix accesses application data recorded in structured logs or span attributes:

| Source | Meaning of `@name` |
|---|---|
| `logs`, `build_logs` | A key in a [structured log line](/observability/logs#structured-logs) |
| `spans` | A span attribute, falling back to a resource attribute when the span has no attribute with that name |
| `http`, `dns`, `flows` | Not supported; these sources don't expose custom attributes |

```railql
logs{@user.plan=pro @items[0].sku="A-1"}
```

```railql
spans{kind=server @http.route="/users/:id"}
```

For logs, `level` is the normalized level extracted by Railway. `@level` is the original value of the structured log's `level` key. An unknown name without `@` produces an error, and the editor suggests the custom-field form.

Paths use `.` for nested objects and `[n]` for array elements. Array indexes start at zero; `[-1]` selects the last element. Keys containing special characters can be quoted, as in `@"content-type"`.

For structured logs, quoting also distinguishes nested paths from keys containing literal dots:

| Path | Matching key |
|---|---|
| `@error.code` | Either nested `{"error": {"code": …}}` or flat `{"error.code": …}` |
| `@"error.code"` | Only the flat key `error.code` |
| `@error."code"` | Only the nested key `code` inside `error` |

Span attributes are flat keys, so `@http.route` and `@"http.route"` refer to the same attribute.

Custom-field equality accepts both numeric and text representations: `@user_id=42` matches the number `42` and the string `"42"`. Numeric operators (`>`, `>=`, `<`, and `<=`) interpret custom values as numbers without unit conversion.

Existence and inequality have different behavior when a key is absent. `@request_id=*` requires the key to exist, while `@plan!=pro` also matches events with no `plan` key. Combining `@plan=* @plan!=pro` restricts the result to events with a non-`pro` plan value.

`@*` compares against the value of any custom key. This produces a warning because it requires searching across keys rather than reading one named key.

### Services

A service name in a filter is resolved to its ID. Wildcards and case-insensitive matching apply to service names: `service=api-*` matches services whose names begin with `api-`.

For `http`, filters on `service`, `deployment`, and `replica` select the replicas to read from. These terms must appear at the top level of the filter, outside `OR` expressions and negated groups.

### Log search syntax

The Logs page filter syntax differs from RailQL. RailQL accepts camelCase aliases for HTTP fields, such as `httpStatus` and `totalDuration`. The following examples show equivalent RailQL filters:

| Log search | RailQL |
|---|---|
| `@level:error` | `level=error` |
| `@user_id:42` | `@user_id=42` |
| `timeout` | `"timeout"` |
| `-@service:worker` | `service!=worker` |
| `@httpStatus:>=500` | `http_status>=500` |
| `@totalDuration:500..2000` | `total_duration>=500 total_duration<=2000` |

In RailQL, `:` performs a substring comparison; `=` performs an equality comparison. A legacy colon filter isn't necessarily equivalent to the same text in RailQL.

Links to the Logs page open in the RailQL explorer with the filter translated. If translation changes the filter's meaning, a note above the result describes the changes.

## Event rollups

An event rollup aggregates matching events into time series with one output sample per step. Its syntax specifies an aggregation function and optional grouping labels:

```railql
spans{service=api kind=server} rollup histogram(duration) by name
```

This produces one Histogram series per span name. Each sample contains the distribution of matching span durations within that step.

| Function | Value per step |
|---|---|
| `count` | Number of events |
| `sum(F)` | Sum of the values of `F` |
| `avg(F)`, `min(F)`, `max(F)` | Average, minimum, or maximum value of `F` |
| `first(F)`, `last(F)` | Value of `F` from the earliest or latest event |
| `count_distinct(F)` | Number of distinct values of `F` |
| `histogram(F)` | Distribution of the values of `F` |

For numeric aggregations, `F` is a built-in numeric field or a custom field such as `@duration_ms`. Custom values are interpreted as numbers; events whose values can't be read as numbers are skipped. `count_distinct` also accepts labels and text fields, and interprets custom values as text.

`count` and `sum` produce Counters, `histogram` produces Histograms, and the remaining functions produce Gauges. Counts use the source's event unit: log lines, requests, DNS queries, flows, or spans.

`by` produces one series per combination of values for the listed labels. Custom fields can also be grouping keys and retain the `@` prefix in output labels, as in `rollup count by service, @error.code`.

Event rollups support `by`, but not `without`. A later spatial aggregation can remove labels retained by the rollup. For example, `rollup count by service, replica | sum without replica` combines replica counts into one series per service.

## Series rollups

Metrics already contain time series. A series rollup combines the recorded samples within each step into one output sample per series. The default aggregation depends on the metric's kind, so an explicit `rollup` clause is optional:

| Kind | Default | Other supported aggregations |
|---|---|---|
| Counter | `sum` | None |
| UpDownCounter | `avg` | `min`, `max`, `last` |
| Gauge | `last` | `avg`, `min`, `max` |
| Histogram | `merge` | None |

For example, memory usage defaults to an average. An explicit `rollup max` selects the highest recorded value in each step instead:

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

For Histograms, `merge` combines the recorded distributions within each step into one distribution. An extraction [stage](#stages), such as `| p99`, converts each output distribution into a numeric value.

## Windows

The `over` clause sets the duration of data aggregated for each output sample. For example, `over 5min` aggregates the preceding five minutes at each step, even when the step is shorter than five minutes. Adjacent windows overlap when the window is longer than the step.

```railql
metric railway.cpu.time{service=api} rollup sum over 5min | sum | rate
```

This sums CPU time over five-minute windows, combines replicas, and divides by the window duration to calculate the CPU usage rate.

```railql
spans{service=api kind=server} rollup histogram(duration) over 5min | p99
```

This calculates the p99 span duration over the preceding five minutes at each step.

Durations after `over` and `rate per` use the same time units as filters: `ms`, `s`, `min`, `h`, and `d`, as in `30s`, `5min`, `1h`, and `1d`. The `over` clause belongs to the rollup, before any pipeline stages. Placing it after a stage is an error; the editor suggests moving it to the rollup.

A window shorter than the step is widened to the step, with a warning. A subsequent `rate` stage divides by the window duration instead of the step duration. Without `rate`, overlapping Counter windows contain repeated increments and must not be interpreted as independent per-step totals. See [sliding windows](/observability/railql/how-it-works#use-a-sliding-window) for an example.

`count_distinct` doesn't support windows. Distinct counts from separate steps can't be added to obtain a window's distinct count, because the same value may occur in multiple steps.

## Stages

A stage follows a pipe (`|`) and transforms the result of the preceding expression. Multiple stages run in sequence from left to right.

| Stage | Operation |
|---|---|
| `sum`, `avg`, `min`, `max` | Aggregate numeric series at each step, with optional `by` or `without` grouping |
| `merge` | Combine Histogram distributions at each step, with optional `by` or `without` grouping |
| `p50`, `p75`, `p90`, `p95`, `p99`, `quantile(q)` | Extract a percentile from each distribution |
| `count` | Extract the number of observations in each distribution |
| `count_series` | Count series with data at each step |
| `rate`, `rate per 1h` | Convert a Counter total to a rate per second, or per the specified duration |
| `cumsum` | Calculate a Counter's running total from the start of the range |
| `to <unit>` | Convert values and their unit, as in `to GiB`, `to %`, or `to min` |
| `+`, `-`, `*`, `/` with a number | Apply arithmetic to each value without changing its unit |

A spatial aggregation groups series by the labels listed after `by`, or by all labels except those listed after `without`. Without either clause, all input series are combined into one. The output retains only the grouping labels.

For example, `| sum by replica` drops the `service` label. `| sum by replica, service` retains both labels for later stages or arithmetic. Stages such as `rate`, `to`, and percentile extraction preserve all input labels.

Unit conversion uses `to`. Arithmetic with a plain number doesn't update the unit: `| / 1024` divides each value by 1,024 but leaves a byte-valued series labeled in bytes. The editor warns about arithmetic that appears to be an attempt at unit conversion.

### Stage input and output kinds

Each stage accepts specific input kinds and produces an output kind. The output kind determines which subsequent stages are valid.

| Stage | Input | Output | Grouping |
|---|---|---|---|
| `sum` | Counter or UpDownCounter | Same kind | `by` or `without` |
| `avg`, `min`, `max` | Numeric series | Gauge | `by` or `without` |
| `merge` | Histogram | Histogram | `by` or `without` |
| `sum`, `count` | Histogram | Counter | Preserves labels |
| `avg`, `min`, `max`, percentiles | Histogram | Gauge | Preserves labels |
| `count_series` | Any series | Gauge | `by` or `without` |
| `rate`, `cumsum` | Counter | UpDownCounter | Preserves labels |
| `to <unit>` | Numeric series | Same kind | Preserves labels |

Some stage names have different meanings depending on the input kind. On Histograms, `| avg` extracts the mean of each distribution and preserves its labels. On numeric series, `| avg` averages across series. The sequence `| merge | avg` combines distributions first, then extracts the overall mean.

Multiplying or dividing two series produces a Gauge. Multiplying or dividing a series by a number without a unit preserves its kind. Dividing a number by a series, or applying remainder (`%`) with a series operand, produces a Gauge.

## Arithmetic

Arithmetic combines queries or numeric values with `+`, `-`, `*`, `/`, and `%`. Each query operand is enclosed in parentheses, including any stages applied to that operand:

```railql
((metric railway.memory.usage) /
 (metric railway.memory.limit)) | to %
```

This divides each replica's memory usage by its own limit, then converts the ratio to a percentage. Combining usage across replicas before dividing by a single replica's limit would overstate utilization.

### Match series by labels

Arithmetic pairs series whose values match on all shared label names. One operand's set of label names must be a subset of the other's, including the case where both sets are equal. The result retains the labels from both operands.

| Left labels | Right labels | Matching |
|---|---|---|
| `service` | `service` | Pair series with the same service value |
| `service, replica` | `service` | Reuse each service-level value for that service's replicas |
| `service` | No labels | Reuse the unlabeled series for every service |
| `service` | `deployment` | Reject with `E_LABELS_INCOMPATIBLE`; neither label set is a subset of the other |

Reusing a less-specific series across several matching series is called broadcasting. It depends on the labels, not the number of returned series. A series labeled `service=api` doesn't match `service=worker`, even if each operand returns only one series. Unmatched series are omitted.

<RailqlDiagram type="matching" />

### Operators and units

Multiplication, division, and remainder (`%`) take precedence over addition and subtraction. Operators with equal precedence are evaluated from left to right. Parentheses override this order.

Addition and subtraction require compatible units. Multiplication and division combine units: bytes divided by bytes produces a dimensionless ratio. The stage `| to %` converts a ratio such as `0.5` to `50%`.

The arithmetic `%` operator calculates a remainder, not a percentage. The result keeps the left operand's unit. The right operand must be dimensionless or have compatible units. Division or remainder by zero produces a missing value. See [Missing data and empty results](/observability/railql/errors-and-limits#missing-data-and-empty-results).

Numeric operands can include units, as in `8 GiB`. Unit conversion uses `to`; dividing bytes by the number `1024` changes the numeric value but leaves the unit as bytes.