Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🔧 GCP Account Setup⚙️ GCP Compute Overview🚀 Cloud Run Deployment🎯 App Engine Deployment📁 GCP Storage & Hosting🔥 Firebase Hosting🗄️ Firestore Setup⚡ Firestore Realtime💾 Cloud SQL Setup📊 GCP Monitoring🔑 GCP Authentication📈 GCP Scaling & Performance⚡ Firebase Functions💰 GCP Cost Optimization
Cloud/Gcp Deployment/Gcp Cost Optimization

💰 GCP Cost Optimization

Introduction

Google Cloud provides tools to monitor, forecast, and optimize your cloud spending. Understanding pricing models and implementing cost management practices prevents unexpected bills while maintaining performance.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • GCP pricing models for different services
  • Cost monitoring and budgets
  • Committed Use Discounts (CUDs)
  • Right-sizing resources
  • Idle resource cleanup
  • Cost allocation and tagging

Understanding GCP Pricing

Service Pricing Models

ServicePricingBest For
Compute EnginePer minute runningAlways-on workloads
Cloud RunPer 100ms CPU + requestsVariable load
App EnginePer instance hourWeb apps
Cloud StoragePer GB storedLong-term storage
FirestorePer read/write/deleteReal-time apps
Cloud SQLPer instance hourRelational databases

Monitoring Costs

Set Up Budget Alerts

# Create budget
gcloud billing budgets create my-budget \
  --billing-account=ACCOUNT_ID \
  --display-name="Monthly Budget" \
  --budget-amount=100 \
  --threshold-rule=percent=50,percent=80,percent=100

View Cost Breakdown

# Get spending by service
gcloud billing accounts describe ACCOUNT_ID

# View detailed costs
gcloud billing accounts list

Cost Management Dashboard

# Export costs to BigQuery
gcloud billing accounts update ACCOUNT_ID \
  --bigquery-dataset-id=billing_export

Committed Use Discounts (CUDs)

Understanding CUDs

CommitmentDiscountBest For
1 Year25%Known workloads
3 Year52%Stable workloads

Purchase CUDs

# For Compute Engine
# 1. Go to Billing → Commitments
# 2. Click "Purchase Commitment"
# 3. Select machine type, region, commitment term
# 4. Review and purchase

Right-Sizing Resources

Analyze Machine Usage

# Get recommendations
gcloud compute instances describe instance-name \
  --zone=us-central1-a

# Check CPU utilization
gcloud monitoring time-series list \
  --filter='resource.type=gce_instance AND metric.type=compute.googleapis.com/instance/cpu/utilization'

Downsize Overprovisioned Machines

# Instead of n1-standard-4 (4 vCPU, 15GB RAM)
# Use e2-standard-2 (2 vCPU, 8GB RAM) if utilization is low

# Change machine type (requires stop)
gcloud compute instances stop instance-name --zone=us-central1-a

gcloud compute instances set-machine-type instance-name \
  --machine-type=e2-standard-2 \
  --zone=us-central1-a

gcloud compute instances start instance-name --zone=us-central1-a

Optimizing Storage Costs

Use Appropriate Storage Classes

Cloud Storage:

# Standard (for frequent access)
gsutil -D cp -r ./website/* gs://active-bucket/

# Archive (for 1+ year storage, save 80%)
gsutil -D cp -r ./backups/* gs://archive-bucket/

# Lifecycle transition
gsutil lifecycle set - gs://my-bucket << 'EOF'
{
  "lifecycle": {
    "rule": [
      {
        "action": {"type": "SetStorageClass", "storageClass": "ARCHIVE"},
        "condition": {"age": 365}
      }
    ]
  }
}
EOF

Database Optimization

# Use Cloud SQL shared-core instances for low workloads
# db-f1-micro (0.6 GB memory) costs ~$12/month

# Use Cloud Datastore for semi-structured data (cheaper than SQL for some cases)
# Firestore per read/write: $0.06 per 100K reads

# For large analytical workloads, use BigQuery

Eliminating Idle Resources

Find Unused Instances

# Get all instances with low CPU
gcloud compute instances list

# Check CPU utilization
gcloud monitoring read-time-series \
  --filter='resource.type=gce_instance AND metric.type=compute.googleapis.com/instance/cpu/utilization AND metric.value <= 0.1'

Delete Unused Resources

# Delete idle instance
gcloud compute instances delete instance-name --zone=us-central1-a

# Delete unused persistent disks
gcloud compute disks list
gcloud compute disks delete disk-name --zone=us-central1-a

# Delete unused snapshots
gcloud compute snapshots list
gcloud compute snapshots delete snapshot-name

Cost Allocation with Labels

# Add labels to instances
gcloud compute instances create my-instance \
  --labels=environment=production,team=backend \
  --zone=us-central1-a

# Filter costs by label
gcloud billing accounts describe ACCOUNT_ID

Optimization Strategies

1. Use Serverless Services

// Cheaper: Cloud Run
gcloud run deploy my-api --image gcr.io/my-project/api

// More Expensive: Compute Engine with 24/7 instance

2. Optimize API Calls

// Bad: Multiple individual requests
for (const id of userIds) {
  const user = await getUser(id);  // 1000 requests
}

// Good: Batch request
const users = await getUsers(userIds);  // 1 request

3. Use Caching

// Reduces read costs in Firestore
const userCache = new Map();

async function getUserCached(userId) {
  if (userCache.has(userId)) {
    return userCache.get(userId);
  }
  
  const user = await db.collection('users').doc(userId).get();
  userCache.set(userId, user.data());
  return user.data();
}

Cost Forecasting

# Export daily costs to monitor trend
gcloud billing accounts update ACCOUNT_ID \
  --bigquery-dataset-id=billing_export

Key Takeaways

  • **Monitor** spending with budgets and alerts
  • **Right-size** resources based on actual usage
  • **Use CUDs** for predictable workloads (25-52% discount)
  • **Leverage** serverless services for variable load
  • **Store** old data in Archive class (80% savings)
  • **Label** resources for cost allocation
  • **Clean up** unused resources regularly

Next Steps

Explore the Cost Management tools in GCP Console, or set up custom reports in BigQuery for detailed cost analysis.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn