Cloud

GCP Billing Kill Switch: Budget to Pub/Sub to Cloud Run, Tested

A Google Cloud budget watches your spend. It does not stop it. When a Gemini loop runs away at 2 a.m., the budget email shows up after the money is gone, and nothing in an alerts-only budget will switch the API off for you. A GCP billing kill switch closes that gap: the budget publishes its numbers to Pub/Sub, a small function reads them, and the function turns off the service or the whole project’s billing when spend crosses the line.

Original content from computingforgeeks.com - post 203898

We ran Mode 1, disabling the Vertex AI API, on a Google Cloud project in December 2026 with Gemini 3.1 Pro doing the spending. The Vertex budget’s costAmount stayed at 0.0 all run, so the real-cost trigger never fired and we tripped the switch with an over-budget message of our own. Mode 2, detaching billing, is Google’s documented call, permission-checked but not fired on the shared project. Payloads, logs and timings below come from that run.

You’ll get the budget, the real payload, a least-privilege function with two kill modes, the recovery steps, spend cap budgets, and what quota overrides did as a brake.

Why a budget cannot stop a bill

An alerts-only budget is a reporting object. Google’s own budget documentation says that setting one does not cap usage or spending, and the programmatic notifications page warns that the first Pub/Sub message can take several hours to arrive. Cost data is the slow part, because Cloud Billing has to meter usage, price it and attribute it to the project before the budget sees a single cent.

Our run made the lag concrete. The first Gemini 3.1 Pro call went out at 21:45 UTC, and by 22:18 we had pushed about $1.87 of list-price output and thinking tokens through it across 32 calls. The Vertex-only budget kept publishing "costAmount": 0.0 the whole time, including a fresh message at 22:18. A $0.20 budget sat at zero while spend ran past nine times its amount, so a kill switch wired to it would not have fired. The function was fine; the number it reads had not caught up.

That lag is the whole story behind the bill shock threads. On 4 December 2026 a Hacker News submission titled “Google sent me to collections: GCP’s 20-min AI alert fired 10h late ($76K bill)” reached the front page with more than 500 points. The poster reports that a 20-minute budget alert fired about ten hours after the spend started; we can’t verify the bill or the account details, and the linked Reddit post was not readable from our side. The pattern in the comments is consistent, though: alerts tell you what already happened, and one commenter reported a $25k Vertex overage of their own.

Native spend caps and the kill switch

Google now ships a real cap for a short list of services. A spend cap budget pauses new usage of one service in one project when the gross, estimated cost passes the amount, and it uses estimated list-price cost so it is designed to act faster than an alerts-only budget. The catch is scope: Gemini API, Vertex AI (renamed Gemini Enterprise Agent Platform on the billing pages), Cloud Run and Cloud Run functions are the only eligible services, one project and one service per budget.

Everything else, from GKE and Compute Engine to BigQuery, still needs the Pub/Sub route, so in practice you run both: a spend cap on each eligible AI service as the first brake, and a kill switch as the backstop for the rest of the project. The table compares the four brakes we tried.

BrakeStopsTriggerUndo
Spend cap budgetNew calls to one eligible service in one projectEstimated gross cost over the amountLift the cap, or wait for the 1st of the month
Kill switch, Mode 1One API, plus services that depend on itPub/Sub budget message over the amountgcloud services enable
Kill switch, Mode 2Every paid service in the project, free tier includedPub/Sub budget message over the amountRelink billing; resources may take up to 24 hours
Quota overrideNothing in our lab: the request limit was refused and the token limit was accepted but not enforcedPer-minute counterDelete the override

Only Mode 1 stopped real traffic in our run. Treat the quota override as unproven on Gemini 3.1 Pro: six calls produced 3,904 output tokens in 39 seconds against a 2,000 per minute override, all HTTP 200. None of these are instant. The spend cap documentation says plainly that enforcement is not instantaneous and that overages accrued during the delay are billed as normal, so set the amount below the number you actually can’t afford.

The kill switch architecture

