Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-run-alert-configuration@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin cloud-run-alert-configuration v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install cloud-run-alert-configuration

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/cloud-run-alert-configuration/

Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-run-alert-configuration for Copilot to auto-discover it.

Skill Files (5)

SKILL.md 7.3 KB
---
name: cloud-run-alert-configuration
metadata:
  version: "1.0.3"
  category: Serverless
description: >-
  Configures best-practice, high-signal alerting policies for Cloud Run
  resources on Google Cloud (services, jobs, and worker pools) based on seasoned
  SRE practices. Use
  when analyzing, recommending, writing, or deploying Terraform PromQL alerting
  policies to monitor Cloud Run error rates (4xx/5xx), request latency, container instance
  saturation (warning/critical), container CPU/memory utilization and allocation, billable
  instance time, job execution status, and worker pool queue backlog. Don't use for
  GKE workloads (use gke-alert-configuration) or Compute Engine VMs.
allowed-tools: terraform gcloud
---

# Cloud Run Alert Configuration

Production-grade observability for Cloud Run using Terraform and PromQL
(Cloud Monitoring). Grounded in SRE practices, this skill focuses strictly on
actionable user impact and scaling bounds.

--------------------------------------------------------------------------------

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-run-alert-configuration)"`
and append `agent-skills/1.0 (skill:cloud-run-alert-configuration)` to `User-Agent` headers.

## CRITICAL RULES

*   **Prompt-First Fast Path (Skip Discovery When Named)**:
    *   **If the user prompt explicitly specifies the target Cloud Run service, job, or worker pool name** (e.g., `'video-encoder'`, `'nightly-reconciliation'`, `'web-frontend'`, `'catalog-service'`, `'api-gateway'`, `'order-processor'`), **SKIP all workspace `.tf` file scanning (`find_by_name`, `code_search`, `list_dir`) and `gcloud` CLI discovery commands entirely**.
    *   Do NOT run `gcloud`, `terraform`, or file search tools when the target name is already provided in the prompt. Instead, parameterize the project ID (`variable "scoping_project_id" { default = "my-gcp-project" }`) and target resource name in Terraform variables and proceed immediately to **Step 2 (Configure Alerts)**.
*   **Autonomous Discovery (Only When Target Name is Omitted)**:
    *   **Never Scan Root Monorepo or Unbounded Directories**: Never run `find_by_name` or `ls` across root workspace directories.
    *   **Config First**: Only if the prompt omits the resource name, check `.tf` files in the immediate working directory for `google_cloud_run_v2_service`, `google_cloud_run_service`, or `google_cloud_run_v2_job`.
    *   **CLI Second (Graceful Fallback)**: Only if unconfigured in prompt or local `.tf` files, attempt `gcloud config get-value project` and `gcloud run services list`. If any `gcloud` command fails (e.g., auth or metadata errors) or `terraform` is missing, immediately stop running CLI commands and output parameterized HCL using explicit variable defaults.
*   **Workload Routing**: Always classify the workload target and follow its
    specific reference guide:
    *   For HTTP Services follow [services.md](references/services.md)
    *   For Cloud Run Jobs follow [jobs.md](references/jobs.md)
    *   For Worker Pools follow [worker_pools.md](references/worker_pools.md)
*   **Explicit Defaults & User Overrides**:
    *   Always use explicit defaults for all constants specified in
        the target workload's reference file (SLO targets, latency thresholds,
        SLAs, saturation ceilings, rate guards).
    *   State the defaults being applied in the final summary output and clearly
        notify the user that any default constant can be customized or
        overridden via Terraform variables or prompt input.
*   **Metric Scope Centralization**: Parameterize `project = var.scoping_project_id` in all Terraform `google_monitoring_alert_policy` resources so the policy can target either a single project or a centralized Cloud Monitoring Metrics Scope.
*   **PromQL `duration` (Retest Window) Rules**:
    *   **Lookbacks $\le$ 25h**: Set `duration = "300s"` (5m buffer) to absorb
        transient blips and scale-up lag (except immediate job failure alerts
        which use `duration = "0s"`).
    *   **Lookbacks $> 25$h** (e.g. 3d/7d Slow Burn): **Omit `duration`
        entirely** (or set to `0s`). Cloud Monitoring rejects PromQL queries
        with `duration` set on lookbacks >25h (`INVALID_ARGUMENT`).
*   **Terraform Standards & Mandatory Labels**:
    *   Output clean, complete `.tf` configurations using `google_monitoring_alert_policy` and `condition_prometheus_query_language` directly in your response.
    *   **Mandatory User Labels**: Every `google_monitoring_alert_policy` resource MUST include a `user_labels` block containing:
        ```hcl
        user_labels = {
          created-with-google-skill = "cloud-run-alert-configuration"
        }
        ```
    *   Include `alert_strategy { auto_close = "604800s" }` and parameterize `notification_channels = var.notification_channels`.

## WORKFLOW STEPS

### 1. Discovery & Target Identification

*   **Fast Path (Target Named in Prompt)**: If the user prompt names the target Cloud Run service, job, or worker pool, **skip all discovery commands and file searches** and proceed directly to **Step 2**.
*   **Discovery Fallback (Target Unnamed)**: Only if no resource name is provided in the prompt, check local `.tf` files or run `gcloud` to identify the target workload type and name. If `gcloud` auth fails, fall back immediately to default Terraform variables (`var.scoping_project_id`).

### 2. Configure Alerts

*   Route to the corresponding guide to generate the alert policies:
    *   **HTTP Services**: Open [services.md](references/services.md). Apply the
        requested alerting policy or standard suite covering availability SLOs (5xx), request
        latency (P95/P99), client errors (4xx), container instance saturation,
        container CPU/memory utilization, traffic anomalies (drop/surge), and billable
        instance time.
    *   **Batch Jobs**: Open [jobs.md](references/jobs.md). Apply immediate job
        execution failure alerts (`duration = "0s"`).
    *   **Worker Pools**: Open [worker_pools.md](references/worker_pools.md).
        Apply the 4-policy standard suite (Task Success SLO Fast/Slow Burn,
        Backlog ETD, Message Age SLA).

### 3. Terraform Generation & Review

*   Provide the complete HCL configuration in your response with explicitly parameterized defaults and the mandatory `user_labels` block (`created-with-google-skill = "cloud-run-alert-configuration"`).
*   State the applied defaults and remind the user of their ability to override
    any constant.
*   Provide a clear plain-English breakdown of the PromQL logic and triggering
    thresholds.

--------------------------------------------------------------------------------

## Additional Resources

*   [Cloud Run Documentation](https://docs.cloud.google.com/run/docs/overview/what-is-cloud-run.md.txt)
*   [Cloud Monitoring PromQL Documentation](https://docs.cloud.google.com/monitoring/promql/promql-in-monitoring.md.txt)
*   [Google Cloud Alerting Policies in Terraform](https://docs.cloud.google.com/monitoring/alerts/terraform.md.txt)
*   [Google SRE Workbook: Alerting on SLOs](https://sre.google/workbook/alerting-on-slos/)
references/
attribution.md 1.9 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-run-alert-configuration)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:cloud-run-alert-configuration)` in the `User-Agent`
    header. If a `User-Agent` header is already specified, append this string to
    the end of it rather than overwriting existing `User-Agent` data — the
    collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
    tokens, so any rewording breaks attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:cloud-run-alert-configuration)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
jobs.md 3.3 KB
# Cloud Run Jobs Alert Configuration

Best-practice observability for scheduled or ad-hoc Cloud Run Jobs.

## Fast-Path Standard: Job Execution Failure Alert

For Cloud Run Jobs (scheduled cron, ad-hoc batch processing, or ETL workflows),
every execution failure represents direct user or system impact.

The standard observability strategy for Cloud Run Jobs is to **alert immediately
on any failed job execution (`result="failed"`)**.

--------------------------------------------------------------------------------

## Default Constants & Parameterization

All generated Terraform alert policies use explicit default constants. Users can
override any parameter in HCL variables or via prompt instruction:

Constant / Parameter      | Explicit Default | HCL Variable Name             | Description & Override Option
:------------------------ | :--------------- | :---------------------------- | :----------------------------
`single_failure_lookback` | `"15m"`          | `var.single_failure_lookback` | Lookback window for detecting single job execution failures.

--------------------------------------------------------------------------------

## PromQL & Terraform Configuration

### Immediate Job Failure Alert

Monitors any single execution failure (`result="failed"`). Evaluates with
`duration = "0s"` to page immediately upon task/job failure.

#### PromQL Query

```promql
sum(
  increase(run_googleapis_com:job_completed_execution_count{result="failed", job_name="[JOB_NAME]"}[15m])
) by (job_name, location) > 0
```

#### Terraform Snippet

```hcl
variable "monitored_jobs" {
  description = "List of Cloud Run job names to monitor for execution failures"
  type        = list(string)
  default     = ["data-ingest", "nightly-sync"]
}

variable "single_failure_lookback" {
  description = "Lookback window for detecting single execution failures"
  type        = string
  default     = "15m"
}

resource "google_monitoring_alert_policy" "job_execution_failure" {
  for_each     = toset(var.monitored_jobs)
  project      = var.scoping_project_id
  display_name = "[Cloud Run Job] Execution Failure - ${each.value}"
  combiner     = "OR"

  conditions {
    display_name = "Job Execution Failed - ${each.value}"
    condition_prometheus_query_language {
      query = <<-EOT
        sum(
          increase(run_googleapis_com:job_completed_execution_count{result="failed", job_name="${each.value}"}[${var.single_failure_lookback}])
        ) by (job_name, location) > 0
      EOT
      duration = "0s"
    }
  }

  user_labels = {
    severity                    = "critical"
    job                         = each.value
    tier                        = "failure"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

--------------------------------------------------------------------------------

## Telemetry Data Sources Reference

Signal Indicator          | Native Metric                                      | SRE Strategy
:------------------------ | :------------------------------------------------- | :-----------
**Job Execution Failure** | `run.googleapis.com/job/completed_execution_count` | **Immediate Failure Alert**: Alert immediately on any failed execution (`result="failed"`)
services.md 28.0 KB
# Cloud Run Services Alert Configuration

Best-practice observability for HTTP-triggered Cloud Run Services.

--------------------------------------------------------------------------------

## Table of Contents

*   [Fast-Path Defaults](#fast-path-defaults) (#fast-path-defaults)
    *   [Core SLO & Instance Saturation Suite](#core-slo-instance-saturation-suite)
    *   [Extended Dashboard & Resource Protection Suite](#extended-dashboard-resource-protection-suite)
*   [Default Constants & Override Protocol](#default-constants-override-protocol)
*   [SLO Delegation & Fallback Rule](#slo-delegation-fallback-rule) (~line 83)
*   [PromQL & Terraform Query Templates](#promql-terraform-query-templates)
    *   [1. Container Instance Saturation](#1-container-instance-saturation)
    *   [2. Container Memory & CPU Utilization (OOM Prevention & Throttling)](#2-container-memory-cpu-utilization-oom-prevention-throttling)
    *   [3. Availability SLO Burn Rate Queries](#3-availability-slo-burn-rate-queries)
    *   [4. Request Latency SLO Queries (P95 & P99)](#4-request-latency-slo-queries-p95-p99)
    *   [5. Client Error Surge (4xx Response Code Storm)](#5-client-error-surge-4xx-response-code-storm)
    *   [6. Traffic & FinOps Anomalies](#6-traffic-finops-anomalies)
    *   [7. Conditional Diagnostic: Cold Start Latency](#7-conditional-diagnostic-cold-start-latency)
*   [Telemetry Data Sources Reference](#telemetry-data-sources-reference)

--------------------------------------------------------------------------------

## Fast-Path Defaults
When standard alerting is requested or thresholds are unspecified, apply the standard suite tailored to user requirements:

### Core SLO & Instance Saturation Suite

1. **Availability SLO (Fast Burn)**: 99.9% target, 1h & 5m windows, $14.4\times$ burn rate, `duration = "300s"` (Critical/Paging).
2. **Availability SLO (Slow Burn)**: 99.9% target, 3d & 6h windows, $1.0\times$ burn rate, **omit `duration`** (Warning/Ticket).
3. **Request Latency SLO (P95)**: Window-based 1h lookback, P95 $\le 500\text{ms}$ in 99% of 5m windows (Warning).
4. **Request Latency SLO (P99)**: Window-based 1h lookback, P99 $\le 1000\text{ms}$ in 99% of 5m windows (Warning).
5. **Instance Saturation (Warning)**: >80% of service `max_instances` ceiling (Warning).
6. **Instance Saturation (Critical)**: $\ge 95\%$ of service `max_instances` ceiling (Critical).
7. **Traffic Drop Anomaly**: 5m throughput drop vs. 1h moving average baseline with min-volume guard (`rate(...[1h]) > 1.0`).

### Extended Dashboard & Resource Protection Suite

8. **Container Memory Saturation & OOM Risk**: P95 container memory utilization $\ge 90\%$ (Critical - Exit Code 137 prevention).
9. **Container CPU Saturation & Throttling**: P95 container CPU utilization $> 85\%$ (Warning).
10. **Client Error Surge (4xx)**: 4xx response code ratio $> 10\%$ with 5 req/s min-volume guard (Warning).
11. **Billable Instance Time Surge**: 5m billable time rate $> 3\times$ 1h moving average baseline (FinOps Warning).
12. **Traffic Surge Anomaly**: 5m request rate $> 3\times$ 1h moving average baseline with min-volume guard (Warning).

---

## Default Constants & Override Protocol

All generated Terraform alert policies use explicit default constants. Users can override any parameter in HCL variables or via prompt instruction:

| Constant / Parameter | Explicit Default | HCL Variable Name | Description & Override Option |
| :--- | :--- | :--- | :--- |
| `availability_slo_target` | `0.999` (99.9%) | `var.availability_slo_target` | Availability target ratio. Override to 0.99 or 0.9999. |
| `latency_p95_threshold_ms` | `500` (500ms) | `var.latency_p95_threshold_ms` | P95 latency limit in milliseconds. |
| `latency_p99_threshold_ms` | `1000` (1000ms) | `var.latency_p99_threshold_ms` | P99 latency limit in milliseconds. |
| `saturation_warning_ratio` | `0.80` (80%) | `var.saturation_warning_ratio` | Instance saturation warning threshold relative to `max_instances`. |
| `saturation_critical_ratio`| `0.95` (95%) | `var.saturation_critical_ratio` | Instance saturation critical threshold relative to `max_instances`. |
| `memory_saturation_ratio` | `0.90` (90%) | `var.memory_saturation_ratio` | P95 container memory utilization critical limit (OOM prevention). |
| `cpu_saturation_ratio` | `0.85` (85%) | `var.cpu_saturation_ratio` | P95 container CPU utilization warning limit. |
| `client_error_4xx_ratio` | `0.10` (10%) | `var.client_error_4xx_ratio` | Maximum allowable ratio of 4xx client errors. |
| `traffic_drop_ratio` | `0.20` (80% drop) | `var.traffic_drop_ratio` | Throughput drop threshold vs 1h moving average. |
| `traffic_min_hourly_rate` | `1.0` (1 req/s) | `var.traffic_min_hourly_rate` | Min hourly rate guard to prevent scale-to-zero false alarms. |
| `traffic_surge_multiplier` | `3.0` (3x surge) | `var.traffic_surge_multiplier` | Throughput spike multiplier vs 1h moving average. |
| `traffic_surge_min_rate` | `15.0` (15 req/s) | `var.traffic_surge_min_rate` | Minimum 5m request rate guard (req/s) to suppress traffic surge false alarms on low volume. |
| `billable_time_surge_multiplier` | `3.0` (3x surge) | `var.billable_time_surge_multiplier` | Billable compute time multiplier vs 1h moving average. |
| `billable_time_min_rate` | `5.0` (5 s/s) | `var.billable_time_min_rate` | Minimum 5m billable instance-seconds rate guard to prevent FinOps false alarms on low baseline usage. |
| `retest_duration_buffer` | `"300s"` (5m) | `var.retest_duration_buffer` | Retest window for lookbacks $\le 25$h. Omitted for lookbacks $>25$h. |

---

## SLO Delegation & Fallback Rule

* **If `google-cloud-slo-alert-configuration` skill is available**: use it to inform SLO creation.
* **If `google-cloud-slo-alert-configuration` skill is NOT available**: Use the standard PromQL burn-rate templates provided directly in this reference guide as a complete, standalone solution.

---

## PromQL & Terraform Query Templates

### 1. Container Instance Saturation
Monitors when active container instances approach configured scaling ceilings (`max_instances`).
> [!NOTE]
> PromQL queries for `container_instance_count` MUST include the label matcher `monitored_resource="cloud_run_revision"` to prevent API validation errors resulting from metric ambiguity with `cloud_run_worker_pool`.

#### Warning Query (>80% Capacity)

```promql
sum(
  max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", state="active"}[5m])
) by (service_name, location) / [SERVICE_MAX_INSTANCES] > 0.80
```

#### Critical Query (>=95% Capacity)

```promql
sum(
  max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", state="active"}[5m])
) by (service_name, location) / [SERVICE_MAX_INSTANCES] >= 0.95
```

#### Terraform Snippet (Instance Saturation Policies)

```hcl
variable "cloud_run_services" {
  description = "Map of Cloud Run services to monitor and their max_instances ceilings"
  type = map(object({
    max_instances = number
  }))
  default = {
    "api-gateway" = { max_instances = 1000 }
  }
}

variable "saturation_warning_ratio" {
  description = "Ratio threshold for container instance saturation warning"
  type        = number
  default     = 0.80
}

variable "saturation_critical_ratio" {
  description = "Ratio threshold for container instance saturation critical"
  type        = number
  default     = 0.95
}

resource "google_monitoring_alert_policy" "instance_saturation_warning" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container Instance Saturation Warning (>80% Limit) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Active Instances Exceed 80% of ${each.key} Ceiling (${each.value.max_instances})"
    condition_prometheus_query_language {
      query = <<-EOT
        sum(
          max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="${each.key}", state="active"}[5m])
        ) by (service_name, location) / ${each.value.max_instances} > ${var.saturation_warning_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}

resource "google_monitoring_alert_policy" "instance_saturation_critical" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container Instance Saturation Critical (>=95% Limit) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Active Instances Exceed 95% of ${each.key} Ceiling (${each.value.max_instances})"
    condition_prometheus_query_language {
      query = <<-EOT
        sum(
          max_over_time(run_googleapis_com:container_instance_count{monitored_resource="cloud_run_revision", service_name="${each.key}", state="active"}[5m])
        ) by (service_name, location) / ${each.value.max_instances} >= ${var.saturation_critical_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "critical"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### 2. Container Memory & CPU Utilization (OOM Prevention & Throttling)

Monitors actual CPU and Memory resource consumption inside container instances.

#### 2.1 Container Memory Saturation (OOM Risk)
Triggers when the 95th percentile memory utilization reaches critical levels, preventing container abrupt termination via Linux kernel OOMKilled (exit code 137).

```promql
histogram_quantile(0.95,
  sum(
    rate(run_googleapis_com:container_memory_utilizations_bucket{
      monitored_resource="cloud_run_revision",
      service_name="[SERVICE_NAME]"
    }[5m])
  ) by (le, service_name, location)
) >= 0.90
```

#### 2.2 Container CPU Saturation & Throttling
Triggers when the 95th percentile container CPU utilization exceeds 85%, indicating compute starvation or inadequate vCPU sizing.

```promql
histogram_quantile(0.95,
  sum(
    rate(run_googleapis_com:container_cpu_utilizations_bucket{
      monitored_resource="cloud_run_revision",
      service_name="[SERVICE_NAME]"
    }[5m])
  ) by (le, service_name, location)
) > 0.85
```

#### Terraform Snippet (Resource Saturation Policies)

```hcl
variable "memory_saturation_ratio" {
  description = "P95 container memory utilization threshold (OOM danger)"
  type        = number
  default     = 0.90
}

variable "cpu_saturation_ratio" {
  description = "P95 container CPU utilization threshold (throttling danger)"
  type        = number
  default     = 0.85
}

resource "google_monitoring_alert_policy" "container_memory_saturation_critical" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container Memory Saturation Critical (P95 >= 90% OOM Risk) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "P95 Memory Utilization >= 90% on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        histogram_quantile(0.95,
          sum(
            rate(run_googleapis_com:container_memory_utilizations_bucket{
              monitored_resource = "cloud_run_revision",
              service_name       = "${each.key}"
            }[5m])
          ) by (le, service_name, location)
        ) >= ${var.memory_saturation_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "critical"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}

resource "google_monitoring_alert_policy" "container_cpu_saturation_warning" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Container CPU Saturation Warning (P95 > 85%) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "P95 CPU Utilization > 85% on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        histogram_quantile(0.95,
          sum(
            rate(run_googleapis_com:container_cpu_utilizations_bucket{
              monitored_resource = "cloud_run_revision",
              service_name       = "${each.key}"
            }[5m])
          ) by (le, service_name, location)
        ) > ${var.cpu_saturation_ratio}
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### 3. Availability SLO Burn Rate Queries

#### Availability Fast Burn (1h & 5m Windows)

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[5m])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[1h])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  # Min-volume guard: ensure at least 1 req/s to prevent false alerts on scale-to-zero or low-traffic services
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) > 1.0
)
```

#### Availability Slow Burn (3d & 6h Windows)
> [!WARNING]
> Lookback windows >25h (like `[3d]`) require **omitting `duration`** in HCL.

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[6h])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[6h])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="5xx"}[3d])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[3d])) by (service_name, location)
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  # Min-volume guard: ensure at least 1 req/s to prevent false alerts on scale-to-zero or low-traffic services
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[6h])) by (service_name, location) > 1.0
)
```

---

### 4. Request Latency SLO Queries (P95 & P99)

#### P95 Request Latency SLO

```promql
avg_over_time(
  (
    histogram_quantile(0.95, sum(rate(run_googleapis_com:request_latencies_bucket{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (le, service_name, location)) > [LATENCY_THRESHOLD_MS]
  )[1h:5m]
) > (1 - [WINDOW_SLO_TARGET])
```

#### P99 Request Latency SLO

```promql
avg_over_time(
  (
    histogram_quantile(0.99, sum(rate(run_googleapis_com:request_latencies_bucket{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (le, service_name, location)) > [LATENCY_THRESHOLD_MS]
  )[1h:5m]
) > (1 - [WINDOW_SLO_TARGET])
```

---

### 5. Client Error Surge (4xx Response Code Storm)
Detects client authorization failures (401/403) or concurrency rate-limiting (429) across inbound requests.

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]", response_code_class="4xx"}[5m])) by (service_name, location)
  /
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  > [CLIENT_ERROR_RATIO]
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location) > [MIN_REQ_RATE]
)
```

#### Terraform Snippet (4xx Client Error Policy)

```hcl
variable "client_error_4xx_ratio" {
  description = "Ratio threshold for 4xx client errors"
  type        = number
  default     = 0.10
}

variable "client_error_min_rate" {
  description = "Minimum request rate (req/s) to guard against low-volume noise"
  type        = number
  default     = 5.0
}

resource "google_monitoring_alert_policy" "client_error_4xx_surge" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Client Error Surge (4xx > 10%) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "4xx Error Ratio Exceeds 10% on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}", response_code_class="4xx"}[5m])) by (service_name, location)
          /
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          > ${var.client_error_4xx_ratio}
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location) > ${var.client_error_min_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "client_error"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### 6. Traffic & FinOps Anomalies

#### 6.1 Traffic Drop Anomaly
Detects sudden traffic drops compared to 1h moving average, guarded against scale-to-zero.

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  /
  (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) + 0.001)
) < [DROP_THRESHOLD_RATIO]
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) > [MIN_HOURLY_RATE]
)
```

#### Terraform Snippet (Traffic Drop Policy)

```hcl
variable "traffic_drop_ratio" {
  description = "Ratio threshold vs 1h average for traffic drop anomaly"
  type        = number
  default     = 0.20 # 80% drop
}

variable "traffic_min_hourly_rate" {
  description = "Minimum hourly request rate (req/s) guard to prevent scale-to-zero false alarms"
  type        = number
  default     = 1.0 # 1 req/s
}

resource "google_monitoring_alert_policy" "traffic_drop_anomaly" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Traffic Drop Anomaly (>80% Drop) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Traffic Dropped >80% vs 1h Average on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          /
          (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) + 0.001)
        ) < ${var.traffic_drop_ratio}
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) > ${var.traffic_min_hourly_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "traffic"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

#### 6.2 Traffic Surge Anomaly
Detects sudden volumetric traffic spikes (e.g. DDoS or unexpected viral load) compared to the 1h moving average baseline (`> 3x` baseline with a minimum rate guard of `> 15 req/s`).

##### PromQL Query

```promql
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  /
  (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) + 0.1)
  > 3.0
)
and
(
  sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location) > 15.0
)
```

##### Terraform Snippet

```hcl
variable "traffic_surge_multiplier" {
  description = "Throughput spike multiplier vs 1h moving average baseline"
  type        = number
  default     = 3.0 # 3x surge
}

variable "traffic_surge_min_rate" {
  description = "Minimum 5m request rate guard (req/s) to suppress false alarms on low volume"
  type        = number
  default     = 15.0 # 15 req/s
}

resource "google_monitoring_alert_policy" "traffic_surge_anomaly" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] Traffic Surge Anomaly (>3x Baseline) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Traffic Surged >3x vs 1h Average on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          /
          (sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) + 0.1)
          > ${var.traffic_surge_multiplier}
        )
        and
        (
          sum(rate(run_googleapis_com:request_count{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location) > ${var.traffic_surge_min_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "traffic"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

#### 6.3 Billable Instance Time Surge (FinOps Cost Control)
Monitors runaway autoscaling or unoptimized compute consumption by tracking surges in billable container instance time (`> 3x` 1-hour moving average baseline with a minimum billable instance-seconds guard `> 5.0`).

##### PromQL Query

```promql
(
  sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location)
  /
  (sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[1h])) by (service_name, location) + 0.1)
  > 3.0
)
and
(
  sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[5m])) by (service_name, location) > 5.0
)
```

##### Terraform Snippet

```hcl
variable "billable_time_surge_multiplier" {
  description = "Billable compute time surge multiplier vs 1h moving average baseline"
  type        = number
  default     = 3.0 # 3x surge
}

