Designing Google Cloud Spending Caps Around a Four-Service Native Cap — Defense-in-Depth for the AI Agent Era
AI coding agents such as Claude Code, Codex, and agents on the Gemini Enterprise Agent Platform can now drive Google Cloud APIs without a human in the loop. If budgets are still sized around the old assumption that humans create resources in the Cloud Console and review them as they go, an agent loop, a leaked Gemini API key, or an accidental GPU VM can rack up unexpected charges in the first few days of a billing cycle, leaving a very large invoice by the time anyone notices. Before letting an AI agent operate on Google Cloud, put billing-side caps and preventive controls in place.
The catch is that Google Cloud’s commercial contracts have no single hard cap that stops an entire billing account across all services at a target dollar amount. Spend Cap Budgets reached GA in late October 2026, but their scope is Gemini API, Agent Platform (formerly Vertex AI), Cloud Run, and Cloud Run functions at a single project × single service × monthly scope. Alerts-only Budgets are notification-only and do not stop usage or billing. A practical enterprise cap therefore has to be built as defense-in-depth: Budgets, anomaly detection, Cloud Quotas, Organization Policies, IAM, Spend Cap, and billing link locks. This post walks through that design against the official behavior as of November 2026, separating production and non-production.
Alerts-only budget vs. Spend Cap budget
Google Cloud Billing has two kinds of budget, and their roles are completely different. The alerts-only budget is a notification and Pub/Sub trigger. The Spend Cap budget auto-stops new usage for the four supported services.
| Item | Alerts-only Budget | Spend Cap Budget |
|---|---|---|
| Main purpose | Cost planning, monitoring, notifications, automation trigger | Auto-stops new usage of the target service |
| On exceed | Billing and resources keep running | New requests are rejected |
| Covered services | All | Gemini API, Agent Platform, Cloud Run, Cloud Run functions |
| Scope | Billing account, organization, folder, project, service, label | 1 project × 1 service |
| Period | Monthly, quarterly, yearly, custom | Monthly (resets on the 1st) |
| Thresholds | Actual + forecast | Fixed at 50% / 80% / 100% |
| Notifications | Default recipients + Cloud Monitoring email channels (up to 5), Pub/Sub | Billing account admins / users and project owners only, not customizable |
| Switch between types | Cannot convert alerts-only into Spend Cap (recreate) | Same |
| Reseller-billed account | Supported | Not supported |
A Spend Cap Budget fires when cost crosses 100% of the budget. Some target services are evaluated on gross (pre-discount, pre-credit) estimated cost and the rest on actual, post-discount cost. Once it fires, new usage of the target service is blocked for both pay-as-you-go and CUD-covered usage. In-flight requests complete and are billed. Persistent-resource fees (Compute, Storage), subscriptions, and provisioned throughput do not stop. Recovery after a manual lift can take up to an hour, and the cap auto-releases on the 1st of the next month. The behavior is documented in Manage spend cap budgets.
Google’s own blog post Google Cloud spend caps now generally available recommends: “Start by applying strict, low-dollar spend caps to your developer sandboxes, testing clusters, and experimental AI agent playgrounds.” It is not meant to be dropped onto availability-critical production.
So no single feature gives commercial customers an absolute guarantee that the bill will stop under the target amount. Compute Engine, BigQuery, Cloud SQL, and Cloud Storage are outside the Spend Cap scope as of 2026-11-16, and their ceilings have to come from other layers.
Alerts-only Budget behavior and latency
An alerts-only Budget can scope to a whole billing account, one or more organizations / folders / projects, a specific service, or resources tagged with a specific label. Thresholds (percent-based) apply to both actual and forecasted spend. Beyond the default recipients (Billing Account Administrators and Billing Account Users), you can add up to 5 Cloud Monitoring email channels and one Pub/Sub topic. The official create, edit, or delete budgets and budget alerts page states: “Budget alert emails might prompt you to take action to control your costs, but they don’t automatically prevent the use or billing of your services when the alerts-only budget amount or threshold rules are met or exceeded.”
Operational caveats:
- Google’s default thresholds are 50% / 90% / 100% actual, but those are starting values, not recommendations. Add a 100% forecasted threshold so you can tell mid-month whether the pace will overshoot.
- Billing data has latency: detailed costs usually surface within a day, sometimes beyond 24 hours. Google explicitly recommends setting the budget below the hard tolerance.
- Monthly budgets keep tracking the prior month for the first 2 days after rollover. Even after Billing is disabled, charges incurred before the stop can surface in the transaction log up to 2 days later.
- Pub/Sub notifications arrive several times a day and are sent even without a threshold breach. Delivery is at-least-once, so duplicates and out-of-order delivery are expected.
- Custom email recipients are configured as Cloud Monitoring email channels, up to 5 per budget. The Cloud Billing Budget API reference states “A maximum of 5 email notifications are allowed” on the
monitoringNotificationChannelsfield. - Savings (discounts / credits) default to applying all of CUD, SUD, promotional credits, free tier, reseller margin, and spend-based discounts (net paid amount). To see post-expiry run rate, uncheck Promotions; to see gross consumption without any discount, create a separate budget with every Savings option off.
Given that latency, Budget alerts are not a real-time breaker. The design must assume the account is already over by the time the email arrives, with other layers holding the line.
Layered alerts
Instead of one threshold, combine five alert types.
| Alert type | Evaluated on | Recommended threshold | Scope |
|---|---|---|---|
| Budget Alerts (actual) | Cumulative actual cost | 50% (progress), 90%, 100% | All scopes |
| Forecast Alerts | End-of-month projection | 100%–120% | All scopes |
| Cost Anomaly Detection | Deviation from historical pattern | Daily automatic evaluation | Projects under the billing account |
| Early anomalies for AI workloads (Preview) | Near-real-time estimated cost for Gemini API, Agent Platform | System-defined, not user-tunable | Supported projects, 20–40 minute expected latency |
| Scheduled reports | Cost Analysis / FinOps hub | Daily, weekly, monthly | For managers and FinOps |
Send notifications to distribution lists or shared mailboxes so alerts still reach the team after people leave or change roles. When a Cloud Run function consumes Pub/Sub, judge on alertThresholdExceeded and forecastThresholdExceeded, and make the receiver idempotent against duplicate deliveries of the same threshold.
Cost Anomaly Detection is free for every customer and requires no setup, according to the GA announcement. The AI-generated thresholds can be tuned by a billing admin against monetary impact and deviation ratio. In 2026 Google added Early anomalies (Preview) for Gemini API and Agent Platform (formerly Vertex AI), using near-real-time estimated cost with a 20–40 minute expected latency. Early anomaly thresholds are system-defined and cannot be adjusted. For reseller-billed accounts, enabling anomaly detection requires contacting Cloud Billing support to turn on project-level cost visibility.
Preventive guardrails: Organization Policies, Cloud Quotas, IAM
To mitigate Budget latency at the root, apply preventive guardrails that refuse to create high-cost resources at the organization, folder, or project level.
Organization Policies
Organization Policies centrally restrict how resources can be used across the hierarchy. For cost control the most useful are:
constraints/gcp.resourceLocations: reject resource creation outside approved regions. Not retroactive to existing resources, and some services with global location are exempt.constraints/gcp.restrictServiceUsage: allowlist the services (APIs) that can be used. Production folders allow a small set; sandboxes allow more; unapproved high-cost services are denied.constraints/compute.managed.vmExternalIpAccessandconstraints/iam.managed.disableServiceAccountKeyCreation: restrict external IP assignment and service account key creation to shut off breach-driven cost blowups.- Custom org policies (up to 20 per resource type): restrict Compute Engine machine types (for example, E2 family only) and GPU attachment, GKE cluster / node pool shape, Workbench machine types at the REST CREATE and UPDATE call.
Validate new policies with Policy Simulator and dry-run mode before enforcing. If you add a conditional rule using tags, you must also attach at least one unconditional rule. None of this is retroactive: adding a deny today does not shut down existing VMs tomorrow.
Cloud Quotas
Cloud Quotas govern per-project allocation, rate, and concurrency across global / region / zone dimensions. Administrators can request a quota decrease through a quota adjustment. That turns quotas into a technical ceiling on resource volume that indirectly caps spend, even though it is not a dollar cap.
Pair this with a custom org policy against cloudquotas.googleapis.com/QuotaPreference to block unauthorized quota increase requests at the API level. The Quota adjuster feature can request automatic increases based on past usage, which may need to be disabled in environments where strict cost caps are mandatory.
Least-privilege Cloud Billing IAM
Separate Cloud Billing IAM roles by function.
| Role | Assign to | Notes |
|---|---|---|
roles/billing.admin | 2–3 finance / platform engineers | Full control over payment, exports, links, IAM. Keep the roster small. |
roles/billing.costsManager | FinOps | Manage budgets and read / export cost data. No payment permission. |
roles/billing.viewer | Accounting, audit | Read-only. |
roles/billing.user | Platform team allowed to create projects | Can link a project to a billing account. Do not hand out broadly. |
roles/billing.projectManager | Per-project | Combined with billing.user to link / unlink. |
roles/billing.projectCostsManager | Team leads | Scoped cost view and budget management for their own projects. |
Anyone holding roles/billing.user plus roles/resourcemanager.projectCreator can freely create billable projects. Do not grant this to all engineers; centralize it in a project factory workflow (Terraform or similar) that provisions the budget, labels, and mandatory org policies at the same time.
Lock production projects to their billing account
Google’s Secure the link between a project and its billing account feature puts a padlock on the link so that the project cannot be moved to a different billing account, nor can billing be disabled, until the lock is released. Locking requires billing.resourceAssociations.create on the billing account (Billing Account User or Billing Account Administrator) and resourcemanager.projects.createBillingAssignment on the project (Project Billing Manager or Project Owner), and in some cases reauthentication. A lock does not keep billing enabled if the billing account is closed or suspended for nonpayment.
Make this mandatory on production projects for two reasons:
- It blocks misconfiguration, insider actions, and automation from disabling billing (and halting every service) unless someone first unlocks the link.
- API-based billing disable cannot execute against a locked project, which closes the path where a budget-triggered script unlinks billing from production and stops every service.
Do not lock sandbox projects where automated billing disable is explicitly allowed. Availability protection and forced stop are in tension, and the balance should shift by environment.
Using Spend Cap and alerts-only together
A Spend Cap Budget cannot be produced by editing an existing alerts-only budget. You must create a new budget and choose Spend cap enforcement. The amount is a fixed Specified amount, and Savings customization is unavailable. According to the docs, some target services are evaluated on gross (pre-discount) estimated cost for fast evaluation, while the rest use actual, post-discount cost.
Recommended usage as of the October 2026 GA:
- In developer sandboxes and AI experimentation projects, apply a low-dollar Spend Cap to each of Gemini API, Agent Platform, Cloud Run, and Cloud Run functions. Google’s own blog recommends starting with developer sandboxes, testing clusters, and experimental AI agent playgrounds.
- Staging / integration environments can run a moderate Spend Cap where some service stoppage is acceptable.
- In production, if downtime would cost more than the overage, skip Spend Cap or set it well above expected spend.
- Once a Spend Cap is enforcing, the budget cannot be edited or deleted until it is lifted. After a manual lift it will not re-enforce in the same month unless you raise the cap value.
Spend Cap Budgets are managed through the existing Cloud Billing Budget API via the spendCap field. FORECASTED_SPEND thresholds and Pub/Sub topics are not supported on Spend Cap budgets. Check whether your Terraform provider version covers this field before relying on it.
Gemini API’s dual cap
Enterprise Gemini API usage runs through two cap layers.
- Per-billing-account tier limit (mandatory): the Rate limits page defines Tier 1 (active billing account linked) at USD 250 / month, Tier 2 (cumulative USD 100 paid + 3 days after first payment) at USD 2,000 / month, Tier 3 (cumulative USD 1,000 paid + 30 days) at USD 20,000–100,000+ / month, plus a 10-minute rolling spend rate limit. Hitting the tier limit stops Gemini API across every project linked to that billing account.
- Per-project cap (optional): configure it on the Spend page in Google AI Studio. There is roughly a 10-minute delay, and overages during that window are on the user. The feature is labeled Experimental and is not available for invoiced billing accounts.
If you set a cap in both AI Studio and Cloud Billing, whichever fires first wins, and either way blocks Gemini API across every platform for that project. An experimental project sharing a billing account with production risks pulling production down to its tier ceiling. Separate the billing account between production and experimentation, or apply Spend Cap from the Project Factory at provisioning time.
API key leaks and abuse
An April 2026 Google AI Developers Forum thread reported that an unrestricted Firebase browser key used for Gemini requests ran up roughly EUR 54,000 of charges in 13 hours. As of June 19, 2026, Gemini API rejects requests from unrestricted standard API keys. Starting May 28, 2026, new AI Studio keys are auth keys by default.
Standardize the following responses:
- Inventory every API key and apply API restrictions and application restrictions.
- Split Maps / Firebase keys from AI keys (ideally separate projects as well).
- Migrate from unrestricted standard keys to auth keys.
- Apply Spend Cap and AI Studio’s project cap to Gemini API projects.
- Keep the
iam.serviceAccountKeyExposureResponseorganization policy at its defaultDISABLE_KEY(do not switch it toWAIT_FOR_ABUSE) so detected leaked keys are automatically disabled. It covers service account keys and API keys bound to a service account (such as auth keys), not standard API keys that are not bound to one.
Service-specific caps (BigQuery, Cloud Run, Cloud Logging)
BigQuery and Cloud Logging are outside Spend Cap scope, and Cloud Run supports Spend Cap but also benefits from in-service controls.
BigQuery
- The on-demand pricing model exposes two custom quotas:
QueryUsagePerDay(per project, default 200 TiB / day) andQueryUsagePerUserPerDay(per user / service account, unlimited by default). Together these form the practical daily hard cap. Per-user override values are not supported. - Per-query cap: set
maximum bytes billed, and queries whose estimated scan exceeds it fail without billing. Make it mandatory for scheduled queries, BI tools, and any service account. - Note that
QueryUsagePerDaydoes not apply to Editions (slot-based pricing). Use reservations to cap Maximum slots explicitly.
Cloud Run
- Set
--max-instancesstrictly per service. For budget protection, start at 3. Cap VPC connectors too (max_instancesongoogle_vpc_access_connectorin Terraform). - The service-level change takes effect immediately. GPU configurations are capped by the per-region GPU quota.
- Combine with a Spend Cap Budget to stop new usage within a month.
Cloud Logging
- Set exclusion filters on the
_Defaultsink to trim Data Access audit logs, GKE container / pod logs, Dataflow logs, and other high-volume output. - Use the organization / folder default resource settings (
gcloud logging settings update, and similar) so new child resources inherit automatic exclusions or a disabled_Defaultsink. - Limits: up to 50 exclusions per sink (20,000 characters each), up to 10
_Defaultsink exclusions via the CreateExclusion API._Requiredsinks cannot be excluded or disabled, and exclusions do not reduceentries.writeAPI quota consumption.
Pub/Sub automation and the danger of billing disable
Automating a response to Pub/Sub budget notifications splits into a safe path and a destructive one.
Graceful automated response (recommended)
The official Control resource usage with notifications shows stopping only Compute Engine VMs while leaving Cloud Storage objects in place. In practice:
- Use labels (
auto-stop=true,env=dev) to mark stop targets explicitly and exclude production or critical resources. - Layer the stages: Slack notification at 90%, stop non-production VMs at 100%, human escalation at 120%.
- Stop resources; keep deletion out of automation.
Disabling billing is the last resort
The official Disable billing usage with notifications tutorial removes the billing link from the project and halts all resources. The docs warn directly:
This tutorial removes Cloud Billing from your project, shutting down all resources. Resources might be irretrievably deleted. You can re-enable Cloud Billing, but it requires manual configuration and there’s no guarantee of service recovery.
Additional constraints:
- Notification latency means there is no guarantee the spend stays under the budget.
- A project with a locked billing account link cannot be disabled this way.
- The function’s service account requires strong billing permissions, and that permission itself is a risk.
- Active / Pending CUDs attached to the project may prevent disabling billing.
- Disabling billing on a Shared VPC host project cascades to the dependent service projects.
Restrict this pattern to personal verification, hands-on labs, and sandboxes where losing all data is acceptable. Use the billing link lock on production so this automation cannot disable billing through the API.
The full defense-in-depth picture
Putting the layers together yields three layers: prevent, detect, and enforce / respond.
flowchart TB
subgraph Prevent["Prevent"]
IAM[Least-privilege IAM]
OP[Organization Policies]
Q[Cloud Quotas / service caps]
LOCK[Production billing link lock]
end
subgraph Detect["Detect"]
B[Alerts-only Budgets<br/>actual + forecast]
A[Cost Anomaly Detection]
EA[Early anomalies for AI]
EX[Billing Export to BigQuery]
end
subgraph Enforce["Enforce / Respond"]
SC[Spend Cap Budgets<br/>4 services]
PS[Pub/Sub]
FN[Cloud Run functions]
HUMAN[FinOps / On-call]
STOP[Staged VM stop]
end
B --> PS
A --> PS
EA --> PS
PS --> FN
PS --> HUMAN
FN --> STOP
SC --> HUMAN
EX --> HUMAN
Separate controls by environment
Shift the weight of controls by environment.
| Environment | Recommended controls |
|---|---|
| Production | No auto-stop. Alerts-only Budget (actual + forecast), Cost Anomaly Detection, Early anomalies, escalation to on-call and department heads, upper bound on Compute autoscale, billing link lock |
| Staging / integration | Alerts-only Budget + Pub/Sub integration, moderate Spend Cap on supported services, strict machine type restrictions via Organization Policy, BigQuery maximum bytes billed, Cloud Run max-instances |
| Dev | Budget + staged VM auto-stop, low-dollar Spend Cap on supported services, Organization Policy denying expensive SKUs, Cloud Logging _Default sink exclusions |
| Sandbox | Small budget, low-dollar Spend Cap on supported services, consider the billing disable script only if total data loss is acceptable, GPUs denied by default, no billing link lock |
Separate production from non-production with folders, and nest sandbox under non-production. For small and mid-size organizations, keep to a single billing account, splitting with folders, projects, and labels. Split billing accounts only when the Gemini API tier limit risks pulling production down, when anomaly sensitivity should differ between sandbox and production, or when subsidiaries or business units need separate invoices.
Managing budgets with Terraform
Codify budgets with the google_billing_budget resource and plug it into the project provisioning pipeline (Project Factory). The currency must match the billing account’s currency.
resource "google_billing_budget" "dev_project" {
billing_account = var.billing_account_id
display_name = "dev-${var.project_id}-monthly"
budget_filter {
projects = ["projects/${var.project_number}"]
}
amount {
specified_amount {
currency_code = "USD"
units = "1000"
}
}
threshold_rules { threshold_percent = 0.5 }
threshold_rules { threshold_percent = 0.9 }
threshold_rules { threshold_percent = 1.0 }
threshold_rules {
threshold_percent = 1.0
spend_basis = "FORECASTED_SPEND"
}
all_updates_rule {
pubsub_topic = var.budget_topic_id
monitoring_notification_channels = [var.team_email_channel_id]
}
}Setting disable_default_iam_recipients = true turns off notifications to the default recipients (Billing Account Administrators and Users). Enabling it without configuring a notification channel yields a budget that notifies no one, so pair the two.
Scoping risk from AI coding agents
When an AI coding agent reaches Google Cloud APIs directly, the first line of defense is to narrow the credentials the agent uses.
- Use a dedicated service account or Workload Identity Federation. Limit IAM to least-privilege roles on specific folders and projects. Do not grant Owner.
- Restrict resource types and regions the agent can deploy via Organization Policy. Deny expensive SKUs such as GPU VMs, and use
gcp.restrictServiceUsageto limit the agent to approved services. - Apply a conservative Budget on the agent’s project (for example 1.5× expected monthly spend). Add Spend Cap on whichever of Gemini API, Agent Platform, or Cloud Run the agent calls.
- Wire Pub/Sub-driven auto-stop, Cost Anomaly Detection, and Early anomalies to Slack or PagerDuty.
- Pin one view (a Cost Analysis saved view or the FinOps hub dashboard) in a daily standup or team meeting so everyone sees the spend trend.
Apply the same API key controls to any key an agent uses: API restrictions, application restrictions, migration to auth keys, and automatic disablement on detected exposure. Cloud Quotas and Spend Cap then bound the dollar impact.
Rollout checklist
To avoid destructive impact on existing environments, work in this order.
- Today: create an alerts-only Budget for the whole billing account (actual 50 / 90 / 100% + forecast 100%) and verify the recipients actually see the notifications. Audit who holds
roles/billing.admin,roles/billing.creator, androles/resourcemanager.projectCreator. - This week: add API restrictions to every API key (separate Gemini keys from others). Apply Spend Cap on non-production projects that use Gemini API, Agent Platform, or Cloud Run, and set the project cap on AI Studio.
- This week: set BigQuery custom quotas (per project and per user) and
maximum bytes billed. Enable Cloud Billing BigQuery export (Standard, Detailed, and FOCUS). - This month: lock the billing link on production projects. Narrow who holds
roles/billing.user. Evaluate Organization Policies (region, SA key creation, GPU restriction) with dry-run, then enforce. - This quarter: bring Budget, Spend Cap, labels, and Cloud Quotas into the Terraform project provisioning pipeline. Build the staged Pub/Sub response (notify → stop non-production VMs). Fold Cost Anomaly Detection, Early anomalies, and the FinOps hub into monthly reviews.
As a standing rule: automated billing disable belongs only in sandboxes, never production. Spend Cap on production is appropriate only for workloads where a stop is tolerable.
That’s all from designing a Google Cloud spending cap against the Spend Cap’s four-service limit, by stacking Budgets with Organization Policies, Cloud Quotas, IAM, billing link locks, Spend Cap, and Pub/Sub automated response for the AI coding agent era, from the Gemba.
References
- Create, edit, or delete budgets and budget alerts
- Manage spend cap budgets
- Google Cloud spend caps now generally available
- Set up programmatic notifications
- Disable billing usage with notifications
- Control resource usage with notifications
- Secure the link between a project and its billing account
- Cloud Quotas overview
- Organization Policy overview
- Restrict service usage
- Cloud Billing access control and permissions
- View and manage cost anomalies
- Estimate and control costs (BigQuery)
- Set maximum instances for services (Cloud Run)
- Configure default resource settings for Cloud Logging
- Well-Architected Framework: Cost optimization pillar