Cloud Functions (Basics)
Google Cloud Functions is a serverless, event-driven execution environment that allows you to run code without managing infrastructure. It is the purest form of “Function as a Service” (FaaS) in the Google Cloud ecosystem.
The Analogy: The Motion-Sensor Floodlight
Think of a motion-sensor floodlight. The light (your code) stays off and consumes no power (costs nothing) until a sensor detects movement (an event). When the sensor is triggered, the light turns on automatically, performs its job, and turns off shortly after the movement stops. You don’t need to keep the light on all night “just in case” someone walks by.
Core Concepts & Best Practices
What & Why
- Event-Driven: Functions respond to triggers from Cloud Storage, Pub/Sub, HTTP requests, or Firebase.
- Zero Administration: Google handles OS updates, security patches, and scaling.
- Cost Optimization: You are billed to the nearest 100ms only when your code is executing.
- Scalability: Functions scale from zero to thousands of concurrent executions automatically.
Comparison: Cloud Functions 1st Gen vs. 2nd Gen
| Feature | 1st Generation | 2nd Generation (Powered by Cloud Run) |
|---|---|---|
| Max Request Duration | 9 Minutes | 60 Minutes (HTTP) / 9 Minutes (Event) |
| Concurrency | 1 request per instance | Up to 1,000 requests per instance |
| Max Memory | 8 GB | 32 GB |
| Triggers | Limited (Pub/Sub, Storage, HTTP) | 90+ Event Sources via Eventarc |
Decision Matrix: When to use Cloud Functions?
If you need to process a file immediately after it is uploaded to Cloud Storage… Then use Cloud Functions.
If you have a containerized web application with complex dependencies… Then use Cloud Run instead.
If you need to run a background task triggered by a message in a queue… Then use Cloud Functions.
Exam Tips: ACE Golden Nuggets
- Statelessness: Functions must be stateless. Do not store data locally; use Cloud Storage or Firestore for persistence.
- Idempotency: Ensure your function can run multiple times with the same input without side effects (critical for retries).
- Deployment: Use
gcloud functions deploy. Remember the--trigger-httpor--trigger-topicflags. - Timeouts: The default timeout is 60 seconds. For the exam, know that the absolute maximum for 1st Gen is 9 minutes.
- Cold Starts: The delay when a function starts from zero. Use “Minimum Instances” to mitigate this (but it increases cost).
Cloud Functions Architecture Flow
- Cloud Storage: Trigger on file upload/delete.
- Pub/Sub: Trigger on message arrival.
- Firestore: Trigger on document changes.
- Heavy Dependencies: Large libraries increase cold start times.
- Global Variables: Use them for caching, but don’t rely on them for state.
- Infinite Loops: A function triggering itself via GCS/PubSub.
- Thumbnail Gen: GCS Trigger -> Resize -> Save back to GCS.
- Webhook: HTTP Trigger -> Process -> Send to Slack/Discord.