AlgoViz

Google Cloud Functions

medium 29 min

Google Cloud Functions, called Cloud Run functions since August 2024, runs one piece of your code when a request or an event arrives.

Video lesson · Chapter 1 of 5

A field photographer publishes a cloud function

0:00 / 4:27

Cloud Run functions in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A function as a service runs code for you without a server that you look after. You write one function, say which request or event starts it, and deploy the source. The platform starts a copy when work arrives and stops it afterwards. AWS Lambda is the best known example; this page is about Google's.

The product was Cloud Functions. Since August 2024 it is named Cloud Run functions, because a function is now a normal Cloud Run service that was built from source. Cloud Functions (2nd gen) became Cloud Run functions. The original lives on as Cloud Run functions (1st gen), with fewer features. Where this page says function, it means the current kind.

Why it exists

Much work in a system is glue: make a small picture when a photo is uploaded, check a webhook, load a row into a table each night. A server for it would wait most of the day. A function costs nothing in computing time while nothing happens, and needs no patching of machines.

Because a function is a container service underneath, you can keep the code when it outgrows the form: raise the memory, split traffic between revisions, or replace the generated container with your own, without moving to another platform.

A short history

  1. 2017, March

    Google Cloud Functions enters beta, according to the product's release notes.

  2. 2018, July

    Cloud Functions reaches general availability on 24 July, with new runtimes for Node.js 8 and Python in beta.

  3. 2022, August

    The second generation becomes generally available. It is built on Cloud Run and Eventarc: longer runs, larger copies and several requests per copy.

  4. 2024, August

    On 21 August Google announces the name Cloud Run functions and lets you deploy a function with gcloud run deploy.

  5. 2026, August

    The tool that upgrades 1st gen functions to Cloud Run functions is generally available since 10 August.

  6. 2026, November

    Runtimes for Python 3.15 and Node.js 26 become generally available on 23 November.

Words to know

HTTP function
Code that answers a web request.
Event-driven function
Code that receives a CloudEvent: something happened, such as a file was stored.
Trigger
The connection from a source of events to your function. Eventarc manages it.
Instance
One running copy of the container.
Concurrency
How many requests one instance may serve at the same time.
Cold start
The wait while a new instance starts and runs your setup code.
Revision
One deployed version of the service. Traffic can be divided between revisions.
Idempotent
Safe to run twice with the same result.

How it works

Step through the idea, or press Play.

Step 1 of 3

Deploy source. Buildpacks make a container image

Understand it

Start here

The puppet booth

Picture a puppet booth in a park. There is no timetable. A coin opens the curtain.

A coin opens the curtain
closed

You write the play. The park decides how many booths to open.

The name

What is it called now?

Old and new names

TodayWasDeploy withNotes
Cloud Run functionsNew since 2024gcloud run deploy with --functionRecommended. Managed as a Cloud Run service
Cloud Run functions, made with the Cloud Functions v2 APICloud Functions (2nd gen)gcloud functions deployWorks as before; can be detached to Cloud Run only
Cloud Run functions (1st gen)Cloud Functions (1st gen)gcloud functions deploy --no-gen2Still supported; an upgrade tool exists

What the first generation lacks

Cloud Run functions1st gen
Requests per instanceUp to 1,0001
HTTP run timeUp to 60 minutesUp to 9 minutes
Runs onCloud RunA Google-internal platform
Traffic between versionsCan be splitCannot
Addressrun.appcloudfunctions.net
Event formatCloudEvents in every languageBackground functions in Node.js, Python, Go and Java
Firebase's Cloud Functions for Firebase is a layer with its own tools on top of the same two generations.

Deploy

From source to a running service

What a deployment does

