Back to diary list

Diary

How I ended the 'fear of notifications without stopping' by setting Spend Caps on all Google Cloud projects

October 24, 202632 minShin Yamaguchi (Representative Partner, FLARES LLC)
Defense-in-depth architecture using Google Cloud Spend Cap budgets. A triple safety mechanism consisting of Edge WAF, execution quota limits, and hard caps.

The term 'cloud bankruptcy' has been whispered among engineers for a long time.

The greatest benefit of public cloud is the flexibility of pay-as-you-go. However, this is always two sides of the same coin with the structural risk that unexpected bugs, traffic surges, or external cyberattacks can lead to massive bills in the millions of yen overnight.

Especially in recent development environments, autonomous agents utilizing LLMs like Gemini API and Vertex AI for night batches, and event-driven microservice coordination using Cloud Run have become standard infrastructure.

What if an infinite loop occurs in the agent's retry process?

What if thousands of API calls per second are repeated due to a runaway prompt?

Or what if Cloud Run endpoints are flooded with traffic, causing containers to scale up to the maximum limit?

Waking up in the morning and opening your email to find a terrifyingly high bill—this type of accident is by no means someone else's problem.


The limitations of traditional Google Cloud budget alerts that 'only notify and do not stop'

Google Cloud has long provided a feature called 'Billing Budgets'. Most teams likely have settings like 'send an email when it reaches 10,000 yen per month'.

However, this standard alert has had a fatal weakness for many years.

That is,**'It only sends a notification email, and neither billing nor resources stop at all (Alerts-only)'**is the specification.

Even if the budget reaches 100% at 2:00 AM and an email is sent, if we are asleep, we won't notice the notification. For the 5 hours until we wake up at 7:00 AM and open the email, the runaway containers and APIs continue to run at full power, relentlessly running up the billing meter. The notification alert is a fire alarm that screams 'Fire!', but it does not sprinkle water like a sprinkler to put out the fire.


Why traditional 'DIY kill switches' could not withstand operations

To address this issue, many 'DIY kill switches' have been devised in the engineering community. A representative one is,**'Triggering Cloud Functions via Billing Budgets Pub/Sub notifications to programmatically disconnect the Billing Account from the project (Disable Billing)'**a method.

I have considered this approach in the past. However, when looking at production operations, I hit three fatal walls that I could not accept.

  1. Risk of collateral damage to persistent data:

    When you disable billing for a project, not only the runaway Cloud Run or API, but also Cloud SQL (database), Cloud Storage (file storage), and Secret Manager within the same project are stopped uniformly. In the worst case, it carried the catastrophic risk of data corruption due to resource shutdown or forced deletion of resources after a certain period.

  2. Data delay (time lag) of several hours to a day:

    Billing's confirmed billing reports (Cloud Billing Export or BigQuery export) are not real-time but are reflected in batch processes that take several hours to up to a day. By the time the kill switch detected '100% budget' and activated, several times the high billing was already confirmed, making it easy for a situation to occur where 'it stopped, but it was too late'.

  3. Bloating of operational maintenance costs:

    Every time the number of managed projects increases, you must individually provision Pub/Sub topics, Cloud Functions, and IAM permissions, and keep up with API changes and runtime EOLs. There was also the constant risk of accidental stops due to bugs in the DIY kill switch itself.

'I just want to stop it safely, but I'm forced to choose between holding persistent data hostage or fearing the late batch delay.' This binary choice was an extremely heavy mental burden when operating the cloud.


Savior: Full-scale introduction of Spend Cap budgets

A feature that puts a definitive end to such long-standing distress has been added to Google Cloud Billing Budgets. That is**'Spend Cap'**.

Spend Cap is an official hard-limit feature that, the moment the pre-set monthly budget limit (100%) is reached,the Google Cloud platform side automatically shuts out (blocks) new API requests for the target service.| Comparison Item | Traditional Budget Alerts | DIY Kill Switch (Disable Billing) | Spend Cap budgets (Adopted) |

| :--- | :--- | :--- | :--- | |

Operation Method | Email/Slack notification only | Billing removal via Pub/Sub + Cloud Functions | API blocking by Google Cloud platform ||

Resource Stop | | Non-stop(Billing continues) | Entire project completely stopped | Safely block only the target service |