Two paths watch the same project, so a failure in one still leaves the other. The spend cap budget reads estimated cost and pauses Vertex AI directly. The alerts-only budget publishes JSON to a Pub/Sub topic several times a day; Eventarc delivers each message to a Cloud Run function, which calls the Service Usage API (Mode 1) or the Cloud Billing API (Mode 2).

GCP billing kill switch architecture diagram: spend cap budget pausing Vertex AI and an alerts-only budget publishing to Pub/Sub, a Cloud Run function and the Service Usage or Cloud Billing API

The function runs as its own service account with one role. That keeps the blast radius small: a bug in the function can disable an API, and that is all it can do unless you deliberately hand it billing rights for Mode 2.

Project variables and APIs

Set three values once. The billing account ID is on the Billing overview page in the console, and the project must already be linked to it.

export PROJECT_ID="your-gcp-project-id"
export BILLING_ACCOUNT="012345-6789AB-CDEF01"
export REGION="us-central1"
gcloud config set project "${PROJECT_ID}"

The function and its trigger need a handful of APIs. Cloud Build and Artifact Registry are only there because Cloud Run functions builds your source into a container image on deploy.

gcloud services enable billingbudgets.googleapis.com cloudbilling.googleapis.com \
  pubsub.googleapis.com cloudfunctions.googleapis.com run.googleapis.com \
  eventarc.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com

The identity we used was a project Owner with no role on the billing account. That turned out to matter: you can create a budget scoped to your own project without billing account rights, but you cannot list the account’s budgets, which we’ll come back to in troubleshooting.

The budget and its Pub/Sub topic

Create the topic first, since the budget refuses a topic that does not exist. The budget below covers only Vertex AI and the Gemini API in this project, excludes credits so free-trial money doesn’t hide real spend, and sets thresholds at 50% and 100% of 20 cents.

gcloud pubsub topics create billing-kill-switch

gcloud billing budgets create --billing-account="${BILLING_ACCOUNT}" \
  --display-name="vertex-kill-switch" \
  --budget-amount=0.200000000USD \
  --filter-projects="projects/${PROJECT_ID}" \
  --filter-services=services/C7E2-9256-1C43,services/AEFD-7695-64FA \
  --credit-types-treatment=exclude-all-credits \
  --threshold-rule=percent=0.5 --threshold-rule=percent=1.0 \
  --notifications-rule-pubsub-topic="projects/${PROJECT_ID}/topics/billing-kill-switch"

That odd-looking 0.200000000USD is deliberate. Our first attempt used --budget-amount=0.20USD, and the describe output showed a budget of 20 nanos, a fraction of a cent. The flag parses everything after the decimal point as raw nanos, so 0.2USD becomes 2 nanos and only a nine-digit fraction lands where you expect.

gcloud billing budgets describe showing a 0.20USD budget stored as 20 nanos, then fixed with 0.200000000USD

Whole-dollar budgets such as 500USD are unaffected, so most production budgets never hit this. Small test budgets do, and a budget of 20 nanos crosses 100% on the first cent of spend, which makes a kill switch fire long before you meant it to. Always read the stored amount back with gcloud billing budgets describe.

The notification payload, field by field

The first message for our Vertex budget arrived at 21:56:43 UTC, about 14 minutes after we created the budget. The function logged the decoded body and the message attributes, so this is exactly what your code receives.

First GCP budget Pub/Sub notification payload logged by the kill switch function with costAmount 0

Notice what’s missing. There is no alertThresholdExceeded key in that first message because cost was still zero, so code that reads the key without a default will crash on the most common message you’ll get. Three minutes later the all-project budget we had created alongside it sent a message that did carry the key, with the month’s earlier spend on the shared project already above its $1 amount.

GCP budget payload with alertThresholdExceeded 1 and the kill switch function ignoring the other budget by name

Our function ignored that one by name, which is the right behaviour when several budgets share one topic. Here is what each field means and how the code should treat it.