A developer sends source with gcloud. In our project, the source goes to a Cloud Storage bucket, Cloud Build makes a container image, the image is stored in Artifact Registry, and Cloud Run starts instances from it.
Cloud Build uses buildpacks and the Functions Framework, which turns your function into a small web server.
Python
import functions_frameworkfrom google.cloud import storageclient = storage.Client()          # global: made once per instance@functions_framework.httpdef hello(request):    name = request.args.get("name", "world")    return f"Hello {name[:40]}\n", 200, {"Content-Type": "text/plain"}@functions_framework.cloud_eventdef on_upload(event):    data = event.data    blob = client.bucket(data["bucket"]).blob(data["name"])    print(event["id"], blob.name)
Two entry points. The first answers web requests, the second receives an event when an object is stored.

Because the result is an ordinary container with a web server, you can run it on your own computer with the Functions Framework, and test it with plain HTTP. With automatic base image updates, security patches of the language arrive without a rebuild.

Start it

Triggers

TriggerHow it arrivesTypical use
HTTPDirectly, the caller waitsAPI, webhook
Pub/Sub topicThrough Eventarc as a CloudEventMessages between services
Cloud StorageThrough Eventarc: object stored, deletedPictures, imports
Firestore and other sourcesThrough EventarcReact to a changed document
Audit log entriesThrough Eventarc, for many Google servicesSomething was created
Cloud Scheduler, Cloud TasksThey call it over HTTPTimetable, controlled queue
Several triggers can point to one function. Events of Eventarc Standard may be at most 512 KB.

A picture is uploaded

Users upload a photo to a Cloud Storage bucket. Eventarc delivers an event to the thumbnail function on Cloud Run. The function writes a small picture to a second bucket. Events that keep failing go to a dead-letter topic in Pub/Sub.
The function reads the bucket and the name from the event. The picture itself is not in the event.

An event that is delivered twice

At-least-once delivery. The event ID is the key. If the work may stop halfway, use the ID to make the work itself repeatable, and mark it done at the end.

Delivery by Eventarc Standard

QuestionAnswer
How often?At least once, so duplicates happen
In order?No guarantee
If the function fails?Waits 10 s at first, growing to 600 s, for 24 hours by default
After that?Lost, unless you set a dead-letter topic
Made in the Cloud Run console?One attempt and no retries by default; with gcloud or Terraform retries are on
The last row surprises people. Check the setting of each trigger. For the idea see idempotency and webhooks.

Scale

Instances and concurrency

Cloud Run counts instances from two measures: the number of requests being served, and CPU use. Both aim at 60% by default. A warm instance stays idle for at most 15 minutes. Minimum instances keep some warm; maximum instances put a lid on the growth, 100 per revision unless you change it.

How many instances?

n=⌈r×tc⌉c=1: ⌈600×0.21⌉=120c=20: ⌈600×0.220⌉=6n = \left\lceil \frac{r \times t}{c} \right\rceil \qquad c = 1:\ \left\lceil \tfrac{600 \times 0.2}{1} \right\rceil = 120 \qquad c = 20:\ \left\lceil \tfrac{600 \times 0.2}{20} \right\rceil = 6
Assumptions: 200 requests per second on average, peak is 3x so r = 600, t = 0.2 s each. One request per instance needs 120 and passes the default limit of 100; twenty at once need 6. Real numbers are higher, because the scaler aims at 60%. The decision: code that waits for the network should allow concurrency.

Settings that matter

  • Concurrency

    Default 80 times the vCPUs, at most 1,000. Below one vCPU it must be 1. Lower it for heavy computing.

  • Maximum instances

    Protects databases and your bill. It can be passed for a short while during a spike.

  • Minimum instances

    Avoids most cold starts. You pay for the waiting ones.

  • Startup CPU boost

    More CPU while an instance starts, so setup is shorter.

What slows a request

A request waits up to 3.5 times the usual start time, or 10 s if that is longer.

Protect

The database behind it

Connections at full scale

connections=nmax×p100×10=100015×10=150\text{connections} = n_{max} \times p \qquad 100 \times 10 = 1000 \qquad 15 \times 10 = 150
Assumption: a pool of p = 10 per instance and a database that allows 200 connections. The default limit of 100 instances would ask for 1,000. With a limit of 15, it fits. Choose the limit from the weakest system behind the function.