| Impact on persistent resources | None (remains operational) | Danger(Collateral damage to Cloud SQL/Storage) | Completely unscathed(DB and files remain operational) | | Judgment timing | Final report (delayed by several hours to 1 day) | Final report (delayed by several hours to 1 day) | Estimated total cost (near real-time) | | Recovery the following month | No configuration required | Manual re-linking required | Automatic recovery on the 1st of the next month (Automatic Lift) | | Emergency manual release | Not required | Complex permission recovery procedure | Immediate release via Console/API (Manual Lift) | | Operational maintenance cost | Low | Enormous (function maintenance/malfunction risk) | Minimal (managed settings only) |

The moment I saw this specification, I was convinced, "This is what we have been looking for for years." Therefore, I decided to implement this Spend Cap across all billing accounts I manage and all active projects.


The four major target API services and the "1 project x 1 service" constraint

Currently, the four services that can be specified as targets for Spend Cap in Google Cloud are as follows.

  1. Gemini API (generativelanguage.googleapis.com)
  2. Vertex AI (aiplatform.googleapis.com)
  3. Cloud Run (run.googleapis.com)
  4. Cloud Run functions (cloudfunctions.googleapis.com)

Indeed, in the midst of the generative AI boom, the compute and AI layers—where the risk of skyrocketing and runaway pay-as-you-go costs is most concerning—are perfectly covered. While persistent layers like databases and storage are excluded, these resources are not of a nature where millions of yen can vanish in minutes due to request volume, so these four services are necessary and sufficient for stopping sudden runaways.

The biggest practical pitfall: inability to configure aggregation

Here, I faced a very important technical constraint (a pitfall) in practice.

Spend Cap cannot be set foran 'entire organization,' 'entire billing account,' or 'a budget covering multiple services.'.

It must be set**as the smallest unit combination of 'a single project (1 project) × a single service (1 service).'**The specification is such that it can only be set in this way.

For example, if you are using both Gemini API and Cloud Run in one project, you cannot create one budget for the entire project; you must create a 'Spend Cap for Gemini API in that project' and a 'Spend Cap for Cloud Run in that project' separately.

If you manage multiple projects, the number multiplies. In my environment, after listing all combinations of projects and active services,**I found that I needed to create a total of 25 individual Spend Cap budgets.**Manually clicking through the Google Cloud Console GUI to create these one by one is a breeding ground for configuration errors and is not realistic.


Bulk provisioning 25 Spend Cap budgets

Therefore, I utilized the Google Cloud Billing Budgets API (google.cloud.billing.budgets.v1), and created an automation script to create and synchronize budget resources in bulk from a definition file.

The API request structure for enabling Spend Cap is as follows.

{
  "displayName": "prod-core-gemini-spend-cap",
  "budgetFilter": {
    "projects": ["projects/123456789012"],
    "services": ["services/generativelanguage.googleapis.com"],
    "creditTypesTreatment": "EXCLUDE_ALL_CREDITS",
    "calendarPeriod": "MONTH"
  },
  "amount": {
    "specifiedAmount": {
      "currencyCode": "JPY",
      "units": "25000"
    }
  },
  "thresholdRules": [
    { "thresholdPercent": 0.5 },
    { "thresholdPercent": 0.8 },
    { "thresholdPercent": 1.0, "spendBasis": "CURRENT_SPEND" }
  ],
  "notificationsRule": {
    "enableProjectLevelRecipients": true
  },
  "spendCap": {
    "outputState": "CONFIGURED"
  }
}

The key points are the following three.

  1. spendCap: { outputState: "CONFIGURED" } specification:

    By including this, it is promoted from a simple alert budget to a 'spending limit budget that performs hard blocks.'

  2. creditTypesTreatment: "EXCLUDE_ALL_CREDITS":

    This ensures that promotional credits and free tiers are not included in the calculation, and judgment is based on pure usage fees (gross amount). This prevents blocks from being delayed due to unexpected free tier consumption discrepancies.

  3. enableProjectLevelRecipients: true:

    This ensures that not only billing administrators but also project owners and developers receive direct email notifications when 50%, 80%, and 100% thresholds are reached.

The sense of achievement and peace of mind when I ran the script and all 25 Spend Caps were provisioned without errors was exceptional.


Peace of mind in the operating principle: Why I can sleep soundly at night

The greatest value this Spend Cap brings is that 'the process of system suspension and recovery is designed to be extremely rational and safe.'

