GCP Cost Optimization â Google Cloud Savings Guide
In this tutorial, you'll learn about GCP Cost Optimization. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
GCP cost optimization reduces your Google Cloud Platform bill by right-sizing Compute Engine instances, leveraging committed use discounts and preemptible VMs, tiering Cloud Storage, minimizing network egress, and enforcing governance with budgets and quotas.
What You'll Learn
By the end of this guide, you'll be able to use GCP Cost Management, right-size GCE instances, choose between Committed Use Discounts and preemptible VMs, tier Cloud Storage with lifecycle policies, reduce network egress costs, and set up budget alerts and quota controls.
Why It Matters
GCP's per-second billing and sustained use discounts help, but costs can still balloon from over-provisioned instances, unattached disks, and data egress. Most GCP accounts waste 25-35% on unnecessary resources. DodaTech reduced DodaZIP's GCP costs by 30% through committed use discounts and preemptible batch processing.
Real-World Use
Spotify uses Committed Use Discounts for its podcast infrastructure, saving 40% over on-demand pricing. Snapchat runs ML training on preemptible VMs at 80% discount. Etsy reduced BigQuery costs by 60% through clustering, Partitioning, and slot management.
flowchart LR
A[Cost Management] --> B[Right-Size GCE]
B --> C[CUD]
B --> D[Preemptible VMs]
A --> E[Storage Tiering]
A --> F[Budgets & Quotas]
C --> G[30-70% Savings]
style G fill:#4285F4,color:#fff
Prerequisites: GCP project access, familiarity with Compute Engine. Understanding of Cloud Computing fundamentals helps.
1. Cost Visibility with GCP Cost Management
GCP Cost Management provides detailed reports, pricing tables, and recommendation insights.
# List billing accounts
gcloud billing accounts list
# Export costs to BigQuery for analysis
gcloud billing budgets create \
--billing-account=BILLING_ACCOUNT_ID \
--display-name="monthly-budget" \
--budget-amount=50000 \
--threshold-rules=percent=0.5 \
--threshold-rules=percent=0.9 \
--filter-projects="projects/my-project"
2. Right-Sizing Compute Engine
Use GCP Rightsizing Recommendations from the Recommender API:
# Get rightsizing recommendations
gcloud recommender recommendations list \
--recommender=google.compute.instance.UsageRecommender \
--project=my-project \
--location=us-central1-a \
--format="table(name,primaryImpact.category,priority)"
# gce_rightsize.py
class GCERightsizer:
def __init__(self):
self.instances = []
def add_instance(self, name, machine_type, cpu_pct, memory_pct, monthly_cost):
self.instances.append({"name": name, "type": machine_type, "cpu": cpu_pct, "mem": memory_pct, "cost": monthly_cost})
def recommend(self):
for inst in self.instances:
if inst["cpu"] < 20 and inst["mem"] < 30:
savings = inst["cost"] * 0.5
print(f"{inst['name']} ({inst['type']}): CPU {inst['cpu']}% Mem {inst['mem']}%. â Downsize. Save ${savings:.0f}/mo")
gc = GCERightsizer()
gc.add_instance("web-1", "n1-standard-4", 15, 25, 220)
gc.add_instance("worker-1", "n1-standard-8", 10, 20, 440)
gc.add_instance("db-1", "n1-highmem-8", 45, 60, 380)
gc.recommend()
Expected output:
web-1 (n1-standard-4): CPU 15% Mem 25%. â Downsize. Save $110/mo
worker-1 (n1-standard-8): CPU 10% Mem 20%. â Downsize. Save $220/mo
3. Committed Use Discounts (CUD) vs Preemptible VMs
| Model | Discount | Best For |
|---|---|---|
| 1-year CUD | 20-40% | Steady-state workloads |
| 3-year CUD | 40-60% | Predictable long-running services |
| Preemptible VMs | 60-91% | Batch, fault-tolerant, stateless jobs |
| Spot VMs | 60-91% | Same as preemptible, no 24h max |
# Purchase a 1-year Committed Use Discount
gcloud compute commitments create \
--name=cud-1yr \
--plan=12-month \
--resources=vcpu=50,memory=200GB \
--region=us-central1 \
--project=my-project
# List preemptible instances
gcloud compute instances list \
--filter="scheduling.preemptible=true" \
--format="table(name,zone,machineType)"
# Create a preemptible VM (80% cheaper)
gcloud compute instances create batch-worker \
--zone=us-central1-a \
--machine-type=n1-standard-8 \
--preemptible \
--maintenance-policy=TERMINATE
4. Cloud Storage Tiering
GCP Cloud Storage offers Standard, Nearline, Coldline, and Archive classes:
# Set lifecycle policy via JSON
cat > lifecycle.json << EOF
{
"lifecycle": {
"rule": [
{
"action": {"storageClass": "NEARLINE"},
"condition": {"age": 30}
},
{
"action": {"storageClass": "COLDLINE"},
"condition": {"age": 90}
},
{
"action": {"storageClass": "ARCHIVE"},
"condition": {"age": 365}
}
]
}
}
EOF
gsutil lifecycle set lifecycle.json gs://dodatech-logs/
Cost comparison for 10TB:
- Standard: $240/month
- Nearline (30d): $120/month
- Coldline (90d): $40/month
- Archive (365d): $12/month
5. Network Egress
GCP egress costs $0.12/GB (internet) but is free between Google services in the same region:
# gcp_network_audit.py
egress = {
"Internet egress": {"gb": 3000, "rate": 0.12},
"Cross-region (US-EU)": {"gb": 2000, "rate": 0.08},
"Same-region (free)": {"gb": 5000, "rate": 0},
"Premium Tier egress": {"gb": 2000, "rate": 0.15},
"Standard Tier egress": {"gb": 2000, "rate": 0.085},
}
for name, s in egress.items():
cost = s["gb"] * s["rate"]
print(f"{name:<30} ${cost:>8.2f}/mo")
Expected output:
Internet egress $360.00/mo
Cross-region (US-EU) $160.00/mo
Same-region (free) $0.00/mo
Premium Tier egress $300.00/mo
Standard Tier egress $170.00/mo
6. Budgets and Quotas
Set budget alerts and custom quotas to prevent runaway costs:
# Create a budget alert
gcloud billing budgets create \
--billing-account=BILLING_ACCOUNT_ID \
--display-name="monthly-compute" \
--budget-amount=25000 \
--threshold-rules=percent=0.5 \
--threshold-rules=percent=0.8 \
--threshold-rules=percent=1.0 \
--notifications-rule-pubsub-topic=budget-alerts \
--notifications-rule-schema=amount_ratio
# Set custom quota for Compute Engine
gcloud compute project-info add-metadata \
--metadata="quota_vm_count=50" \
--project=my-project
# List current quotas
gcloud compute regions describe us-central1 \
--format="table(quotas)"
Common Mistakes
1. Not Using Committed Use Discounts
Steady-state workloads on on-demand pricing are 40-60% more expensive than CUDs. Even a 1-year commitment saves 20-40%.
2. Running Preemptible-Incompatible Workloads
Preemptible VMs can terminate within 30 seconds. Don't run databases or stateful services on them. Use checkpoints for batch jobs.
3. Ignoring Sustained Use Discounts
GCP automatically applies sustained use discounts for running instances >25% of a month. But these cap at 30% â CUDs save more for predictable usage.
4. Cross-Region Network Egress
Data transfer between GCP regions costs $0.08-0.12/GB. Keep services in the same region when possible.
5. No Budget Alerts
Without budgets, a runaway data pipeline can burn through thousands in hours. Always set budgets at 50%, 80%, 90%, and 100%.
Practice Questions
1. What is the difference between Committed Use Discounts and Sustained Use Discounts? CUDs are pre-purchased commitments for 1 or 3 years, saving 20-60%. SUDs are automatically applied for instances running >25% of a month, capping at 30%. CUDs offer higher savings for predictable workloads.
2. When should you use preemptible VMs? For batch processing, rendering, CI/CD workers, ML training, and any fault-tolerant workload. Don't use for databases, stateful services, or latency-sensitive applications.
3. What are the GCP Cloud Storage classes? Standard (frequent), Nearline (30+ days), Coldline (90+ days), Archive (365+ days). Each tier reduces storage cost but increases retrieval cost and minimum storage duration.
4. Challenge: Optimize a $45k/month GCP project: review Recommender rightsizing suggestions, purchase CUDs for baseline compute, migrate batch jobs to preemptible VMs, implement lifecycle policies for all storage buckets, and set up budget alerts.
Mini Project: GCP Cost Analyzer
class GCPCostAnalyzer:
def __init__(self):
self.costs = {}
def add_service_cost(self, service, on_demand, cud_eligible=True):
self.costs[service] = {"on_demand": on_demand, "cud_eligible": cud_eligible}
def analyze_savings(self):
total_on_demand = sum(s["on_demand"] for s in self.costs.values())
cud_eligible = sum(s["on_demand"] for s in self.costs.values() if s["cud_eligible"])
print(f"Total on-demand: ${total_on_demand:,}/mo")
print(f"CUD-eligible: ${cud_eligible:,}/mo")
print(f"Potential CUD savings (40%): ${cud_eligible*0.4:,.0f}/mo")
print(f"Potential preemptible (off-peak): ${cud_eligible*0.7*0.8:,.0f}/mo")
gcp = GCPCostAnalyzer()
gcp.add_service_cost("Compute Engine", 20000)
gcp.add_service_cost("Cloud SQL", 5000)
gcp.add_service_cost("GKE nodes", 8000)
gcp.add_service_cost("BigQuery (on-demand)", 3000, cud_eligible=False)
gcp.analyze_savings()
FAQ
Related Concepts
What's Next
You now understand GCP cost optimization! Next, learn about Kubernetes Cost optimization, then explore Multi-Cloud Cost optimization for managing costs across GCP, AWS, and Azure.
- Practice daily â Review GCP Recommender recommendations
- Build a project â Automate preemptible VM checkpoint/restart for batch jobs
- Explore related topics â Check out BigQuery slot management for query cost control
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro