Alert policies built on router.googleapis.com/bgp/session_up catch hard outages, yet two common hybrid routing failures slip right past them. bgp/session_up is sampled once every 60 seconds and can take up to 180 seconds to appear in Cloud Monitoring (see Google Cloud metrics: P through Z | Cloud Monitoring). A BGP session that drops and recovers within 15 to 20 seconds between samples looks completely flat (1 -> 1 -> 1). Likewise, if an on-premises router withdraws a critical prefix while keeping BGP Established, bgp/session_up never moves.
You can close both gaps by querying live router state directly from Method: routers.getRouterStatus | Compute Engine. Each response includes per-peer uptimeSeconds, BGP state, optional BFD diagnostics, and active learned routes. Comparing uptimeSeconds across polls catches fast resets even after recovery, and checking learned routes against expected prefixes catches silent withdrawals right away.
What get-status exposes beyond Cloud Monitoring
Running gcloud compute routers get-status | Google Cloud SDK with --format=json returns two key arrays: result.bgpPeerStatus[] and result.bestRoutesForRouter[]. Here is a trimmed peer entry from a Cloud Interconnect VLAN attachment with BFD enabled:
{
"bfdStatus": {
"bfdSessionInitializationMode": "ACTIVE",
"localDiagnostic": "NO_DIAGNOSTIC",
"localState": "UP",
"negotiatedLocalControlTxIntervalMs": 1000,
"uptimeMs": "409548112"
},
"enableIpv4": true,
"enableIpv6": false,
"ipAddress": "169.254.10.1",
"md5AuthEnabled": false,
"name": "peer-vlan-0",
"numLearnedRoutes": 2,
"peerIpAddress": "169.254.10.2",
"state": "Established",
"status": "UP",
"uptime": "4 days, 17 hours, 45 minutes, 48 seconds",
"uptimeSeconds": "409548"
}
Two details matter here. First, uptimeSeconds (and bfdStatus.uptimeMs) comes back as a JSON string, so cast it with tonumber in jq. When uptimeSeconds drops below the prior poll's value, the session bounced in between polls - even if state already reads "Established". Second, bfdStatus.localState and bfdStatus.localDiagnostic help separate fault layers. For example, BGP stuck in "Connect" while BFD stays "UP" points to a TCP 179 filter or config mismatch rather than an underlay drop.
For prefix checks, result.bestRoutesForRouter[] lists the best BGP routes learned by this Cloud Router along with each route's destRange and routeStatus:
"bestRoutesForRouter": [
{
"asPaths": [
{
"asLists": [
65002
],
"pathSegmentType": "AS_SEQUENCE"
}
],
"creationTimestamp": "2026-11-21T11:03:24.015-08:00",
"destRange": "192.168.100.0/24",
"kind": "compute#route",
"network": "https://www.googleapis.com/compute/v1/projects/my-gcp-project/global/networks/vpc-a",
"nextHopIp": "169.254.10.2",
"nextHopOrigin": "INCOMPLETE",
"priority": 0,
"routeStatus": "ACTIVE",
"routeType": "BGP"
}
]
Keep bestRoutesForRouter distinct from the sibling bestRoutes array covered in View router details | Cloud Router. bestRoutesForRouter covers routes learned by this router alone, while bestRoutes shows the winning dynamic routes programmed in the region's VPC (including cross-region routes when global dynamic routing is on). Filtering bestRoutesForRouter on routeStatus == "ACTIVE" confirms that this router still holds your required prefixes and that route quotas didn't drop them.
Checking uptime regressions and active routes with gcloud and jq
This script runs gcloud compute routers get-status, compares uptimeSeconds against a small JSON state file from the previous run, and checks bestRoutesForRouter against your required prefixes. It exits with status 1 if any peer flaps, drops out of Established, disappears, or loses an expected prefix.
#!/bin/bash
set -euo pipefail
# --- Configuration (Replace with your details) ---
PROJECT="<YOUR_PROJECT_ID>"
REGION="<YOUR_REGION>"
ROUTER="<YOUR_CLOUD_ROUTER_NAME>"
EXPECTED_PREFIXES="192.168.100.0/24,192.168.101.0/24"
STATE_FILE="/tmp/cr-bgp-state.json"
PREV_STATE="{}"
if [[ -f "$STATE_FILE" ]]; then
PREV_STATE=$(cat "$STATE_FILE")
fi
STATUS_JSON=$(gcloud compute routers get-status "$ROUTER" \
--project="$PROJECT" \
--region="$REGION" \
--format=json)
# Compare peer uptimes against the previous poll and verify active learned prefixes
REPORT=$(echo "$STATUS_JSON" | jq \
--argjson prev "$PREV_STATE" \
--arg expected_csv "$EXPECTED_PREFIXES" '
($expected_csv | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(length > 0))) as $expected |
([(.result.bestRoutesForRouter // [])[] | select(.routeStatus == "ACTIVE") | .destRange] | unique) as $active |
($expected - $active) as $missing_prefixes |
(($prev | keys) - [(.result.bgpPeerStatus // [])[].name]) as $missing_peers |
[
(.result.bgpPeerStatus // [])[] |
(.uptimeSeconds // "0" | tonumber) as $cur |
($prev[.name] // null) as $last |
($last != null and $cur < $last) as $flap |
(if .bfdStatus then "\(.bfdStatus.localState // "UNKNOWN") (\(.bfdStatus.localDiagnostic // "NONE"))" else "n/a" end) as $bfd |
{
alert: (.state != "Established" or $flap),
line: (
"Peer: \(.name) | State: \(.state) | Uptime: \($cur)s"
+ (if $flap then " (reset from \($last)s)" else "" end)
+ " | Flap: \($flap) | BFD: \($bfd) | Learned: \(.numLearnedRoutes // 0)"
)
}
] as $peers |
{
has_alert: (($peers | any(.alert)) or ($missing_prefixes | length > 0) or ($missing_peers | length > 0)),
lines: (
($peers | map(.line))
+ (if ($missing_peers | length) > 0 then ["Missing peers: \($missing_peers | join(", "))"] else [] end)
+ [
if ($missing_prefixes | length) > 0 then
"Missing active prefixes: \($missing_prefixes | join(", "))"
else
"Expected prefixes active: \($expected | join(", "))"
end
]
)
}
')
# Persist current peer uptimes for the next poll
echo "$STATUS_JSON" | jq '
[(.result.bgpPeerStatus // [])[] | {(.name): (.uptimeSeconds // "0" | tonumber)}] | add // {}
' > "$STATE_FILE"
echo "$REPORT" | jq -r '.lines[]'
if [[ $(echo "$REPORT" | jq -r '.has_alert') == "true" ]]; then
exit 1
fi
On the first run against cr-us-south1, the script saves baseline uptimes and confirms both prefixes are active:
~ bash cr-bgp-health-check.sh
Peer: peer-vlan-0 | State: Established | Uptime: 409548s | Flap: false | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Peer: peer-vlan-1 | State: Established | Uptime: 812925s | Flap: false | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Expected prefixes active: 192.168.100.0/24, 192.168.101.0/24
On a later run after peer-vlan-0 bounces for 15 seconds and recovers - while 192.168.102.0/24 is withdrawn upstream - both sessions still read Established. The script catches both issues and exits 1:
~ bash cr-bgp-health-check.sh
Peer: peer-vlan-0 | State: Established | Uptime: 14s (reset from 409548s) | Flap: true | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Peer: peer-vlan-1 | State: Established | Uptime: 812985s | Flap: false | BFD: UP (NO_DIAGNOSTIC) | Learned: 2
Missing active prefixes: 192.168.102.0/24
Things to watch out for in production
- Cloud Router maintenance restarts: Google Cloud periodically restarts Cloud Router software tasks, which resets
uptimeSecondswhile BGP Graceful Restart keeps forwarding traffic. Check Cloud Logging (resource.type="gce_router") for"Router task de-activated"and"Router task activated"events before paging on a single short reset (see View logs and metrics | Cloud Router). - Disabled and deleted peers: Deleting a peer makes
bgp/session_upstop emitting points instead of writing0, and--no-enabledemits0just like an outage.get-statusshowsstate: "Disabled"(documented in BGP session states | Cloud Router), and diffing against saved peer keys catches deletions on the next poll. - Active-passive peers on one router: When two peers on the same router advertise the same prefix with different MEDs or AS paths,
bestRoutesForRouteronly keeps the winning path. Watch per-peernumLearnedRoutesalongsidebestRoutesForRouterif you also want to confirm a standby peer is still sending routes. - BFD support: Cloud Router BFD works only on Dedicated Interconnect and Partner Interconnect VLAN attachments - not HA VPN or Router appliance peers (see Bidirectional Forwarding Detection (BFD) overview | Cloud Router). The script defaults to
n/awhenbfdStatusisn't present.
You can run this check on a timer in Cloud Run Jobs or export the same routers.getRouterStatus fields as custom Cloud Monitoring metrics. It's an easy way to spot fast flaps and silent route drops during cutovers or maintenance windows.
Top comments (3)
This is the same trap I hit on the floor with a flapping fiber link: at the moment you check it, the session reads Established and the ticket gets closed as no fault found. What caught it for us was the same idea as your uptimeSeconds check — comparing the session uptime and the interface error counters against the previous check, instead of trusting a single snapshot. A link that bounced 15 seconds ago and recovered looks healthy right now, and the only evidence left is the counter that moved.
One edge case for the uptime comparison: a reset does not always make the next counter smaller. Suppose polls are 60 seconds apart and report 5s, then 20s. A second reset 40 seconds after the first poll produces exactly that pair, but
20 < 5is false, so$flapstays false.It would help to persist the sample time alongside each uptime and compare the uptime increase with elapsed time, allowing for integer rounding and request latency. Without a reset, the second uptime should be about 65s in this example; 20s indicates a changed session start time. That pair would make a useful regression test alongside the large-counter-to-small-counter example.
The API defines
uptimeSecondsas the time the session has been up, which makes this check possible even when both sampled states areEstablished.You're right that
cur < lastalone misses back-to-back resets when the second counter is larger (like5s -> 20sover 60 seconds). Saving the poll timestamp and previous peer state alongside eachuptimeSecondsvalue closes that gap.Comparing
($last.uptime + $elapsed) - $curagainst a 5-second tolerance catches the shifted start time while absorbing integer rounding and API latency. Gating onEstablished -> Establishedalso avoids false flap flags when a peer stays down or cleanly recovers:With that check in place, a
5s -> 20spair across a 60-second interval flagsFlap: trueagainstexpected ~65s. Thanks for calling out that edge case.