1. Near real-time judgment based on Gross Estimated Costs

There is no delay of several hours like in traditional billing reports. The Google Cloud infrastructure continuously evaluates estimated costs, and a block decision is made immediately when approaching the limit (100%). Even if a sudden burst occurs at night, the faucet is turned off within minutes to tens of minutes.

2. Localized blocking of target APIs only

When 100% is reached, only new requests to the specified service are blocked.

Even if Cloud Run is blocked, databases in Cloud SQL and customer data in Cloud Storage remain intact and waiting. Data corruption or loss will absolutely not occur.

3. Flexibility of Automatic Lift and Manual Lift

When the month changes and it hits 0:00 (UTC) on the 1st of the next month, the current month's usage is reset to zero, and the block is automatically lifted (Automatic Lift). There is no need for humans to perform recovery work at the beginning of the next month.

Also, if the limit is reached temporarily due to a legitimate surge in access during the day, you can increase the budget amount from the Console or API, or lift the Spend Cap setting (Manual Lift), and the service will usually return to normal operation within an hour.


Budget design matrix by hierarchy

Setting a uniform limit for all projects does not fit the reality of operations. The acceptable costs and risks differ between prototypes under verification and core services in production.

Therefore, this time, I designed the following three-tier budget matrix according to the project's role.

Environment ClassificationMain UseSpend Cap Limit (Monthly)Alert ThresholdAssumed Response Policy
Tier 1: Verification/StagingPoC, development environment, experimental agents1,000 JPY - 2,000 JPY50%, 80%, 100%Immediate stop upon runaway detection. Left idle until the following month or released after bug fixes
Tier 2: Internal infrastructure / Medium-scale mediaBusiness support tools, owned media, batch processing8,000 JPY - 15,000 JPY50%, 80%, 100%Optimize queries or cache at 80% notification. Decide on budget increase upon reaching 100%
Tier 3: Mission-critical production servicesCustomer-facing web services, production API integration25,000 JPY50%, 80%, 100%Immediate investigation of scale factors at 80% notification. Increase limit if necessary to continue

By setting an extremely tight limit of 1,000 JPY for the verification environment, even if a developer leaves a loop process running over the weekend, the damage is reliably capped at the cost of a single lunch. On the other hand, the production environment is set to 25,000 JPY, which is about 2-3 times the normal monthly usage, tuned so that it does not stop during normal spikes and only triggers the safety net during clear anomalies.


3-Layer Defense in Depth Architecture

Of course, just because there is a Spend Cap does not mean you can neglect unlimited scaling or security measures on the application side.

The Spend Cap is strictly the "Last Line of Defense."

We have implemented a multi-layered defense architecture consisting of the following three layers.

Loading diagram...
  1. Layer 1 (Edge Defense Layer): Cloudflare WAF / Rate Limiting

    Turn away malicious bots, DDoS attacks, and brute-force requests at the Cloudflare edge. Prevent requests from reaching Google Cloud in the backend in the first place.

  2. Layer 2 (Execution / Quota Suppression Layer): Cloud Run max-instances and API Quota

    Explicitly limit the max-instances (maximum number of instances) of Cloud Run services to prevent thousands of containers from spinning up uncontrollably. Also, set realistic values for Gemini API and Vertex AI project quotas (requests per minute / token limits).

  3. Layer 3 (Billing Hard Cap Layer): Google Cloud Spend Cap

    In the event that internal bugs, infinite retries, or unexpected large-scale data processing slip through the first and second layers, the Spend Cap acts as the final line of defense, physically shutting down the API to reliably stop expenditures.

Because these three layers overlap, no matter what happens at any layer, it will not lead to a fatal blow.


Only by solidifying defenses can we accelerate offensive development

As a company that operates its own services and manages client systems, infrastructure cost management is not just an accounting issue, but a management task that determines business continuity.

As long as you live with the "fear of not stopping with just a notification," running night batches or operating new autonomous LLM agents will always have a psychological brake applied.

By rolling out Spend Caps to all projects and completing the 3-layer defense in depth, that psychological brake has completely disappeared. This is because we have the certainty that "no matter how bad a runaway occurs, it will not jump up by even one yen beyond the set limit."

It is because of robust guardrails that cars can reach top speed on a circuit.

With infrastructure defenses thoroughly automated and hardened, we want to continue to step on the accelerator for exploring and challenging new technologies without hesitation.