FieldExampleHow to use it
budgetDisplayNamevertex-kill-switchFilter on it when one topic serves several budgets
costAmount7.29Month-to-date cost as billing currently sees it; compare this to the budget
budgetAmount0.2The configured amount, already converted from nanos
alertThresholdExceeded1.0Highest threshold crossed; absent until one is crossed
costIntervalStart2026-12-01T08:00:00ZStart of the period in Pacific time; it changes on the 1st, so reset any state then
budgetAmountTypeSPECIFIED_AMOUNTLAST_MONTH_COST when the budget tracks last month’s spend, LAST_PERIODS_COST for quarterly or yearly
currencyCodeUSDThe billing account’s currency
attribute budgetIdb6ff9870-…Stable ID, safer than the display name for routing

Google documents the delivery as at least once and possibly out of order, with messages several times a day even when nothing changed. Treat every message as a fresh reading of costAmount against budgetAmount, and make the kill action idempotent so a duplicate is harmless.

A least-privilege function

Give the function its own service account and only the role Mode 1 needs. Service Usage Admin can enable and disable APIs, and it has no billing permissions at all, which we confirmed later with a permission test.

gcloud iam service-accounts create kill-switch --display-name="Billing kill switch"

gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
  --member="serviceAccount:kill-switch@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role=roles/serviceusage.serviceUsageAdmin --condition=None

Make a kill-switch working directory with two files and cd into it. The function code goes in main.py; open it with vim main.py and paste the version below, which is the exact file we deployed.

import base64
import json
import os

import functions_framework
import google.auth
from google.auth.transport.requests import AuthorizedSession

PROJECT_ID = os.environ["TARGET_PROJECT"]
MODE = os.environ.get("KILL_MODE", "disable_api")
SERVICE = os.environ.get("KILL_SERVICE", "aiplatform.googleapis.com")
BUDGET_NAME = os.environ.get("BUDGET_NAME", "")

