Wednesday, 4 June 2025

Prometheus rate() Function: Measuring How Fast Your Metrics Are Growing

The rate() function calculates the average per-second increase of a counter over a given time range. In simple terms, It tells you how fast a value (like a counter) is increasing every second, averaged over the specified time window.

 

Syntax

rate(metric_name[time_range])

 

Here,

·      metric_name: A Prometheus counter metric (like http_requests_total)

·      [time_range]: The range of time you want to calculate the rate over (like [5m] for 5 minutes)

 

Points to note:

·      rate() works only on counters (monotonically increasing values).

·      It returns an instant vector, meaning one data point per series for the current evaluation time.

·      It’s perfect for alerting and graphs, especially for slow-moving metrics.

 

Example

Let’s say we have a counter metric: http_requests_total, which counts total HTTP requests to your server.

 

Here’s some made-up data from a 5-minute window:

Time

prometheus_http_requests_total{handler="/metrics"}

10:00:00 

1000

10:01:00 

1100

10:02:00 

1220

10:03:00 

1300

10:04:00 

1410

10:05:00 

1500

 

So in 5 minutes, the count increased from 1000 → 1500, which is a total of 500 requests.

 

Now let’s calculate the rate:

rate(prometheus_http_requests_total{handler="/metrics"}[5m])

 

This gives you: 500 requests / 300 seconds = 1.6667 requests/sec

 

So Prometheus would return a single value of 1.6667 (on a per-series basis), representing average rate of increase in requests per second in the last 5 minutes.

 


You can combine rate() with aggregation functions like topk to find out which metrics are increasing the fastest. For example, which endpoints or services are handling the most HTTP requests per second.

 

topk(3, rate(prometheus_http_requests_total[5m])) 

 


avg(rate(prometheus_http_requests_total[5m])) by (code)

Calculating the average rate of increase per second per status code across multiple time series (usually instances).

 

In summary,

·      Always apply rate() before using aggregators like sum(), avg().

·      Only use it on counters and histograms (not gauges).

·      Great for alerting thresholds like rate(errors_total[5m]) > 0.5

 

 

Previous                                                    Next                                                    Home

Match on specific labels using on keyword in Prometheus

When you use binary operators in PromQL like +, -, *, /, and, or, Prometheus matches time series based on all their labels by default.

But sometimes, you only want to match series based on specific labels and ignore all the others.

 

That’s where the on keyword comes in.

 

The on(...) keyword restricts the matching to only the labels you specify.

 

Example

node_cpu_seconds_total{mode="idle"} 
and on(cpu) 
node_cpu_seconds_total{mode="system"}

Here,

·      I am using the and operator to find time series that exist in both sets.

·      Normally, Prometheus would try to match all labels, including mode, instance, etc.

·      But with on(cpu), it only uses the cpu label to match.

·      So this query matches, all idle and system metrics that share the same cpu, even if they have different mode or instance.

 



Why is on useful?

Because sometimes:

·      The labels differ, but you still want to match.

·      You want precise control over which labels are used for matching.

·      You want to avoid unexpected mismatches due to extra labels like mode, instance, or job.

 

Understanding Prometheus Aggregation Operators

When you query metrics in Prometheus, you often get a bunch of time series, sometimes too many. Aggregation operators helps you to combine, group, or filter these metrics into something more useful.

 

For example,

sum(prometheus_http_requests_total)

 

This gives you the total number of HTTP requests across all codes, methods, or other labels.

 

Following table summarizes the aggregation operators supported by Prometheus.

 

Operator

Description

sum

Adds up values

min

Gets the smallest value

max

Gets the largest value

avg

Calculates the average

count

Counts how many values there are

stddev

Measures how much the values vary

stdvar

Measures how spread out the values are (variance)

group

Groups values together and sets them to 1

count_values("label")

Counts how many times each value appears and labels it

topk(n, ...)

Gets the top N biggest values

bottomk(n, ...)

Gets the bottom N smallest values

quantile(φ, ...)

Gets the percentile (like median or 95th)

limitk(n, ...)

Gets N random samples (experimental)

limit_ratio(r, ...)

Gets a portion of samples based on a ratio (experimental)

 

Examples

Example 1: Sum of all requests

sum(prometheus_http_requests_total)

 


Example 2: Sum of all requests grouped by response code

sum(prometheus_http_requests_total) by (code) 


 

Example 3: Top 2 HTTP codes by request count