Functions grow in seconds and databases do not. Besides the limit, put a queue in between: Cloud Tasks and Pub/Sub smooth the rate, and the caller gets an answer before the work is done. See queues and asynchronous communication.

Life cycle

Start, work, idle, stop

The life of an instance

An idle instance may go at any moment, including one kept by the minimum. Nothing in memory is safe.

Four habits

  1. 1

    Reuse in global scope

    Create clients and pools once, outside the handler. Load rarely used parts only when needed.

  2. 2

    Finish before you answer

    With the default billing the CPU is taken away after the reply. Work left in the background stops and may wake up inside another request.

  3. 3

    Clean the temporary folder

    The file system is memory. Files you leave behind use up the memory of the instance.

  4. 4

    Always answer

    A handler that sends no reply runs, and is billed, until the timeout.

Operate

Limits, security and cost

Limits to know

WhatValue
HTTP request time5 minutes by default, up to 60
Event-driven made with the v2 APIUp to 9 minutes
Memory and CPUUp to 32 GiB and 8 vCPU
Request body32 MB
Event size (Eventarc Standard)512 KB
Instances per revision100 by default, can be raised by quota
Services per project and Region1,000, functions included
Start of a containerMust be ready within 4 minutes
Values from Google's quota pages in November 2026.

Run it safely

AreaDo
Who may callRequire the invoker role; open to all only for public pages and webhooks, and check their signature
What it may doIts own service account with few rights, and not the default one
SecretsSecret Manager, never in source or plain settings
NetworkLimit who can reach it; Direct VPC egress for private systems
ReleasesA new revision with a small share of traffic, then more
WatchingError rate, latency, instance count, age of undelivered messages

Cost. With request-based billing, the default, you pay for CPU and memory while requests are served, plus a small price per request. With instance-based billing you pay for the whole life of an instance, and background work is allowed. A function that is busy all day is often cheaper in the second form, or as a committed container. Building, storing images, events and outgoing traffic are billed separately.

Decide

When to choose it, and when not

Choose a function

  • Reacting to files, messages and documents on Google Cloud
  • Webhooks and small APIs
  • Uneven load with quiet times
  • A scheduled job of a few minutes
  • A team that wants to ship source only

Choose something else

  • Steady heavy traffic: a plain service
  • Hours of batch work: Cloud Run jobs, up to 7 days per task
  • Long steps that depend on each other: Workflows
  • Strict low delay for every request, with no warm copies
  • Data kept in memory between requests

Compare

Function, service, job or workflow?

Pick the shape first

Calls from Cloud Scheduler and Cloud Tasks to a function may last up to 30 minutes.

Neighbours

OptionSameDifferentChoose it when
Cloud Run servicePlatform, scaling, billingYou bring a container or a whole appSeveral routes, own base image
AWS LambdaFunction per eventOne request per environment by default, 15 minutesOn AWS
Azure FunctionsFunction per eventBindings, durable orchestration in codeOn Azure
Cloudflare WorkersCode per requestIsolates near the user, small limitsShort work at the edge
KubernetesRuns containersYou run the platformMany services, special needs

Summary

The whole topic in one minute.

You deploy source; Cloud Build and buildpacks make a container; Cloud Run starts as many instances as the requests need, up to a limit, and none when idle. HTTP requests and CloudEvents from Eventarc both arrive as HTTP. Each instance can serve many requests together.

Choose it for glue, webhooks and uneven work on Google Cloud. Make event handlers safe to repeat, cap the number of instances so that a database is not flooded, and move steady heavy load to plain containers.

  • Cloud Functions is now Cloud Run functions; a function is a Cloud Run service built from source.
  • One instance serves many requests: 80 per vCPU by default, up to 1,000.
  • Eventarc delivers at least once, without order, for 24 hours by default. Check whether retries are on.
  • Finish the work before the reply, and make it safe to repeat.
  • Set maximum instances from what the database can bear.
  • Zero when idle; minimum instances buy away most cold starts.

Sources