A complete, practical guide for architects and developers: when to pick Cloud Functions vs Cloud Run, end-to-end architecture, secure connectivity to databases, CI/CD, cost optimization, and real-world use cases.
1. Introduction to Serverless Computing on GCP
Serverless computing is an operational model where the cloud provider manages server provisioning, scaling, and runtime. Developers deploy code or containers and pay for execution time and resources used — not idle servers. Key benefits include:
Auto-scaling: scale to zero and up automatically with demand.
Pay-per-use: cost aligns with actual traffic and compute duration.
No infrastructure management: focus on code and business logic.
On Google Cloud Platform (GCP), the main serverless compute offerings are Cloud Functions, Cloud Run, and App Engine. This guide focuses on Cloud Functions and Cloud Run and how they complement each other in modern serverless architectures.
Cloud Functions is GCP's Function-as-a-Service (FaaS) offering — event-driven single-purpose functions that respond to triggers like HTTP requests, Pub/Sub messages, Cloud Storage events, or other platform events. Cloud Functions supports multiple runtimes (Node.js, Python, Go, Java, and more) and is ideal for short-lived tasks and glue logic between services.
Short startup and execution times — best for single-purpose tasks.
Automatic scaling per-trigger concurrency model.
Important note from GCP docs: Cloud Functions (v2) is built on Cloud Run and Eventarc; many users are advised to consider Cloud Run functions for advanced control.
3. Overview of Google Cloud Run
Cloud Run is a fully-managed container-based platform that runs stateless HTTP-driven containers. It is built on top of Knative and provides a serverless container runtime: you bring any container and Cloud Run handles provisioning, autoscaling (including scale-to-zero), and ingress.
Cloud Run is ideal for microservices, multi-endpoint APIs, and workloads needing custom runtimes or persistent language/process state for the duration of a request. Cloud Run allows you to configure concurrency, min/max instances, and memory/CPU per revision.
GCP documentation: Cloud Run is described as a fully managed application platform to run containers invocable via requests or events.
4. When to Use Cloud Functions vs Cloud Run
Choose between the two based on workload characteristics:
Criteria
Cloud Functions (FaaS)
Cloud Run (Containers)
Deployment model
Upload function code
Deploy container image
Best for
Single-purpose event handlers, quick glue code
APIs, long-running requests, custom runtimes
Control
Less control over runtime
Full control of container environment
Startup model
Optimized for small cold starts
Flexible — can tune min instances to reduce cold starts
Scaling
Automatic per event
Automatic, configurable concurrency and min-instances
Decision quick-check:
If you need event-driven, tiny tasks — pick Cloud Functions.
If you require custom binaries, multiple endpoints, or want to reuse local Docker workflows — pick Cloud Run.
Note: Google has been integrating functions into Cloud Run (Cloud Run functions) and recommends considering Cloud Run for unified capabilities.
5. Architecture of a Serverless Application on GCP
A typical serverless application on GCP has the following layers:
Service-to-service authentication using Workload Identity or service account keys is recommended rather than unauthenticated endpoints.
10. Using Pub/Sub for Event Communication
Pub/Sub is the recommended message bus for decoupling microservices and building asynchronous, scalable architectures. Use topics for events (e.g., image.uploaded) and subscriptions consumed by Functions or Cloud Run subscribers.
Serverless services (Cloud Run / Cloud Functions) do not live inside your VPC by default. To access private databases (e.g., Cloud SQL via private IP), configure a Serverless VPC Access connector or use Cloud SQL Auth proxy or Cloud SQL connectors.
Docs and codelabs show how to connect Cloud Run to Cloud SQL and how to configure Serverless VPC Access.
Best practices
Use connection pooling (e.g., PgBouncer) for relational databases to avoid connection storms.
Prefer Cloud SQL connection pools or the Cloud SQL Auth proxy / connectors for credential management.
Use regional deployments for low latency between Cloud Run/Functions and Cloud SQL.
12. Securing Serverless Applications
Security is multi-layered. Key controls:
Cloud IAM roles — least privilege for service accounts.
Service-to-service authentication — use Workload Identity and short-lived tokens; avoid embedded static keys.
Secret Management — store credentials and API keys in Secret Manager and grant access only to necessary service accounts.
Network controls — Serverless VPC connectors for private database access; private services where required.
Identity-Aware Proxy (IAP) — optional for controlling web access to services behind an auth gate.
Audit logs — keep Audit Logging enabled for critical services and use log sinks for long-term retention.
Always rotate service account keys and use short-lived tokens wherever possible.
13. Managing Environment Variables and Configuration
Use environment variables for non-sensitive configuration. For secrets (DB passwords, API keys), use Secret Manager and bind access to service accounts. Cloud Run supports direct Secret Manager integration; Cloud Functions can read secrets at runtime.
# Example: set env var on Cloud Run
gcloud run services update my-api --set-env-vars=NODE_ENV=production
Avoid storing secrets in repo or inline configuration. Use Parameter Store / Secret Manager and give only required roles.
14. Monitoring, Logging, and Tracing
Use GCP's observability suite:
Cloud Logging — centralized logs (structured logs help searchability).
Cloud Run supports revisions (immutable deploy snapshots). Use revisions for canary releases and traffic splitting (e.g., 90% v1, 10% v2). For Cloud Functions, manage versions via source control and staged deployments.
# Example: split traffic between revisions
gcloud run services update-traffic my-api --to-revisions my-api-00001=90,my-api-00002=10 --region=us-central1
Design rollback strategies: automated health checks + scriptable rollback using gcloud or CI/CD pipelines.
17. Cost Optimization Techniques
Serverless helps reduce baseline costs, but optimization matters:
Right-size memory/CPU per service — don’t over-allocate.
Use min-instances on Cloud Run only for latency-sensitive endpoints to balance cold starts vs cost.
Set appropriate timeouts to prevent runaway charges.
Monitor usage with Billing Alerts and Cost Explorer.
For heavy persistent workloads, compare Cloud Run vs GKE for cost trade-offs.
18. Handling Cold Starts and Performance Optimization
Cold starts occur when instances spin up from zero. Mitigation strategies:
Use min-instances on Cloud Run to keep some warm capacity.
Reduce package size and dependency initialization time for functions and containers.
Prefer faster runtimes for latency-critical endpoints.
Use connection pooling and lazy initialization for DB clients.
Trade-off: min-instances increases cost slightly but improves latency predictability.
19. Real-World Use Cases
Image processing pipeline
Flow: User uploads image to Cloud Storage → Cloud Function triggers → publish to Pub/Sub → Cloud Run job consumes message and runs processing (resize, watermark), writes back to Cloud Storage.
REST API
Cloud Run hosts a REST API (multiple endpoints) with autoscaling and canary releases; use Cloud Armor for WAF-style protections and IAP for internal APIs.
IoT event ingestion
Devices push telemetry to Pub/Sub → Cloud Functions validate and write to Pub/Sub or BigQuery for analytics.
Chatbot backend
Use Cloud Run for conversational backends integrated with Firestore for session state. Consider GenAI/ML inference deployed in containers on Cloud Run for scalable inference.
20. Best Practices and Future Trends
Event-driven design: decouple services with Pub/Sub for resiliency and scalability.
Observability-first: instrument logs, metrics, and tracing from day one.
Security-first: use least-privilege service accounts and Secret Manager.
Design for idempotency: event replays can cause duplicate messages.
Adopt container-first mindset: Cloud Run provides greater portability and rapid feature growth.
Emerging trends: tighter Cloud Run + Functions integration (Cloud Run Functions), serverless connectors for easier VPC access, and GenAI integration in serverless workflows (embedding inference in containers). Keep an eye on portability via Knative for multi-cloud patterns.
Additional resources & recommended reading
CloudKnowledge — curated tutorials and deep-dives on GCP.
2 responses to “Building a serverless application on GCP with Cloud Functions & Cloud Run”
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.com/zh-TC/register?ref=DCKLL1YD
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.com/zh-TC/register?ref=DCKLL1YD
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.