topk(2, sum(prometheus_http_requests_total) by (code)) 


Example 4: Bottom 2 HTTP codes by request count

bottomk(2, sum(prometheus_http_requests_total) by (code))

 


Example 5: CPU usage grouped by mode

sum(node_cpu_seconds_total) by (mode)

 


Example 6: Count elements in the vector.

count(node_cpu_seconds_total)

 


In summary, Aggregation operators help you get a sense of large amounts of data, turn chaos into clarity, and build dashboards that actually tell a story. Start with simple aggregations. Try sum and count. Then slowly explore topk, quantile, and the rest as your needs grow.

 

References

https://prometheus.io/docs/prometheus/latest/querying/operators/

 

Previous                                                    Next                                                    Home

Tuesday, 3 June 2025

How to rename a column in BigQuery?

Renaming columns in BigQuery is an important task when evolving your database schema to maintain clarity and consistency. This guide provides a comprehensive overview of how to rename columns in BigQuery, including important considerations and limitations.​

Understanding Column Renaming in BigQuery

BigQuery supports renaming columns using the ALTER TABLE RENAME COLUMN statement. This feature simplifies schema modifications without the need to recreate tables.​

 

Syntax for Renaming a Column

To rename a column in BigQuery, use the following SQL syntax.

ALTER TABLE  `project.dataset.table`
RENAME COLUMN old_column_name TO new_column_name;

Here

·      project: Project name

·      dataset_name: The name of your dataset.

·      table_name: The name of your table.

·      old_column_name: The current name of the column you wish to rename.

·      new_column_name: The new name you want to assign to the column.


For example, I have employee table like below.

ALTER TABLE  `project.dataset.employee`
RENAME COLUMN age TO my_age;

Above statement renames age column of employee table to my_age.

 

You can confirm the same in schema section of the table.

 


Important Considerations

·      Impact on Dependent Objects: Renaming a column does not automatically update references in views, materialized views, or scripts that depend on the old column name. You must manually update these objects to reflect the new column name to prevent errors.

 

·      Nested Fields Limitation: The ALTER TABLE RENAME COLUMN statement cannot be used to rename subfields within nested structures (e.g., fields inside a STRUCT or repeated fields). To rename nested fields, you need to recreate the table with the desired schema.

 

·      Partitioning and Clustering Columns: Renaming columns that are used for partitioning or clustering is not permitted. To change the names of such columns, you must:

 

o   Create a new table with the updated column names.

o   Transfer data from the existing table to the new table.

o   Recreate any associated partitioning or clustering configurations.

 

Best Practices

·      Backup Data: Before making schema changes, create a backup of your data to prevent accidental loss.

 

·      Update Dependencies: After renaming a column, systematically update all dependent objects and scripts to reference the new column name.

 

·      Test Changes: Implement changes in a development or staging environment first to ensure they work as expected before applying them to production.

 

·      Review Documentation: Familiarize yourself with BigQuery's schema modification guidelines (https://cloud.google.com/bigquery/docs/managing-table-schemas)  to understand the full scope of capabilities and limitations.

 

By following these guidelines, you can effectively manage column renaming in BigQuery, ensuring the integrity and reliability of your data schema.

 

Previous                                                    Next                                                    Home

How to Add a New Column to an Existing Table in BigQuery?

Adding a new column to an existing table in BigQuery is a common task when evolving your data schema. BigQuery allows schema updates like adding new columns without requiring a full table rewrite.

Add a column using SQL

You can use the ALTER TABLE statement to add a new column.

ALTER TABLE `my_project.my_dataset.my_table`
ADD COLUMN new_column_name STRING;

Let’s create an employee table by executing following statement.

CREATE TABLE `your_project.your_dataset.employee` (
    employee_id INT64,
    first_name STRING,
    last_name STRING,
    email STRING,
    hire_date DATE,
    department STRING
);

 


Let’s add new column ‘salary’ of type DOUBLE to the employee table by executing following ALTER statement.

ALTER TABLE `your_project.your_dataset.employee`
ADD COLUMN salary FLOAT64;

Go back to the table schema view and click on Refresh button. You can see the updated table schema.  


 

You can even add new column by clicking on ‘Edit schema’ button.

 


Click on the button ‘Add field’. Fill the field name, type, Mode and description.  

 


Click on the Save button to reflect these changes. Now go back to schema section, you can confirm that the new column ‘age’ is added.

 

 

Previous                                                    Next                                                    Home