credentials, _ = google.auth.default(
    scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
session = AuthorizedSession(credentials)


def disable_service():
    url = (
        f"https://serviceusage.googleapis.com/v1/projects/{PROJECT_ID}"
        f"/services/{SERVICE}:disable"
    )
    r = session.post(url, json={"disableDependentServices": True})
    print(json.dumps({"action": "disable_api", "service": SERVICE,
                      "status": r.status_code, "response": r.json()}))


def detach_billing():
    url = f"https://cloudbilling.googleapis.com/v1/projects/{PROJECT_ID}/billingInfo"
    r = session.put(url, json={"billingAccountName": ""})
    print(json.dumps({"action": "detach_billing",
                      "status": r.status_code, "response": r.json()}))


@functions_framework.cloud_event
def kill_switch(cloud_event):
    msg = cloud_event.data["message"]
    data = json.loads(base64.b64decode(msg["data"]).decode("utf-8"))
    attrs = msg.get("attributes", {})
    print(json.dumps({"received": data, "attributes": attrs,
                      "publishTime": msg.get("publishTime")}))

    # One topic can carry many budgets: act only on the one we were built for.
    if BUDGET_NAME and data.get("budgetDisplayName") != BUDGET_NAME:
        print(f"ignoring budget {data.get('budgetDisplayName')!r}")
        return

    cost = data["costAmount"]
    budget = data["budgetAmount"]
    if cost <= budget:
        print(f"under budget: {cost} <= {budget}, no action")
        return

    print(f"over budget: {cost} > {budget}, running {MODE}")
    if MODE == "detach_billing":
        detach_billing()
    else:
        disable_service()

The function compares cost with budget itself instead of trusting alertThresholdExceeded, so it still fires if a threshold message is lost or arrives out of order. Pin the dependencies loosely in requirements.txt:

functions-framework==3.*
google-auth==2.*
requests==2.*

Deploy it as a second-generation function on the topic. Using the same service account for the trigger and the runtime keeps the identity count at one, and a single instance is plenty for a handful of messages a day.

gcloud functions deploy billing-kill-switch --gen2 --region="${REGION}" \
  --runtime=python313 --source=. --entry-point=kill_switch \
  --trigger-topic=billing-kill-switch \
  --service-account="kill-switch@${PROJECT_ID}.iam.gserviceaccount.com" \
  --trigger-service-account="kill-switch@${PROJECT_ID}.iam.gserviceaccount.com" \
  --set-env-vars="TARGET_PROJECT=${PROJECT_ID},KILL_MODE=disable_api,KILL_SERVICE=aiplatform.googleapis.com,BUDGET_NAME=vertex-kill-switch" \
  --max-instances=1

The trigger’s identity also needs permission to invoke the underlying Cloud Run service, or Eventarc delivers nothing and the function log stays empty:

gcloud run services add-iam-policy-binding billing-kill-switch --region="${REGION}" \
  --member="serviceAccount:kill-switch@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role=roles/run.invoker

Check the deployed state before trusting it. The fields that matter are the topic, the runtime identity, the environment and the retry policy.

gcloud functions describe output for the billing kill switch Cloud Run function with Pub/Sub trigger and env vars

RETRY_POLICY_DO_NOT_RETRY is the default for these triggers and it’s what you want here. The budget sends a fresh reading several times a day anyway, so a failed run is retried by the next message instead of by a tight loop hammering the Service Usage API.

Mode 1: switching off the Vertex AI API

Mode 1 disables one API with disableDependentServices set, so anything built on top of Vertex AI goes down with it. It’s the mode we’d reach for first: billing stays attached, Cloud Storage buckets and databases keep running, and the undo is one command.

Real cost had not reached the budget yet, so we proved the path the way you should test it in production: publish an over-budget message to the topic yourself. The function cannot tell a hand-published message from one the budget sends, so this exercises the function and the API disable exactly as a real alert would. It does not prove the billing side: the Vertex budget never sent a real over-budget message, and the only real ones came from the all-project budget ($7.29, then $7.33, against $1), which the function ignored by name, as designed.

gcloud pubsub topics publish billing-kill-switch \
  --attribute=budgetId=b6ff9870-d08e-437b-bcd4-e51280320fe9,schemaVersion=1.0 \
  --message='{"budgetDisplayName":"vertex-kill-switch","alertThresholdExceeded":1.0,"costAmount":0.27,"costIntervalStart":"2026-12-01T08:00:00Z","budgetAmount":0.2,"budgetAmountType":"SPECIFIED_AMOUNT","currencyCode":"USD"}'

Swap in your own budget ID from the create output. Pub/Sub stamped the message 22:23:04, the function logged “over budget” two seconds later, and the Service Usage API accepted the disable at 22:23:07. A probe loop calling Gemini Flash-Lite once a minute tells the rest of the story:

Kill switch Cloud Run function disabling the Vertex AI API after an over-budget Pub/Sub message, then generateContent returning 403 SERVICE_DISABLED

Note the 22:23:21 call still returned 200, fourteen seconds after the disable. Propagation took between 14 and 76 seconds, and the next call got 403 PERMISSION_DENIED with reason SERVICE_DISABLED. That error is what your application sees, so make sure its retry logic doesn’t treat it as transient and hammer a dead endpoint. Anything already billed stays billed: the brake stops new calls, it doesn’t claw back the spend that tripped it.

Mode 2: detaching billing from the project

Mode 2 is the nuclear option. Setting billingAccountName to an empty string unlinks the project from its billing account, and Google’s documentation is blunt about the result: every paid service stops, free-tier usage stops with it, and some resources may be removed and become unrecoverable. A database you built with something like our Cloud SQL instance on Terraform walkthrough is exactly what you don’t want in a project that can lose its billing account. Run Mode 2 only on a project whose data lives somewhere else.

The function’s service account can’t do it with the role we gave it. Unlinking needs resourcemanager.projects.deleteBillingAssignment on the project, which comes with Project Billing Manager or Owner. We asked IAM which of the relevant permissions the kill-switch identity actually holds:

testIamPermissions as the kill switch service account returns only serviceusage.services.disable, no billing permissions

Only serviceusage.services.disable came back, which is the least-privilege design working as intended. To arm Mode 2 you grant the extra role and flip the environment variable. Run the redeploy from the kill-switch directory, because gcloud functions deploy uploads the current directory as the source:

gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
  --member="serviceAccount:kill-switch@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role=roles/billing.projectManager --condition=None

gcloud functions deploy billing-kill-switch --gen2 --region="${REGION}" \
  --update-env-vars=KILL_MODE=detach_billing

We did not let Mode 2 fire. The only project in our lab is shared with other work, and detaching it would have stopped everything else running there, so the detach path above is Google’s documented call with permissions checked rather than an unlink we watched happen. Three constraints from the documentation shape how you arm it:

  • Locked projects: a project whose billing link is locked cannot be unlinked until an admin unlocks it, so the function’s call fails and spend carries on. Active or pending committed use discounts block the unlink the same way.
  • One-way door: relinking needs billing.resourceAssociations.create on the billing account, which the function never has, so recovery always goes through a human with billing rights.
  • Free tier included: the documentation says services stop in an unlinked project, free tier included, and that covers the Pub/Sub topic and Cloud Run function the kill switch runs on.

That last point is why Mode 2 belongs on a dedicated project. It stops the bill completely, but it also stops every tool you would use to investigate what went wrong.

A spend cap budget on Vertex AI

The native cap sits in front of the kill switch for the services it covers. We created it through the Budget API, which is strict about shape: one project, one service ID, a monthly period, credits excluded, and thresholds of exactly 0.5, 0.8 and 1.0 with project-level recipients switched on, and the documentation requires every one of those. Save the body as spend-cap.json:

{
  "displayName": "vertex-spend-cap",
  "budgetFilter": {
    "projects": ["projects/your-gcp-project-id"],
    "services": ["services/C7E2-9256-1C43"],
    "creditTypesTreatment": "EXCLUDE_ALL_CREDITS",
    "calendarPeriod": "MONTH"
  },
  "amount": {"specifiedAmount": {"units": "1", "nanos": 0}},
  "thresholdRules": [{"thresholdPercent": 0.5}, {"thresholdPercent": 0.8}, {"thresholdPercent": 1.0}],
  "notificationsRule": {"enableProjectLevelRecipients": true},
  "spendCap": {"inputState": "CONFIGURED"}
}

C7E2-9256-1C43 is the Vertex AI service ID; use AEFD-7695-64FA for the Gemini API, and a second budget if you call both. POST it to the billing account with your project as the quota project:

curl -s -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "x-goog-user-project: ${PROJECT_ID}" -H "Content-Type: application/json" \
  -d @spend-cap.json \
  "https://billingbudgets.googleapis.com/v1/billingAccounts/${BILLING_ACCOUNT}/budgets"

The response echoes the budget with its ID and a read-only state. Keep the ID as CAP_BUDGET_ID; you need it to lift the cap later.

  "name": "billingAccounts/012345-6789AB-CDEF01/budgets/8ee7da84-7c74-4624-96c8-ee569109e662",
  "displayName": "vertex-spend-cap",
...
  "spendCap": {
    "outputState": "CONFIGURED"
  }

CONFIGURED means armed. When the cap trips, outputState changes to ENFORCED and new calls to the service are paused. Ours never got there: 32 minutes after creation, with about $1.90 of captured Gemini 3.1 Pro calls on the project, a fresh GET still returned CONFIGURED. The estimated cost the cap reads was lagging just like the budget’s, so treat the cap amount as a point the bill will pass, not where it stops.

Turning things back on

Each brake has its own undo, and they recover at different speeds. Plan for that before you need it, because the person fixing it at night will want the command, not the theory.

Mode 1 is the quick one, but disarm before you re-enable. costAmount is month-to-date, so it never drops below the budget again until the 1st, and the next message (about 20 minutes apart in our run) would switch the API off again. Raise the amount once you know what spent the money:

gcloud billing budgets update "${BUDGET_ID}" --billing-account="${BILLING_ACCOUNT}" \
  --budget-amount=50USD

BUDGET_ID is the ID the budget create printed. Mind the nanos gotcha from earlier: cents need all nine decimal places, while whole dollars parse cleanly, and our update to 50USD came back as units: '50' with no nanos. The switch stays disarmed at the new amount until spend passes it, so lower it again on the 1st. With the switch disarmed, turn the API back on:

gcloud services enable aiplatform.googleapis.com

In our run the enable finished in under three seconds and the next probe call, about 35 seconds after the enable command ran, returned 200:

gcloud services enable aiplatform.googleapis.com finishing in under 3 seconds and Gemini calls returning 200 again within a minute

Disabling with disableDependentServices also took down any API that depends on Vertex AI, and enable only brings back the one you name. List what you had before the incident (gcloud services list --enabled belongs in your runbook) and re-enable each dependent API too.

For Mode 2, per Google’s documentation, relinking takes rights on both sides: billing.resourceAssociations.create on the billing account (Billing Account User) and resourcemanager.projects.createBillingAssignment on the project (Project Billing Manager or Owner). Someone holding both runs:

gcloud billing projects link "${PROJECT_ID}" --billing-account="${BILLING_ACCOUNT}"

Google’s documentation says services can take up to 24 hours to come back after relinking, and resources removed while the project had no billing account are not restored. A spend cap is lifted with a PATCH that sets spendCap.inputState to AWAITING_NEXT_PERIOD; recovery can take up to an hour, and the cap won’t trigger again that month unless you raise the amount and set it back to CONFIGURED.

curl -s -X PATCH -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "x-goog-user-project: ${PROJECT_ID}" -H "Content-Type: application/json" \
  -d '{"spendCap":{"inputState":"AWAITING_NEXT_PERIOD"}}' \
  "https://billingbudgets.googleapis.com/v1/billingAccounts/${BILLING_ACCOUNT}/budgets/${CAP_BUDGET_ID}?updateMask=spendCap.inputState"

An enforced spend cap budget cannot be edited or deleted until it is lifted, so this PATCH also comes first when you want to remove the budget altogether.

Per-minute quota caps as a faster brake

Quotas act on every request, so a low per-minute limit looks like the perfect brake for a runaway Gemini loop. It caps rate, not dollars, but a rate cap still bounds how fast a bill can grow. On our project the result was less useful than that sounds.

Gemini 3.x models on the global endpoint run on a shared Standard pay-as-you-go pool with no per-model request bucket. Asking for a request-per-minute override of 2 on Gemini 3.1 Pro was refused outright:

gcloud alpha services quota update failing with consumer override value can only be set between 0 to 0 for Gemini 3.1 Pro

The output-token metric did accept an override, but only with --force, because cutting an unlimited quota to 2,000 tokens a minute trips Service Usage’s 10% safety check. The consumer quota API then reported an effective limit of 2,000 for that model.

gcloud alpha services quota update --service=aiplatform.googleapis.com \
  --consumer="projects/${PROJECT_ID}" \
  --metric=aiplatform.googleapis.com/global_generate_content_output_tokens_per_minute_per_base_model \
  --unit='1/min/{project}/{base_model}' \
  --dimensions=base_model=gemini-3.1-pro-preview --value=2000 --force

Then we tested whether it bites. Six Gemini 3.1 Pro calls, started two seconds apart, 24 minutes after the override went in:

Vertex AI output token per minute quota override of 2000 accepted with force while six parallel Gemini 3.1 Pro calls still return HTTP 200

All six returned 200, with 3,904 visible output tokens inside 39 seconds, nearly double the 2,000-per-minute limit, before counting thinking tokens. The same burst six minutes after the override gave the same result. On this project and this model, the override was accepted, reported as effective, and not enforced. We can’t tell you whether that’s propagation, the shared pay-as-you-go pool ignoring per-project overrides, or a preview model quirk; what we can tell you is that you should not rely on a token quota as your brake until you have watched it return a 429 on your own project. We deleted the override afterwards.

gcloud alpha services quota delete --service=aiplatform.googleapis.com \
  --consumer="projects/${PROJECT_ID}" \
  --metric=aiplatform.googleapis.com/global_generate_content_output_tokens_per_minute_per_base_model \
  --unit='1/min/{project}/{base_model}' --override-id="${OVERRIDE_ID}" --force

The override ID is the last path segment of consumerOverride.name in gcloud alpha services quota list output. On the request side, Gemini 3.1 Pro on the global endpoint gave us nothing to set at all, which leaves the spend cap and the kill switch as the brakes that worked.

The measured timeline

All times are UTC on 4 December 2026. Spend came from Gemini 3.1 Pro calls on the global endpoint, in two shapes: long answers of 4,500 to 6,600 output tokens plus 1,600 to 2,300 thinking tokens, and short quota probes of about 750 to 830 output plus 1,000 to 1,700 thinking. Thinking bills as output at $12 per million.

Time (UTC)EventElapsed
21:43:08Alerts-only budget vertex-kill-switch created0
21:45:11First Gemini 3.1 Pro call billed2 min
21:46:22Kill switch function instance passes its startup probe3 min
21:53:53Spend cap budget ($1, Vertex AI) created11 min
21:56:43First Pub/Sub message for the Vertex budget, cost 0.014 min
21:59:15All-project budget message, threshold 1.0, cost 7.2916 min
22:18:16Vertex budget message, cost still 0.0 after about $1.87 of calls35 min
22:23:04Test over-budget message published40 min
22:23:07Function disables aiplatform.googleapis.com3 s after message
22:24:23First 403 SERVICE_DISABLED79 s after message
22:24:48gcloud services enable runs (2.7 s)
22:25:23Calls succeed again35 s after the enable command
22:25:36Spend cap still CONFIGURED, not enforced32 min after cap

Read the table in two halves. Everything after the Pub/Sub message is fast: three seconds to act, about a minute to bite, half a minute to undo. Everything before it is slow and out of your hands, because neither the alerts-only budget nor the spend cap had registered the Vertex spend by the end of the window. Size the budget amount for that blind spot, not for the bill you hope to see.

Troubleshooting the kill switch

These are the failures we hit or tested for, with the exact messages so a search for the error lands here.

Error: “Caller does not have required permission to use project” on deploy

Our first deploy failed about 90 seconds after the service account got its role:

ERROR: (gcloud.functions.deploy) ResponseError: status=[403], code=[], message=[Validation failed for trigger projects/your-gcp-project-id/locations/us-central1/triggers/billing-kill-switch-212006: Caller does not have required permission to use project your-gcp-project-id. Grant the caller the roles/serviceusage.serviceUsageConsumer role, or a custom role with the serviceusage.services.use permission, by visiting https://console.developers.google.com/iam-admin/iam?project=your-gcp-project-id and then retry. Propagation of the new permission may take a few minutes.]

Service Usage Admin already includes serviceusage.services.use, so the grant was right and IAM just hadn’t propagated. Rerunning the same deploy a minute later worked. If it keeps failing, check that the trigger service account is the one holding the role.

Permission denied on updateProjectBillingInfo

Mode 2 returns 403 when the function’s identity lacks resourcemanager.projects.deleteBillingAssignment on the project. Grant Project Billing Manager as shown above, then confirm it took effect, since IAM propagation lags here too, with the same testIamPermissions call. If the permission is present and the call still fails, the project is probably locked to its billing account, which blocks unlinking until an admin unlocks it. Google’s pages also disagree on whether project roles alone are enough: the updateBillingInfo reference asks for project owner or billing account owner, so if the 403 persists with Project Billing Manager, add Billing Account Viewer on the account as well.

The function never triggered

Work down the chain, because each link fails in its own way and the symptom is the same silence:

  • Budget not publishing: nothing arrives on an audit subscription either. Give it time, since the first message for a new budget can take hours; ours arrived 14 minutes after creation on a project that already had billing history.
  • Trigger not invoking: messages reach the audit subscription but the function log is empty, so the trigger identity is missing roles/run.invoker on the service. On projects created on or before 8 April 2021, the Pub/Sub service agent also needs roles/iam.serviceAccountTokenCreator.
  • Function filtering it out: the log shows “ignoring budget”, which means BUDGET_NAME does not match the budget’s display name exactly.

We kept a pull subscription called kill-switch-audit on the topic for the first check:

gcloud pubsub subscriptions create kill-switch-audit --topic=billing-kill-switch --message-retention-duration=7d
gcloud pubsub subscriptions pull kill-switch-audit --auto-ack --limit=20 --format=json

Remember that --format=json prints the data field base64 encoded, so decode it before comparing it with the function’s log line.

Duplicate notifications

Duplicates are normal, not a bug. The budget republishes the same threshold crossing several times a day and Pub/Sub delivers at least once. Our all-project budget sent alertThresholdExceeded: 1.0 at 21:59 and again at 22:19, twenty minutes apart, so a function that pages someone on every message pages them twice for one crossing. The fix is in the action, not the trigger: have the function check the current state first (is the API still enabled, is billing still linked) and only act and alert when something changes.

“does not have permission to access billingAccounts instance” on budgets list

A project Owner can create and describe a budget scoped to their own project, yet gcloud billing budgets list fails because listing reads the whole billing account. Keep the budget ID from the create output and use describe with it, or ask for Billing Account Costs Manager if you need the full list.

Production hardening

The lab setup proves the mechanics. A production kill switch needs a few more decisions, and most of them are about who owns the off switch when it fires.

  • Spend caps first: put a spend cap budget on every eligible AI service in every project that calls it, set below your real pain threshold to absorb enforcement lag.
  • One project per blast radius: Mode 2 is only safe on a project that holds nothing you cannot rebuild, so isolate experimental AI work in its own project linked to the same billing account.
  • Route on budgetId: display names change; the budgetId attribute doesn’t, so match on it once you have more than one budget per topic.
  • Alert on the action: a log-based alert on the “over budget” line tells a human the brake fired, which matters more than the budget email that preceded it.
  • Test monthly: publish a fake over-budget message to the topic on a sandbox project and confirm the API goes down, since an untested kill switch is a comforting story.

The running cost is close to nothing, because the whole thing idles. A few budget messages a day sit well inside Pub/Sub’s free tier, and the function wakes up for each one and finishes in about a second. Keep the budget, topic and function in code next to the rest of your platform, the way we manage certificates in the GCP certificate inventory with Terraform and Argo CD setup, so nobody can quietly delete the kill switch in the console during a cleanup.

A Vertex kill switch only watches Vertex. Our breakdown of hidden GCP billing traps covers egress, NAT and logging, the costs this setup will never see, and on GKE Kubecost cost allocation shows which workload is spending long before a budget notices. If you call Gemini from Python, the Vertex AI Gemini streaming and tool use guide shows the client side this switch protects.

Keep reading

The Ecosystem Advantage: Building a Future-Ready Enterprise Data Resilience Strategy Backup The Ecosystem Advantage: Building a Future-Ready Enterprise Data Resilience Strategy OpenCloud vs ownCloud vs Nextcloud: Tested on Identical VMs Cloud OpenCloud vs ownCloud vs Nextcloud: Tested on Identical VMs Install Nextcloud on Ubuntu 26.04 LTS Cloud Install Nextcloud on Ubuntu 26.04 LTS Hetzner Inference API: Setup, First Call, Prices and Latency AI Hetzner Inference API: Setup, First Call, Prices and Latency AZ-204 Practice Questions with Answers, Updated for AI-200 Cloud AZ-204 Practice Questions with Answers, Updated for AI-200 Install AWS CloudFormation Helper Scripts on Linux Cloud Install AWS CloudFormation Helper Scripts on Linux

Leave a Comment

Press ESC to close