variable "billable_time_min_rate" {
  description = "Minimum 5m billable instance-seconds rate guard to suppress alerts on low baseline usage"
  type        = number
  default     = 5.0 # 5 billable instance-seconds/s
}

resource "google_monitoring_alert_policy" "billable_instance_time_surge" {
  for_each     = var.cloud_run_services
  project      = var.scoping_project_id
  display_name = "[Cloud Run] FinOps Billable Instance Time Surge (>3x Baseline) - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Billable Instance Time >3x vs 1h Average on ${each.key}"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location)
          /
          (sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="${each.key}"}[1h])) by (service_name, location) + 0.1)
          > ${var.billable_time_surge_multiplier}
        )
        and
        (
          sum(rate(run_googleapis_com:container_billable_instance_time{monitored_resource="cloud_run_revision", service_name="${each.key}"}[5m])) by (service_name, location) > ${var.billable_time_min_rate}
        )
      EOT
      duration = "300s"
    }
  }

  user_labels = {
    severity                    = "warning"
    service                     = each.key
    tier                        = "finops"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

---

### 7. Conditional Diagnostic: Cold Start Latency

```promql
histogram_quantile(0.95,
  sum(
    rate(run_googleapis_com:container_startup_latencies_bucket{monitored_resource="cloud_run_revision", service_name="[SERVICE_NAME]"}[30m])
  ) by (le, service_name, location)
) > [STARTUP_LATENCY_SECONDS]
```

---

## Telemetry Data Sources Reference

| Signal Indicator | Native Metric | SRE Observability Strategy |
| :--- | :--- | :--- |
| **Availability (5xx)** | `run.googleapis.com/request_count` | **SLO Fast Burn (1h/5m) & Slow Burn (3d/6h)** (`response_code_class="5xx"`) |
| **Request Latency (P50/P95/P99)** | `run.googleapis.com/request_latencies` | **SLO P95 & P99 Window Evaluation** (`request_latencies_bucket`) |
| **Performance / Client Errors (4xx)** | `run.googleapis.com/request_count` | **Client Error Spike Alert**: 4xx ratio $> 10\%$ with 5 req/s guard |
| **Container Instance Saturation** | `run.googleapis.com/container/instance_count` | **Scaling Ceiling Warning (0.80) & Critical (0.95)** vs `max_instances` |
| **Container Memory Utilization** | `run.googleapis.com/container/memory/utilizations` | **OOM Prevention Alert**: P95 memory utilization $\ge 90\%$ (Exit 137 guard) |
| **Container CPU Utilization** | `run.googleapis.com/container/cpu/utilizations` | **Compute Throttling Alert**: P95 CPU utilization $> 85\%$ |
| **Billable Instance Time** | `run.googleapis.com/container/billable_instance_time` | **FinOps Cost Spike Alert**: 5m rate $> 3\times$ 1h moving average baseline |
| **Container CPU Allocation** | `run.googleapis.com/container/cpu/allocation_time` | **Regional vCPU Quota Headroom Monitoring** |
| **Container Memory Allocation** | `run.googleapis.com/container/memory/allocation_time` | **Regional RAM Quota Headroom Monitoring** |
| **Traffic Drop Anomaly** | `run.googleapis.com/request_count` | **Guarded Anomaly Alert**: Drop vs. 1h baseline (`rate(...[1h]) > 1.0`) |
| **Cold Start Latency** | `run.googleapis.com/container/startup_latencies` | **Conditional Diagnostic**: P95 startup latency over 30m window |
worker_pools.md 12.0 KB
# Cloud Run Worker Pools Alert Configuration

Best-practice observability for Cloud Run Worker Pools.

--------------------------------------------------------------------------------

## Table of Contents

*   [Fast-Path Defaults](#fast-path-defaults)
*   [Default Constants & Override Protocol](#default-constants-override-protocol)
*   [SLO Delegation & Fallback Rule](#slo-delegation-fallback-rule)
*   [Workload Target Discovery](#workload-target-discovery)
    *   [Autonomous Parameter Discovery](#autonomous-parameter-discovery)
*   [PromQL & Terraform Query Templates](#promql-terraform-query-templates)
    *   [1. Task Success Rate SLO Burn Rate Queries](#1-task-success-rate-slo-burn-rate-queries)
    *   [2. Queue Backlog Drain Time (ETD)](#2-queue-backlog-drain-time-etd)
    *   [3. Oldest Unacked Message Age](#3-oldest-unacked-message-age)
    *   [4. Health Probe Success Rate SLO Burn Rate Queries](#4-health-probe-success-rate-slo-burn-rate-queries)
*   [Telemetry Data Sources Reference](#telemetry-data-sources-reference)

--------------------------------------------------------------------------------

## Fast-Path Defaults
When standard alerting is requested or thresholds are unspecified, suggest the following 4-policy standard suite:

1. **Task Success Rate SLO (Fast Burn)**: 99.9% target, 1h & 5m windows, $14.4\times$ burn rate, `duration = "300s"` (Critical/Paging).
2. **Task Success Rate SLO (Slow Burn)**: 99.9% target, 3d & 6h windows, $1.0\times$ burn rate, **omit `duration`** (Warning/Ticket).
3. **Queue Backlog Drain Time (ETD)**: Estimated time to drain queue exceeds processing SLA threshold (e.g., >30m) with `duration = "300s"` retest buffer (Warning/Paging).
4. **Oldest Unacked Message Age**: Oldest unacknowledged message age exceeds SLA threshold (Critical/Paging).

> [!NOTE]
> Unlike HTTP Services (where container saturation directly causes HTTP 504 errors), Worker Pools operating at `max_instances` are operating at maximum efficiency. As long as Queue Drain Time (ETD) and Message Age remain within SLA, instance saturation is expected and does not trigger alerts.

---

## Default Constants & Override Protocol

All generated Terraform alert policies use explicit default constants. Users can override any parameter in HCL variables or via prompt instruction:

| Constant / Parameter | Explicit Default | HCL Variable Name | Description & Override Option |
| :--- | :--- | :--- | :--- |
| `task_success_slo_target` | `0.999` (99.9%) | `var.task_success_slo_target` | Task processing success rate target. Override to 0.99 or 0.9999. |
| `health_probe_slo_target` | `0.999` (99.9%) | `var.health_probe_slo_target` | Process health probe attempt success target. |
| `max_drain_time_second` | `1800` (30m) | `var.max_drain_time_second` | Maximum allowed Queue Estimated Time to Drain (ETD) SLA. |
| `oldest_message_age_second`| `1800` (30m) | `var.oldest_message_age_second`| Maximum allowed unacknowledged message age SLA. |
| `retest_duration_buffer` | `"300s"` (5m) | `var.retest_duration_buffer` | Retest window for lookbacks $\le 25$h. Omitted for lookbacks $>25$h. |

---

## SLO Delegation & Fallback Rule

* **If `google-cloud-slo-alert-configuration` skill is available**: use it to inform SLO creation.
* **If `google-cloud-slo-alert-configuration` skill is NOT available**: Use the standard PromQL burn-rate templates provided directly in this reference guide as a complete, standalone solution.

---

## Workload Target Discovery

### Autonomous Parameter Discovery
Before proposing alerts, ensure the Google Cloud SDK is installed and configured properly. Then discover worker pool telemetry and queue bindings:

* **Queue Integration (Direct API & Config Scan)**:
  1. **Worker Pool API**: Run `gcloud run worker-pools describe [NAME] --format="json"` to check container environment variables (`spec.template.spec.containers[].env`) for `PUBSUB_SUBSCRIPTION`, `SUBSCRIPTION_ID`, or `TOPIC_ID`.
  2. **Service Account IAM Binding**: Extract `serviceAccountName` from the worker pool description and run `gcloud pubsub subscriptions list --format="json"` to check which subscriptions grant `roles/pubsub.subscriber` to that service account.
  3. **Terraform Scan**: Search `.tf` files for `google_pubsub_subscription` resources associated with the worker pool module.
  * *Outcome*: If a Pub/Sub subscription is identified, apply Task Success SLOs, Backlog Drain Time (ETD), and Message Age alerts.
* **Non-Pub/Sub & Alternative Consumer Workloads**:
  Worker pools can also operate as pull-based consumers for alternative queue systems (e.g., Apache Kafka, RabbitMQ) or run custom background event loops without Pub/Sub bindings. When not bound to Pub/Sub, the primary alerting signals to configure are container CPU/Memory utilization and process health probes (`run.googleapis.com/container/completed_probe_attempt_count`).

---

## PromQL & Terraform Query Templates

### 1. Task Success Rate SLO Burn Rate Queries

#### Fast Burn (1h & 5m Windows)

```promql
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[1h])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[1h])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[1h])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 14.4
)
```

#### Slow Burn (3d & 6h Windows)
> [!WARNING]
> Lookback windows >25h (like `[3d]`) require **omitting `duration`** in HCL.

```promql
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[6h])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[6h])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[6h])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[3d])) or vector(0))
  /
  (
    (sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[3d])) or vector(0))
    +
    (sum(rate(pubsub_googleapis_com:subscription_nack_requests{subscription_id="[SUBSCRIPTION_ID]"}[3d])) or vector(0))
    + 0.001
  )
  > (1 - [SLO_TARGET]) * 1.0
)
```

### 2. Queue Backlog Drain Time (ETD)
Monitors estimated queue drain processing time in seconds.
> [!IMPORTANT]
> PromQL conditions for ETD MUST specify `duration = "300s"` (5-minute retest buffer) in HCL. This buffer absorbs temporary ETD spikes caused by autoscaler scale-up lag during sudden bursty traffic.

#### PromQL Query

```promql
(
  (sum(pubsub_googleapis_com:subscription_num_undelivered_messages{subscription_id="[SUBSCRIPTION_ID]"}) or vector(0))
  /
  clamp_min((sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="[SUBSCRIPTION_ID]"}[5m])) or vector(0)), 0.05)
) > [MAX_DRAIN_TIME_SECONDS]
```

#### Terraform Snippet (ETD Alert Policy)

```hcl
variable "worker_pools_etd" {
  description = "Map of worker pools to subscription IDs and maximum drain time SLAs (in seconds)"
  type = map(object({
    subscription_id       = string
    max_drain_time_second = number
  }))
  default = {
    "order-processor" = {
      subscription_id       = "order-topic-sub"
      max_drain_time_second = 1800 # 30 minutes SLA
    }
  }
}

variable "retest_duration_buffer" {
  description = "Retest duration buffer for lookbacks <= 25h"
  type        = string
  default     = "300s"
}

resource "google_monitoring_alert_policy" "queue_backlog_etd" {
  for_each     = var.worker_pools_etd
  project      = var.scoping_project_id
  display_name = "[Worker Pool] Queue Backlog Estimated Time to Drain (ETD) Exceeded - ${each.key}"
  combiner     = "OR"

  conditions {
    display_name = "Estimated drain time on ${each.value.subscription_id} exceeds ${each.value.max_drain_time_second}s"
    condition_prometheus_query_language {
      query = <<-EOT
        (
          (sum(pubsub_googleapis_com:subscription_num_undelivered_messages{subscription_id="${each.value.subscription_id}"}) or vector(0))
          /
          clamp_min((sum(rate(pubsub_googleapis_com:subscription_ack_message_count{subscription_id="${each.value.subscription_id}"}[5m])) or vector(0)), 0.05)
        ) > ${each.value.max_drain_time_second}
      EOT
      duration = var.retest_duration_buffer # 5m retest buffer to absorb autoscaling scale-up lag
    }
  }

  user_labels = {
    severity                    = "warning"
    worker                      = each.key
    tier                        = "saturation"
    "created-with-google-skill" = "cloud-run-alert-configuration"
  }

  alert_strategy { auto_close = "604800s" }
  notification_channels = var.notification_channels
}
```

### 3. Oldest Unacked Message Age

```promql
(
  (pubsub_googleapis_com:subscription_oldest_unacked_message_age{subscription_id="[SUBSCRIPTION_ID]"} or vector(0))
) > [AGE_THRESHOLD_SECONDS]
```

### 4. Health Probe Success Rate SLO Burn Rate Queries

#### Fast Burn (1h & 5m Windows)

```promql
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[5m])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[5m]))
  > (1 - [SLO_TARGET]) * 14.4
)
and
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[1h])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[1h]))
  > (1 - [SLO_TARGET]) * 14.4
)
```

#### Slow Burn (3d & 6h Windows)
> [!WARNING]
> Lookback windows >25h (like `[3d]`) require **omitting `duration`** in HCL.

```promql
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[6h])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[6h]))
  > (1 - [SLO_TARGET]) * 1.0
)
and
(
  (sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]", is_healthy="false"}[3d])) or vector(0))
  /
  sum(rate(run_googleapis_com:container_completed_probe_attempt_count{monitored_resource="cloud_run_worker_pool", worker_pool_name="[WORKER_POOL_NAME]"}[3d]))
  > (1 - [SLO_TARGET]) * 1.0
)
```

---

## Telemetry Data Sources Reference

<!-- mdformat off -->
| Signal Indicator | Native Metric | SRE Strategy |
| :--- | :--- | :--- |
| **Task Availability** | `pubsub.googleapis.com/subscription/nack_requests` | **SLO Skill (`google-cloud-slo-alert-configuration`)**: Fast Burn (1h/5m) & Slow Burn (3d/6h) |
| **Process Health SLO** | `run.googleapis.com/container/completed_probe_attempt_count` | **SLO Skill (`google-cloud-slo-alert-configuration`)**: Probe Failure Ratio (`is_healthy="false"`) Fast & Slow Burn |
| **Queue Backlog ETD** | `pubsub.googleapis.com/subscription/num_undelivered_messages` & `pubsub.googleapis.com/subscription/ack_message_count` | **Estimated Time to Drain (ETD)**: Drain time > SLA threshold with `duration = "300s"` retest buffer |
| **Message Age** | `pubsub.googleapis.com/subscription/oldest_unacked_message_age` | **Threshold Alert**: Message age > SLA limit (e.g., 30m) |
<!-- mdformat on -->

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE