Cloud Functions is GCP’s event-driven serverless compute platform. Functions run in response to events — HTTP requests, Pub/Sub messages, storage changes — and scale automatically from zero to thousands of instances. For lightweight, event-driven tasks, Cloud Functions is simpler than Cloud Run; for containerized apps with custom runtimes, prefer Cloud Run.

Function Types

Type Trigger Use Case
HTTP HTTP requests APIs, webhooks
Event-driven Pub/Sub, GCS, Firestore Background processing
CloudEvents Various GCP services Modern event format

1st Gen vs. 2nd Gen

Feature 1st Gen 2nd Gen (Recommended)
Infrastructure Functions-only runtime Cloud Run underneath
Concurrency 1 request per instance Up to 1000 per instance
Max timeout 9 minutes 60 minutes
VPC access VPC Connector (limited) Direct VPC egress
Min instances Not supported Supported (reduce cold starts)
CPU Fixed with memory Independently configurable

Always use 2nd gen for new production workloads.

Deploy a 2nd Gen Function

  gcloud functions deploy helloHttp \
  --gen2 \
  --runtime=nodejs20 \
  --region=us-central1 \
  --source=. \
  --entry-point=helloHttp \
  --trigger-http \
  --allow-unauthenticated \
  --memory=256Mi \
  --timeout=60s
  

Example function (index.js):

  const functions = require('@google-cloud/functions-framework');

functions.http('helloHttp', (req, res) => {
  const name = req.query.name || req.body?.name || 'World';
  res.json({ message: `Hello, ${name}!`, timestamp: new Date().toISOString() });
});
  

package.json dependencies:

  {
  "dependencies": {
    "@google-cloud/functions-framework": "^3.0.0"
  }
}
  

Configuration and Deployment

  gcloud functions deploy helloHttp \
  --gen2 \
  --runtime=nodejs20 \
  --region=us-central1 \
  --memory=512Mi \
  --cpu=1 \
  --timeout=120s \
  --min-instances=1 \
  --max-instances=100 \
  --concurrency=80 \
  --set-env-vars=ENV=production,LOG_LEVEL=info \
  --set-secrets=DB_PASSWORD=db-password:latest \
  --service-account=web-app@learning-gcp-dev.iam.gserviceaccount.com \
  --vpc-connector=projects/learning-gcp-dev/locations/us-central1/connectors/my-connector \
  --egress-settings=private-ranges-only
  

Event-Driven Triggers

Pub/Sub Trigger

  gcloud functions deploy processOrder \
  --gen2 \
  --runtime=python312 \
  --region=us-central1 \
  --entry-point=process_order \
  --trigger-topic=orders \
  --memory=256Mi
  
  import functions_framework

@functions_framework.cloud_event
def process_order(cloud_event):
    data = cloud_event.data
    order_id = data.get("message", {}).get("attributes", {}).get("order_id")
    print(f"Processing order: {order_id}")
  

Cloud Storage Trigger

  gcloud functions deploy resizeImage \
  --gen2 \
  --runtime=nodejs20 \
  --region=us-central1 \
  --entry-point=resizeImage \
  --trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
  --trigger-event-filters="bucket=learning-gcp-dev-uploads"
  

Integration Patterns

Pattern Services Flow
API backend Functions + API Gateway Client → Gateway → Function
Image processing GCS → Functions → GCS Upload triggers resize
ETL pipeline Pub/Sub → Functions → BigQuery Event-driven data load
Webhook handler Functions → Pub/Sub → Cloud Run Receive, queue, process
Scheduled task Cloud Scheduler → Functions Cron-based execution
  # Cloud Scheduler → HTTP function
gcloud scheduler jobs create http daily-cleanup \
  --schedule="0 2 * * *" \
  --uri="https://us-central1-learning-gcp-dev.cloudfunctions.net/cleanup" \
  --http-method=POST \
  --oidc-service-account-email=scheduler@learning-gcp-dev.iam.gserviceaccount.com
  

Cloud Functions vs. Cloud Run

Criteria Cloud Functions Cloud Run
Deployment unit Single function file Container image
Runtime Managed (Node, Python, Go, etc.) Any language in a container
Cold start Faster (smaller) Slightly slower (container)
Max execution 60 min (gen2) 60 min
Best for Event handlers, webhooks Full applications, microservices

Real-World Scenario: Image Upload Pipeline

A photo app processes uploads asynchronously:

  1. Client uploads to GCS bucket via signed URL
  2. GCS finalize event triggers resizeImage function
  3. Function generates thumbnails (small, medium, large)
  4. Thumbnails saved to CDN bucket; metadata written to Firestore
  5. Pub/Sub notification triggers email function for user

Cost: functions run seconds per upload; scale to zero overnight.

Common Mistakes

Mistake Impact Fix
1st gen for production Limited concurrency, VPC Migrate to 2nd gen
No max-instances limit Runaway cost during spikes Set --max-instances
Secrets in env vars Leaked in logs/deploy history Use Secret Manager
Long-running work in function Timeout, wasted compute Offload to Cloud Run or Pub/Sub + worker
No min-instances on latency-critical APIs Cold start delays Set --min-instances=1

Best Practices

  • Use 2nd gen for production workloads (better scaling, VPC access)
  • Keep functions small — offload heavy work to Cloud Run or GKE
  • Store secrets in Secret Manager, reference in deployment
  • Set max instances to control cost during traffic spikes
  • Monitor with Cloud Monitoring and Cloud Trace
  • Use Workload Identity / dedicated service accounts for GCP API access
  • Set appropriate memory — CPU scales with memory allocation
  • Use idempotent handlers for event-driven functions (events may duplicate)

Troubleshooting

Function deployment fails:

  gcloud functions logs read helloHttp --gen2 --region=us-central1 --limit=20
# Check build logs in Cloud Build history
  

Cold start latency:

  # Set min instances
gcloud functions deploy helloHttp --gen2 --min-instances=1 --region=us-central1
# Or increase memory (more CPU)
gcloud functions deploy helloHttp --gen2 --memory=1Gi --region=us-central1
  

VPC connectivity issues: Verify VPC connector exists and --egress-settings matches your target (private-ranges-only vs. all).

“Permission denied” on trigger: Ensure the function’s service account has the required roles (e.g., roles/pubsub.subscriber for Pub/Sub triggers).

Cloud Functions lets you run code in response to events without provisioning or managing servers.

Next: Cloud Monitoring — metrics, logs, alerts, and SLOs.