
Cloud Run functionsAuthorCloudBrum editorial teamLast reviewedReading time~12 minLevelBeginner to advanced
Google Cloud · Compute · Serverless functions (formerly Cloud Functions)
Event-driven code on Google Cloud, with the servers out of sight. Cloud Run functions, the product that used to be called Cloud Functions, takes your function, builds it for you and runs it on Cloud Run, scaling with demand.
On this page (17 sections)
Mind map: Cloud Run functions at a glance
Free to share. The downloaded image includes the CloudBrum link.
Key features (summary)
- HTTP and event triggersA function can answer web requests or react to Pub/Sub messages and to Eventarc events from many Google Cloud sources.
- Built for youYou deploy source code. Google builds it into a container image and runs it on Cloud Run, so you do not write a Dockerfile.
- Scales with demandInstances start as traffic arrives and, with a minimum of zero, disappear when it stops.
- ConcurrencyOne instance can handle several requests at once when you raise the concurrency setting, which helps with cost and cold starts.
- Room to growChoose the memory and CPU a function gets, up to large sizes, and a timeout that for HTTP functions can reach an hour.
- Common languagesNode.js, Python, Go, Java, .NET, Ruby and PHP are supported, using the open-source Functions Framework.
- Per-function identityEach function runs as a service account you choose, and callers need the invoker role unless you allow public access.
- RevisionsEvery deploy creates a revision, so you can roll back or split traffic between versions.
Basic concepts
- Function
- A single entry point in your code that Google runs for each request or event.
- Functions Framework
- An open-source library that turns your function into a small web server, locally and in the cloud.
- Entry point
- The name of the function in your source that Cloud Run functions should call.
- HTTP function
- A function with its own URL that answers web requests and returns a response.
- Event-driven function
- A function that receives a CloudEvent, for example when a message is published or a file is stored. Delivery goes through Eventarc or Pub/Sub.
- Eventarc
- The Google Cloud service that routes events from many sources to your function.
- Service account
- The identity your function runs as. Its roles determine what your code is permitted to do in Google Cloud.
- Invoker role
- The IAM role (roles/run.invoker) a caller needs to call a function that does not allow public access.
- Instance and concurrency
- An instance is a running copy of your function. Concurrency is how many requests one instance handles at the same time.
- Minimum and maximum instances
- A floor that keeps instances warm, and a ceiling that limits scale-out and cost.
- Revision
- An immutable version of the function created by each deploy, which you can roll back to.
- 1st gen and current
- Cloud Functions 1st gen is the older engine, still available as Cloud Run functions (1st gen). New functions normally use the current engine, which is built on Cloud Run.
How to create & configure it
Deploy a function from the Google Cloud console
- Pick a project and enable the servicesChoose or create a project with billing on. Enable Cloud Run, Cloud Build, Artifact Registry and, for events, Eventarc and Pub/Sub.
- Start a new functionOpen Cloud Run in the console and choose Write a function (or create a function from the functions list). Name it and choose a Region close to your users or data.
- Choose the triggerSelect HTTPS for a web endpoint, or an event trigger such as a Pub/Sub topic or a Cloud Storage event. For HTTPS, choose Require authentication unless the function must be public.
- Set resources and scalingPick memory and CPU, the timeout, and the minimum and maximum number of instances. Start small and cap the maximum.
- Choose the service accountCreate a dedicated service account for the function and give it only the roles it needs, rather than using the default one.
- Configure variables and secretsKeep ordinary settings in environment variables, and keep secrets in Secret Manager, referenced from the function.
- Write the code and entry pointUse the inline editor or upload source, pick the runtime, and make sure the entry point matches the function name in your code.
- DeployDeployment builds a container with Cloud Build and stores it in Artifact Registry. Wait for the revision to become ready.
- Test and read the logsCall the URL, or publish a test message, then check Cloud Logging for output and errors.
- Make it repeatableOnce it works, deploy with gcloud or Terraform from a pipeline so test and production match (see the code references).
Tip: use a different service account for each function, and keep the minimum instances at zero until you have measured a real need for warm capacity.
Common issues after configuration
| Symptom | Likely cause | What to check / fix |
|---|---|---|
| Deploy fails during the build | A required API is off, or the build identity lacks a role | Enable Cloud Build and Artifact Registry, check the build service account’s roles and read the build log for the real error. |
| Function failed to start or the container does not listen | Wrong entry point, a syntax error or a missing dependency | Check the entry point name, confirm every package is in the requirements file and test locally with the Functions Framework. |
| 403 Forbidden when you call it | The function needs authentication | Grant roles/run.invoker to the caller (functions on the 1st gen engine use roles/cloudfunctions.invoker), or send a Google-signed identity token. Allow public access only if that is intended. |
| The function times out | Work takes longer than the timeout | Raise the timeout within its limit, or move long work to Cloud Tasks, Workflows or a Cloud Run job. |
| An event function keeps running again and again | Retries are on and the code keeps failing | Fix the error, make the handler idempotent and decide whether retries should be on at all. |
| Slow first request | Cold start | Set a minimum number of instances, trim the package and create heavy clients lazily and once. |
| Out of memory | Memory setting too low | Raise the memory, and check for large files or objects held in memory. |
| Requests fail when traffic spikes | The maximum instance count or a quota is reached | Raise the maximum instances or the quota, and consider a queue between callers and the function. |
| Connections to a private database time out | The function has no route into the VPC | Set up direct VPC egress or a connector, then check firewall rules and that you use the database’s private address. |
| Permission denied reading a secret | The runtime service account cannot access the secret | Grant the function’s service account the Secret Manager Secret Accessor role on that secret. |
| The function ran twice for one Pub/Sub message | Pub/Sub promises at-least-once delivery | Record a unique key before doing the work, or use a write that succeeds only if the item is absent. |
| Image storage keeps growing | Old build images stay in Artifact Registry | Add a cleanup policy to the repository so old images are deleted. |
Use cases: when and where to use it
Good fit
- Web hooks and small HTTP APIs
- Reacting to Pub/Sub messages and Eventarc events
- File processing when something lands in Cloud Storage
- Scheduled jobs through Cloud Scheduler
- Linking Google Cloud services together
- Light data-prep and notification tasks
Consider something else
- Machines you must configure yourself → Compute Engine
- Containers you already package yourself → Cloud Run services
- Long-running or very large jobs → Cloud Run jobs or Batch
- Multi-step flows with waits and retries → Workflows
- Container platforms with full control → Google Kubernetes Engine
Pros: why consider it?
Why teams choose it
- Nothing to provision, and an idle function costs nothing
- Simple deploy from source, no Dockerfile needed
- Runs on Cloud Run, so you can use its features
- Concurrency lets one instance serve many requests
- Fine-grained identity and IAM for each function
- Wide range of event sources through Eventarc
Trade-offs to weigh
- Event-driven functions have shorter time limits than HTTP ones
- The first request after a quiet spell waits for an instance to start
- The product name and generations can confuse older tutorials
- Builds and image storage add small side costs
- Code that is not safe for concurrent requests needs care
- Triggers and settings are specific to Google Cloud
Common threats, vulnerabilities & risks
| Risk | Severity | Why it matters | Mitigation |
|---|---|---|---|
| Public, unauthenticated function | High | Anyone on the internet can run your code and your bill. | Require authentication, grant the invoker role to named callers, and use API Gateway or a load balancer with Cloud Armor for public APIs. |
| Default or over-powerful service account | High | The code can use every permission the account holds, which for defaults is very broad. | Use a dedicated service account per function with only the needed roles. |
| Untrusted input used unsafely | High | Anything arriving in a request or event may be crafted to inject commands or queries. | Validate each field, escape output and pass values to databases as bound parameters. |
| Secrets in environment variables | Medium | A secret in a variable is visible to anyone allowed to view the function’s settings. | Use Secret Manager and grant access per secret. |
| Open ingress | Medium | A function reachable from anywhere widens the attack surface. | Restrict ingress to internal traffic and load balancers where users are not public. |
| Runaway scale and cost | Medium | Loops, retries or floods of requests scale up fast. | Set a maximum instance count, budgets and alerts, and avoid functions that trigger themselves. |
| Vulnerable dependencies | Medium | A compromised package executes with the same service account as your own code. | Scan packages, pin versions and rebuild regularly. |
| Unsupported runtime | Low–Med | Deprecated runtimes no longer get patches. | Watch the runtime deprecation schedule and move to a supported version in time. |
| Sensitive data in logs | Low–Med | Detailed logging can capture personal data or secrets. | Log request IDs rather than whole payloads, and limit how long logs are kept. |
Performance optimisation
- Create heavy clients lazily and once. Build database and API clients on first use and keep them for later requests on the same instance.
- Use concurrency when your code is safe for it. One instance serving several requests lowers cold starts and cost.
- Keep warm capacity where users feel it. A minimum number of instances removes most cold-start waits.
- Keep the package small and avoid loading libraries you do not use on every start.
- Right-size CPU and memory. More resources can shorten a run, so measure before settling.
- Run close to your data. Choose the Region of your database and storage.
- Keep HTTP answers quick. Acknowledge fast and hand slow work to Pub/Sub, Cloud Tasks or Workflows.
- Tune event handling. Set sensible retry behaviour and keep handlers short so events do not pile up.
Reduce monthly cost
FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Cloud Run functions.
- Keep minimum instances at zero unless latency really demands warm capacity.
- Use concurrency. Serving many requests per instance can lower the compute bill for I/O-heavy code.
- Set a maximum. A ceiling keeps both the bill and the systems behind the function safe from a surge.
- Right-size memory and CPU. Pay only for resources the function really needs.
- Choose the billing mode that fits. Request-based billing suits spiky traffic, and instance-based billing can win for steady, busy functions.
- Trim the event stream. Filter in Eventarc or Pub/Sub and batch where you can, so the function wakes only for real work.
- Clean up builds. Add Artifact Registry cleanup policies so old images do not accumulate.
- Watch the neighbours. Logging volume, networking, egress and the services the function calls can cost more than the function.
- Use the free tier wisely and remember it is shared across the billing account.
- Set budgets and alerts in Cloud Billing, and label each function with its team and product.
Prices and free-tier amounts depend on Region, billing mode and generation, and Google revises them. Look up the live figures before you commit (see Pricing).
Security optimisation
- Run each function as its own service account with least-privilege roles, never the broad default account.
- Keep functions private by default: require authentication and grant roles/run.invoker only to named callers.
- Restrict ingress to internal traffic or a load balancer, and put API Gateway or Cloud Armor in front of public APIs.
- Store secrets in Secret Manager and grant access secret by secret.
- Validate input and assume any field in a request or event could be hostile.
- Use VPC connectors or direct VPC egress with firewall rules for private resources, and control outbound traffic.
- Scan dependencies and images, pin versions and rebuild often; consider Binary Authorization where policy requires it.
- Upgrade runtimes before they are deprecated, and remove functions nobody calls.
- Use Cloud Audit Logs and Cloud Logging, and alert on errors, denied calls and unusual spikes.
- Apply organisation policies to limit ingress, VPC egress and who can deploy.
Governance & compliance
Guardrails
- A labelling rule: owner, environment and cost-center on every function
- Organisation policies for allowed ingress and VPC egress settings
- IAM roles that separate who can deploy from who can call
- Budgets and quotas that keep the number of functions in check
Policy constraints to review
- “constraints/cloudfunctions.allowedIngressSettings”
- “constraints/cloudfunctions.allowedVpcConnectorEgressSettings”
- “constraints/cloudfunctions.requireVPCConnector”
- Cloud Run policies such as “constraints/run.allowedIngress” for the underlying service
Constraint names and which ones apply depend on the function generation, so check the current organisation policy list. For audit evidence, Cloud Audit Logs record who changed what, Security Command Center lists findings, and the Compliance reports manager supplies Google’s compliance reports. Google’s attestations cover the underlying platform; the function’s code, service account, data and configuration still have to be secured, and evidenced, by you.
Reduce carbon footprint
- Leave minimum instances at zero so an idle function consumes no compute.
- Use concurrency to serve more requests with fewer instances.
- Right-size resources and make each run efficient.
- Filter and batch events to avoid needless wake-ups.
- Run in lower-carbon Regions where latency, cost and data location permit; Google publishes carbon data for each Region.
- Delete unused functions and old images.
- Measure it. Carbon Footprint in the Google Cloud console estimates emissions from your usage, so confirm what it covers for your account.
Pricing
Purchase options
Request-based billing Spiky
Pay per request plus the CPU and memory used while requests are handled, with nothing charged while the function is idle.
Instance-based billing Steady
Pay for the CPU and memory of an instance for its whole lifetime. Can cost less for busy functions that are rarely idle.
Monthly free tier Free
A standing free amount of requests and compute applies each month, shared across the billing account. The pricing page lists the present allowance.
Committed use discounts Commit
Commit to steady spend for lower rates where your usage and Region qualify.
What you actually pay for
- Requests, plus vCPU-seconds and GiB-seconds of compute
- Minimum instances, which are billed while they are idle
- Builds in Cloud Build and image storage in Artifact Registry
- Logging, networking, VPC connectors and data transfer out
- The services your function calls: Pub/Sub, Firestore, Secret Manager and others
Regions and billing modes price differently, and Google updates rates over time. Current figures are on the official Cloud Run pricing page (it covers Cloud Run functions too) and in the Google Cloud pricing calculator. The older 1st gen engine has its own price list.
Important code references
A small function that saves each order from a Pub/Sub topic to Firestore with a create-if-absent write, so a repeated message does no harm. The gcloud and Terraform tabs deploy it; the Python and C# tabs hold the function. Replace the placeholder names and the project with your own.
# Enable the services a function deployment uses (once per project)
gcloud services enable run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com \
eventarc.googleapis.com pubsub.googleapis.com firestore.googleapis.com
# A topic, and a service account for the function to run as
gcloud pubsub topics create orders
gcloud iam service-accounts create orders-fn --display-name "Orders function"
gcloud projects add-iam-policy-binding my-project \
--member "serviceAccount:orders-fn@my-project.iam.gserviceaccount.com" --role roles/datastore.user
# Deploy from the folder that holds main.py and requirements.txt
gcloud functions deploy orders-processor \
--gen2 \
--region asia-south1 \
--runtime python313 \
--source . \
--entry-point handle_order \
--trigger-topic orders \
--service-account orders-fn@my-project.iam.gserviceaccount.com \
--memory 512Mi \
--timeout 120s \
--min-instances 0 \
--max-instances 20 \
--retry \
--set-env-vars ENVIRONMENT=dev
# Publish a test message, then read the latest logs
gcloud pubsub topics publish orders --message '{"order_id": "A1", "total": 12.5}'
gcloud functions logs read orders-processor --gen2 --region asia-south1 --limit 20
# For an HTTP function that only permitted callers may use, deploy with --trigger-http --no-allow-unauthenticated
# and grant roles/run.invoker on the function to each caller
# Assumes a Pub/Sub topic (google_pubsub_topic.orders) and a storage bucket for the source zip (google_storage_bucket.source) are defined elsewhere
resource "google_service_account" "orders_fn" {
account_id = "orders-fn"
display_name = "Orders function"
}
resource "google_project_iam_member" "orders_fn_firestore" {
project = "my-project"
role = "roles/datastore.user"
member = "serviceAccount:${google_service_account.orders_fn.email}"
}
data "archive_file" "src" {
type = "zip"
source_dir = "${path.module}/src"
output_path = "${path.module}/src.zip"
}
resource "google_storage_bucket_object" "src" {
name = "orders-processor-${data.archive_file.src.output_md5}.zip"
bucket = google_storage_bucket.source.name
source = data.archive_file.src.output_path
}
resource "google_cloudfunctions2_function" "orders" {
name = "orders-processor"
location = "asia-south1"
build_config {
runtime = "python313"
entry_point = "handle_order"
source {
storage_source {
bucket = google_storage_bucket.source.name
object = google_storage_bucket_object.src.name
}
}
}
service_config {
available_memory = "512Mi"
timeout_seconds = 120
min_instance_count = 0
max_instance_count = 20
service_account_email = google_service_account.orders_fn.email
environment_variables = {
ENVIRONMENT = "dev"
}
}
event_trigger {
trigger_region = "asia-south1"
event_type = "google.cloud.pubsub.topic.v1.messagePublished"
pubsub_topic = google_pubsub_topic.orders.id
retry_policy = "RETRY_POLICY_RETRY"
}
labels = {
env = "dev"
owner = "platform-team"
}
}
# main.py (requirements.txt: functions-framework, google-cloud-firestore)
import base64
import json
import logging
from functools import lru_cache
import functions_framework
from google.api_core.exceptions import AlreadyExists
from google.cloud import firestore
@lru_cache(maxsize=1)
def orders():
"""Created on first use, then reused by later requests handled by the same instance."""
return firestore.Client().collection("orders")
@functions_framework.cloud_event
def handle_order(cloud_event):
# An error raised here makes Pub/Sub deliver the message again, because the function was deployed with --retry
message = cloud_event.data["message"]
order = json.loads(base64.b64decode(message["data"]))
try:
orders().document(str(order["order_id"])).create(order)
except AlreadyExists:
logging.info("order %s was already saved", order["order_id"]) # a repeated message is harmless
// dotnet add package Google.Cloud.Functions.Framework
// dotnet add package Google.Events.Protobuf
// dotnet add package Google.Cloud.Firestore
using System.Text.Json;
using CloudNative.CloudEvents;
using Google.Api.Gax;
using Google.Cloud.Firestore;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.PubSub.V1;
using Grpc.Core;
using Microsoft.Extensions.Logging;
namespace OrdersProcessor;
public class Function : ICloudEventFunction<MessagePublishedData>
{
// Created on first use, then reused by later requests handled by the same instance
private static readonly Lazy<CollectionReference> Orders =
new(() => FirestoreDb.Create(Platform.Instance().ProjectId).Collection("orders"));
private readonly ILogger _logger;
public Function(ILogger<Function> logger) => _logger = logger;
public async Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
{
// An error thrown here makes Pub/Sub deliver the message again, because the function was deployed with --retry
using var doc = JsonDocument.Parse(data.Message.TextData);
var orderId = doc.RootElement.GetProperty("order_id").GetString()!;
try
{
await Orders.Value.Document(orderId).CreateAsync(new Dictionary<string, object> { ["body"] = data.Message.TextData }, cancellationToken);
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.AlreadyExists)
{
_logger.LogInformation("order {OrderId} was already saved", orderId);
}
}
}
Best videos to explore
Short walkthrough videos for this service are being prepared. They will appear here and load only when you press play. Until then, follow CloudBrum on YouTube for new videos.
Interview questions
BasicWhat are Cloud Run functions?
Cloud Run functions is Google Cloud’s serverless functions service. You deploy a function, Google builds and runs it on Cloud Run, and it scales with demand. It answers HTTP requests or reacts to events such as Pub/Sub messages.
BasicHow is it related to Cloud Functions?
It is the same product under a new name. Google renamed Cloud Functions (2nd gen) to Cloud Run functions in 2024. The older engine is still available as Cloud Run functions (1st gen), so older tutorials may use either name.
BasicWhat are the two kinds of function?
HTTP functions have their own URL and return a response. Event-driven functions receive a CloudEvent, for example from Pub/Sub or Cloud Storage, and have no direct caller waiting for an answer.
IntermediateHow does concurrency change the way you write a function?
With concurrency above one, an instance handles several requests at once, so shared state must be safe for parallel use and global variables must not hold request-specific data. In return you need fewer instances, which lowers cost and cold starts.
IntermediateHow do you control who can call a function?
Keep it private and grant roles/run.invoker to the callers that need it, who then send a Google-signed identity token. For public APIs put API Gateway or a load balancer with Cloud Armor in front, and restrict ingress.
IntermediateWhat happens when an event-driven function fails?
If retries are enabled the event is delivered again until it succeeds or expires, which means your code must be idempotent. Without retries the event is dropped. For Pub/Sub you can add a dead-letter topic for messages that keep failing.
AdvancedHow would you reduce cold starts for a user-facing function?
Set a minimum number of instances, raise concurrency, keep the package small, create heavy clients lazily and once, and avoid slow work at start-up. Measure with real traffic, because minimum instances are billed while idle.
AdvancedHow would you run a function every night at 02:00 without leaving it open to the internet?
Deploy it as a private HTTP function with no public access, create a Cloud Scheduler job that calls it on a cron schedule, and run the job as a service account that holds roles/run.invoker on the function. Scheduler then sends a signed identity token, so only that job can call it.
AdvancedWhen would you choose Cloud Run services instead of Cloud Run functions?
When you want to bring your own container, run a web framework with several routes, need a different language version or system packages, or need more control over start-up and traffic. Functions suit single-purpose handlers that you want built for you.
Similar or alternative services on other clouds
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Service | AWS Lambda | Azure Functions | Cloud Run functions |
| HTTP endpoint | Function URL, API Gateway | HTTP trigger, API Management | HTTP function, API Gateway |
| Event sources | SQS, SNS, EventBridge, S3, Kinesis | Queue Storage, Service Bus, Event Grid, Event Hubs | Pub/Sub, Eventarc, Cloud Storage |
| Multi-step workflows | Step Functions | Durable Functions | Workflows |
| Warm capacity | Provisioned concurrency, SnapStart | Always ready instances, Premium plan | Minimum instances |
| Longest run | 15 minutes | Depends on the plan: 10 minutes on Consumption, no enforced maximum on Flex and Premium | Longer for HTTP functions than for event-driven ones |
| Billing unit | Requests and GB-seconds | Executions and GB-seconds (Premium by vCPU and memory time) | Requests plus vCPU-seconds and GiB-seconds |
| Local development | AWS SAM CLI | Azure Functions Core Tools | Functions Framework |
Not sure a function is the right size? Compare with Compute Engine for servers you control, Cloud Run services for your own containers, Workflows for multi-step processes and Google Kubernetes Engine for full container orchestration.
Did you find this article helpful?
Your answer helps us improve this page for the next reader.
Sources and further reading
CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.
- Cloud Run functions documentationGoogle Cloud
- Cloud Run pricingGoogle Cloud
- Cloud Run functions quotas and limitsGoogle Cloud
- Cloud Run functions runtimes and supportGoogle Cloud
- Google Cloud Architecture FrameworkGoogle Cloud
- Eventarc documentationGoogle Cloud
- Cloud Run functions Service Level AgreementGoogle Cloud
- gcloud functions deployGoogle Cloud
- Terraform Google provider: google_cloudfunctions2_functionHashiCorp
- Functions Framework for PythonGoogle Cloud
- Functions Framework for .NETGoogle Cloud
