GCP Cost Optimization: Reduce Your Google Cloud Bill
In this tutorial, you'll learn about GCP Cost Optimization: Reduce Your Google Cloud Bill. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
GCP cost optimization is the practice of reducing your GCP bill by leveraging committed use discounts, preemptible VMs, sustained use auto-discounts, rightsizing recommendations, and storage lifecycle policies — without compromising performance.
What You'll Learn
You'll configure Committed Use Discounts for steady-state workloads, deploy preemptible and Spot VMs for fault-tolerant jobs, apply rightsizing recommendations from the GCP Recommender, set up budget alerts with Pub/Sub notifications, and optimize storage and network costs.
Why It Matters
GCP offers unique cost advantages — sustained use discounts apply automatically, and preemptible VMs are simpler to use than AWS Spot. But without active management, orphaned disks, oversized instances, and cross-region network egress still waste 25-35% of spend. DodaTech reduced DodaZIP's data processing costs by 40% using preemptible TPUs and committed use discounts on Compute Engine.
flowchart LR
A[GCP Cost Tools] --> B[Committed Use Discounts]
A --> C[Preemptible / Spot VMs]
A --> D[Sustained Use Discounts]
A --> E[Recommender]
B --> F[30-70% Savings]
C --> G[60-91% Savings]
D --> H[Auto: up to 30%]
E --> I[Rightsizing + Architecture]
style F fill:#34a853,color:#fff
1. Committed Use Discounts (CUDs)
CUDs offer 30-70% discount in exchange for a 1- or 3-year commitment to a specific amount of vCPU, memory, or GPU resources in a region.
# Purchase a Compute Engine CUD (1-year)
gcloud compute commitments create \
--region us-central1 \
--name cud-1yr-8vcpu \
--resources vcpu=8,memory=32768 \
--plan 12-month \
--type general-purpose
# Purchase a CUD for GPUs (3-year)
gcloud compute commitments create \
--region us-central1 \
--name cud-3yr-t4 \
--resources vcpu=16,memory=65536,gpu=2 \
--plan 36-month \
--type accelerators
# List existing commitments
gcloud compute commitments list --region us-central1
Expected output:
[
{
"name": "cud-1yr-8vcpu",
"plan": "12-month",
"resources": {"vcpu": "8", "memory": "32768MB"},
"status": "NOT_YET_ACTIVE",
"startTimestamp": "2026-06-21T00:00:00Z]
}
]
| Resource Type | 1-Year Discount | 3-Year Discount |
|---|---|---|
| General-purpose vCPU | 20-30% | 40-55% |
| Memory-optimized vCPU | 30-40% | 50-65% |
| GPU (T4, V100, A100) | 30-40% | 50-70% |
2. Sustained Use Discounts
GCP automatically applies sustained use discounts to VMs that run for a significant portion of the month — no upfront commitment needed.
# sustained_use_calculator.py
def calculate_sustained_use_discount(hours_run: int, monthly_hours: int = 730) -> float:
"""Calculate automatic sustained use discount for a single VM."""
usage_percentage = (hours_run / monthly_hours) * 100
if usage_percentage <= 25:
discount = 0.0
elif usage_percentage <= 50:
discount = 10.0
elif usage_percentage <= 75:
discount = 20.0
else:
discount = 30.0
return discount
def monthly_cost(instance_type: str, hours: int, base_rate: float) -> dict:
discount = calculate_sustained_use_discount(hours)
discounted_rate = base_rate * (1 - discount / 100)
total_cost = discounted_rate * hours
return {
"instance": instance_type,
"hours": hours,
"usage_pct": round((hours / 730) * 100, 1),
"discount_pct": discount,
"effective_rate": round(discounted_rate, 4),
"total_cost": round(total_cost, 2)
}
vms = [
("n2-standard-4", 730, 0.095), "# Full month
("n2-standard-4"", 400, 0.095), "# Half month
("n2-standard-4"", 100, 0.095), # Short burst
]
for vm in vms:
result = monthly_cost(*vm)
print(f"{result['instance']:15} {result['hours']:4}h ({result['usage_pct']:5.1f}%) "
f"-> {result['discount_pct']:2.0f}% off -> ${result['total_cost']:>7.2f}")
Expected output:
n2-standard-4 730h (100.0%) -> 30% off -> $ 48.55
n2-standard-4 400h ( 54.8%) -> 20% off -> $ 30.40
n2-standard-4 100h ( 13.7%) -> 0% off -> $ 9.50
3. Preemptible and Spot VMs
Preemptible VMs offer up to 91% discount but run for a maximum of 24 hours. Spot VMs have no time limit but can still be terminated.
# Create a preemptible VM
gcloud compute instances create batch-worker-01 \
--zone us-central1-a \
--machine-type n2-standard-8 \
--preemptible \
--max-run-duration 14400s
# Create a Spot VM with proactive termination handling
gcloud compute instances create spot-worker-01 \
--zone us-central1-a \
--machine-type n2-standard-8 \
--provisioning-model SPOT \
--instance-termination-action STOP
# Create a preemptible instance template for managed instance groups
gcloud compute instance-templates create preemptible-template \
--machine-type n2-standard-4 \
--preemptible \
--image-family ubuntu-2204-lts \
--image-project ubuntu-os-cloud
Pricing comparison:
n2-standard-8 on-demand: $0.38/hr
n2-standard-8 preemptible: $0.04/hr (90% savings)
n2-standard-8 spot: $0.06/hr (84% savings)
Graceful Shutdown Handling
#!/bin/bash
# preemptible-shutdown.sh — runs when GCP signals preemption
# Set up with: gcloud compute instances add-metadata \
# --metadata shutdown-script="$(cat preemptible-shutdown.sh)"
echo "Preemption notice received. Saving checkpoint..."
JOB_DIR="/var/checkpoints"
# Save job state to persistent storage
if [ -f "$JOB_DIR/current_job.state" ]; then
gsutil cp "$JOB_DIR/current_job.state" "gs://dodatech-checkpoints/$(hostname)-$(date +%s).state"
echo "Checkpoint saved."
fi
# Drain connections
echo "Draining active connections..."
sleep 5
# Signal completion
curl -X POST -H "Content-Type: application/json" \
-d '{"instance": "'$(hostname)'", "status": "shutdown", "checkpoint": true}' \
https://monitor.dodatech.com/events
echo "Shutdown complete."
4. GCP Recommender for Rightsizing
The GCP Recommender analyzes utilization and suggests optimal machine types.
# List rightsizing recommendations
gcloud recommender recommendations list \
--project=my-project \
--location=us-central1-a \
--recommender=google.compute.instance.MachineTypeRecommender \
--format="json"
# Apply a recommendation (resize instance)
gcloud compute instances set-machine-type my-instance \
--machine-type e2-standard-4 \
--zone us-central1-a
# List idle IP address recommendations
gcloud recommender recommendations list \
--project=my-project \
--location=global \
--recommender=google.compute.address.IdleResourceRecommender
Expected recommendation output:
{
"recommendation": "Change machine type from n2-standard-8 to n2-standard-4",
"costProjection": {
"monthlySavings": {"currency": "USD", "value": 98.56}
},
"primaryImpact": {
"category": "COST",
"costProjectionBefore": 197.12,
"costProjectionAfter": 98.56
}
}
5. Storage Class Tiering
GCP Cloud Storage offers object lifecycle management to move data between storage classes.
# Create a lifecycle policy to tier data
gcloud storage buckets update gs://dodatech-logs \
--lifecycle-file=- <<EOF
{
"lifecycle": {
"rule": [
{
"action": {"type": "SetStorageClass", "storageClass": "NEARLINE"},
"condition": {"age": 30, "matchesStorageClass": ["STANDARD"]}
},
{
"action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
"condition": {"age": 90, "matchesStorageClass": ["NEARLINE"]}
},
{
"action": {"type": "SetStorageClass", "storageClass": "ARCHIVE"},
"condition": {"age": 365, "matchesStorageClass": ["COLDLINE"]}
},
{
"action": {"type": "Delete"},
"condition": {"age": 730}
}
]
}
}
EOF
# Check current storage class breakdown
gsutil du -s -c gs://dodatech-logs/**
| Storage Class | Price/GB/Month | Retrieval |
|---|---|---|
| Standard | $0.020 | Instant |
| Nearline | $0.010 | Instant (1s) |
| Coldline | $0.004 | Instant (1s) |
| Archive | $0.0012 | Hours |
Common Mistakes
Not using Committed Use Discounts: Every steady-state workload should be covered by a CUD. For a single n2-standard-8 running 24/7 for a year, the saving is $1,200.
Preemptible VMs for long-running jobs: Preemptible VMs are terminated after 24 hours. Use Spot VMs for workloads that need more than 24 hours.
Ignoring sustained use discounts: These apply automatically, but spreading workloads across many regions reduces the per-region discount. Consolidate into fewer regions.
No budget alerts: Set budgets with alerts at 50%, 90%, and 100% of forecast. Use Pub/Sub to trigger automated shutdowns.
Orphaned persistent disks: Deleting a VM does not delete the boot disk. Use
gcloud compute disks list --filter="users=[]"to find unattached disks.
Practice Questions
What is the difference between a Committed Use Discount and a Sustained Use Discount? Answer: CUD requires a 1- or 3-year commitment for 30-70% discount. Sustained Use Discount applies automatically based on monthly usage (up to 30%) with no commitment.
When should you use preemptible VMs vs Spot VMs on GCP? Answer: Preemptible VMs for workloads under 24 hours at maximum discount. Spot VMs for workloads exceeding 24 hours with similar discounts but no runtime limit.
How do you find orphaned persistent disks in GCP? Answer:
gcloud compute disks list --filter="users=[]"lists unattached disks. Use--formatto export for automated cleanup.
Challenge
Optimize a $40k/month GCP project: purchase CUDs covering 70% of steady-state compute, migrate all batch processing to preemptible VMs with checkpointing, apply Recommender rightsizing suggestions, configure lifecycle policies for all storage buckets, set up budgets with Pub/Sub alerts, and clean up unattached disks and unused static IPs.
FAQ
What's Next
| Topic | Description |
|---|---|
| {{< card link="../gcp-pricing-guide" title="GCP Pricing Guide" icon="currency-dollar" >}} | Detailed GCP pricing and discounts |
| {{< card link="../spot-instances" title="Spot & Preemptible Instances" icon="currency-dollar" >}} | Deep dive into spot compute |
Related topics: Cloud Cost Optimization, Cloud Computing, GCP
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro