GCP Cloud Functions Cheat Sheet
Reference for deploying event-driven and HTTP-triggered serverless functions on Google Cloud Functions.
Python HTTP Function
A minimal HTTP-triggered Cloud Function (2nd gen).
import functions_frameworkfrom flask import jsonify@functions_framework.httpdef hello_http(request): name = request.args.get('name', 'World') return jsonify({"message": f"Hello, {name}!"})
Deploy via gcloud
Deploy an HTTP function and a Pub/Sub-triggered function.
# HTTP-triggeredgcloud functions deploy hello_http \ --gen2 --runtime=python312 --region=us-central1 \ --source=. --entry-point=hello_http \ --trigger-http --allow-unauthenticated# Pub/Sub-triggeredgcloud functions deploy process_message \ --gen2 --runtime=python312 --region=us-central1 \ --source=. --entry-point=process_message \ --trigger-topic=my-topic
Pub/Sub-Triggered Function
React to messages published to a topic.
import functions_frameworkimport base64@functions_framework.cloud_eventdef process_message(cloud_event): data = base64.b64decode(cloud_event.data["message"]["data"]) print(f"Received: {data.decode('utf-8')}")
Trigger Types
Key trigger types to know.
- HTTP Trigger- Invoked directly via an HTTPS endpoint
- Pub/Sub Trigger- Fires when a message is published to a topic
- Cloud Storage Trigger- Fires on object finalize, delete, or metadata update events
- Firestore Trigger- Fires on document create, update, or delete
- Eventarc- Unified eventing backbone routing Google Cloud/Cloud Audit Log events (2nd gen)
1st Gen vs 2nd Gen
Key 1st gen vs 2nd gen to know.
- 2nd Gen- Built on Cloud Run + Eventarc; supports concurrency, longer timeouts (up to 60 min), larger instances
- 1st Gen- Legacy platform, max 9-minute timeout, simpler event model
- Concurrency- 2nd gen functions can handle multiple requests per instance simultaneously
- Cold Start- Latency incurred spinning up a new instance after scale-to-zero
Runtime Service Account & Least Privilege
Assign a dedicated, minimally-scoped service account instead of the default compute SA.
gcloud iam service-accounts create fn-invoker-sa \ --display-name="Cloud Function invoker SA"gcloud projects add-iam-policy-binding my-project \ --member="serviceAccount:[email protected]" \ --role="roles/pubsub.subscriber"gcloud functions deploy process_message \ --gen2 --runtime=python312 --region=us-central1 \ --trigger-topic=my-topic \ --run-service-account=fn-invoker-sa@my-project.iam.gserviceaccount.com \ --no-allow-unauthenticated
Mounting Secret Manager Secrets
Inject secrets as env vars or volumes at deploy time instead of hardcoding them.
gcloud functions deploy hello_http \ --gen2 --runtime=python312 --region=us-central1 \ --trigger-http \ --set-secrets='API_KEY=api-key-secret:latest,DB_PASS=db-pass-secret:2' \ --set-env-vars='ENV=production'
Concurrency, Min/Max Instances & CPU
Tune scaling and cold-start behavior for 2nd gen functions running on Cloud Run.
gcloud functions deploy hello_http \ --gen2 --runtime=python312 --region=us-central1 \ --trigger-http \ --min-instances=1 \ --max-instances=20 \ --concurrency=40 \ --cpu=1 --memory=512Mi \ --timeout=120s
Retryable Errors in Event-Driven Functions
Raise to trigger Eventarc/Pub-Sub retry with exponential backoff; return normally to ack.
import functions_frameworkfrom google.cloud import firestoredb = firestore.Client()@functions_framework.cloud_eventdef handle_order(cloud_event): order_id = cloud_event.data["message"]["attributes"].get("orderId") try: db.collection("orders").document(order_id).update({"status": "processed"}) except Exception as e: # Raising causes Eventarc to redeliver per the retry policy (max 7 days, # exponential backoff) instead of silently dropping the event. raise RuntimeError(f"transient failure processing {order_id}") from e
Observability & Debugging
Tools for tracing failures across Cloud Functions and their downstream Cloud Run revision.
- Cloud Logging- Structured JSON logs written to stdout/stderr are auto-parsed into severity, trace, and jsonPayload fields
- Cloud Trace- Auto-instruments HTTP and gRPC calls for 2nd gen functions to show end-to-end latency breakdowns
- Error Reporting- Automatically groups uncaught exceptions from function logs into recurring issue clusters
- Execution ID- Unique per-invocation ID (X-Cloud-Trace-Context / execution_id log label) for correlating a single request across logs
- gcloud functions logs read- CLI shortcut to tail recent logs for a specific function without opening the console
- Cloud Monitoring uptime checks- Synthetic HTTP probes against public function endpoints to catch regressions before users do
Prefer 2nd generation Cloud Functions for new projects — they run on Cloud Run under the hood, giving you longer timeouts, larger max instance sizes, and request concurrency that 1st gen doesn't support.