Skip to main content

Cloud Run functions

Exam guide§2.1

Cloud Run functions is a fully managed, serverless functions-as-a-service (FaaS) platform: you write a single-purpose function, Google builds the container, and it runs with no infrastructure to provision or servers to manage. A function is glue - a connective layer of logic that reacts to an event or an HTTP request and extends other cloud services. It scales automatically and is integrated with Cloud Observability for logging and diagnosis.

Two generations

RecommendedCloud Run functions (2nd gen)Formerly Cloud Functions (2nd gen)Deploys functions as services on Cloud RunTriggered via Eventarc and Pub/SubInherits Cloud Run features: concurrency,longer timeouts, traffic splittingLegacyCloud Run functions (1st gen)Formerly Cloud Functions (1st gen)The original versionLimited event triggersLimited configurability
Cloud Run functions ships in two generations: the current 2nd gen runs your function as a service on Cloud Run, while the original 1st gen offers fewer triggers and less configurability.

Setting up a function

Develop</>Write your function logicGo, Node.js, PythonDeployCloud BuildConsolegcloud CLI / APITriggerHTTP requestor cloud event
Three steps to a Cloud Run function: develop it in a supported language, deploy it with Cloud Build, the Console, or the gcloud CLI, then it runs on an HTTP request or cloud event.

Two types of functions

HTTP functionEvent-driven functionhttps://HTTP TriggerCloud StoragePub/SubFirestoreFirebaseEventarcOther Google Cloud servicesEvent TriggersCODE (function)</>
Cloud Run functions come in two flavors - an HTTP function is invoked directly by an https:// request through an HTTP trigger, while an event-driven function runs when Cloud Storage, Pub/Sub, Firestore, Firebase, Eventarc, or another Google Cloud service fans an event into an event trigger.
  • HTTP functions handle HTTP(S) requests.
  • Event-driven functions handle events from your cloud environment.

HTTP functions

Use an HTTP trigger when you want to invoke a function with an HTTP(S) request. The function is assigned a URL and runs in response to requests to it - a good fit for a webhook or API that handles requests from other services.

To implement one, you write an HTTP handler and register it with the Functions Framework for your language. The handler accepts the request and response arguments, processes the request based on its method, and sends back an HTTP response.

GotchaAuthenticated by default; finish background work first

Requests to HTTP functions require authentication by default - you can choose to allow unauthenticated requests at deploy time. Any background tasks the function creates (threads, processes, Promise objects) must be terminated before the response is sent.

Event-driven functions

Use an event-driven function when it should be invoked automatically in response to an event in your cloud environment. Event triggers are supported for Pub/Sub, Cloud Storage, Firestore, Firebase, and Eventarc sources, plus any Google Cloud service that supports Pub/Sub as an event bus. The exact sources available depend on whether the function is Cloud Run functions or 1st gen. For how each trigger is wired to a service, see the event triggers overview.

You implement an event-driven function as a CloudEvent function or a Background function, depending on your language runtime and generation:

Implementing event-driven functionsCloudEvent functionsBased on the CloudEventsspecification.Registered with theFunctions Framework.Event data is in CloudEventsformat.Used by Cloud Run functions(1st gen) [some runtimes]and Cloud Run functions.Background functionsOlder style event-drivenfunction.Event data is based onevent type.Used by Cloud Runfunctions (1st gen).
Event-driven Cloud Run functions come in two shapes - modern CloudEvent functions carry data in the standard CloudEvents format via the Functions Framework, while older background functions shape their event data by event type and only run on Cloud Run functions (1st gen).

What the 2nd generation adds

Because 2nd-gen functions run on Cloud Run, they gain its scale and rollout controls:

Features of Cloud Run functionsLarger instancesIncreased concurrencyLonger request processingFast rollbacks and traffic splittingExtensibility and portabilityMany more event sourcesStandardized event schemaImproved developer experience
The eight capabilities that Cloud Run functions (2nd gen) gains by running on Cloud Run.

The exact limits behind those features:

NumbersCloud Run functions (2nd gen) limits
  • Instances with up to 32 GB of RAM and 4 vCPUs.
  • Up to 1000 concurrent requests per instance - fewer cold starts and lower latency when scaling.
  • Run-time limit up to 60 minutes for HTTP functions and up to 10 minutes for event-driven functions.
  • A new revision on every deploy - split traffic between revisions or roll back to a prior one.
  • Eventarc triggers from 90+ Google, external SaaS, and custom sources (by publishing to Pub/Sub).
  • Standardized CloudEvents format to simplify event-handling code.
  • Portable: move the function to Cloud Run or Kubernetes.

Features & benefits

Features:Benefits:Local development and testingSeamless authenticationHTTP and event-drivenIntegrates with cloud databasesPortable across standard runtimesAugments existing cloud servicesServerlessAutoscalingObservablePay as you go
What Cloud Run functions does for you (features) and what those features buy you (benefits).
  • Seamless authentication uses service accounts; integration covers Cloud SQL, Bigtable, Spanner, and Firestore.
  • Serverless means Google manages the software and infrastructure - no servers, framework updates, or OS patching - and autoscaling goes from a few invocations a day to millions with no extra work.
  • Pay-as-you-go cost is based on the number of invocations, compute time, and outbound data-transfer fees.

Use cases

Data ProcessingRespond to Cloud Storage events when a fileis created, updated, or deleted. Validate andtransform data, process images, andtranscode videos.APIWebhooks/APIsProcess webhook and API calls originatingfrom external systems that can send HTTPrequests.Mobile device backendDevelop a mobile device backend respondingto events triggered by Firebase, Google'smobile platform for app developers.IoTStream device data into Pub/Sub, and launchCloud Run functions to process, transform,and store data.
Cloud Run functions fit four common event-driven jobs: data processing, webhooks and APIs, mobile backends, and IoT streams.

Language runtimes & source structure

You can develop functions in Node.js, Python, Go, Java, .NET, Ruby, or PHP (specific supported versions are in the Cloud Run functions documentation). Each runtime has required source-layout rules so the platform can locate your function definition:

Source directory structureNode.js.├── index.js├── package.jsonPython.├── main.py├── requirements.txtGo.├── myfunction.go├── go.modRoot of function source directoryBasic directory structure
A Cloud Run function is deployed from a source directory whose root holds the entrypoint file plus its language manifest.
  • Node.js - loads source from index.js at the function root by default; set the main field in package.json to change it. package.json also declares the Functions Framework and any dependencies.
  • Python - loads from main.py at the root; requirements.txt declares the Functions Framework and dependencies.
  • Go - your function must be in a Go package at the project root; go.mod declares the Functions Framework.

Entry point

The entry point is the code executed when the function is invoked. It must be defined in your main file or root package, is a function or a class depending on the language, and is specified when you deploy the function.

Regions

The infrastructure that runs a function is in a specific region, managed by Google to be redundantly available across all zones within that region. Choose a region by latency and availability - generally the one closest to the function's users, while also considering where the other Google Cloud services your app uses are located, since spanning locations affects latency and pricing.

Gotcha1st gen regional availability differs

Cloud Run functions 1st generation has different regional availability from 2nd gen - confirm your target region supports the generation you're deploying.

Recap

DECISIONHTTP function or event-driven function?
Invoke it directly with an HTTP(S) request (webhook, API)HTTP function
React to a Pub/Sub message or Cloud Storage object changeEvent-driven function
React to Firestore / Firebase or many GCP event sourcesEvent-driven function (via Eventarc)
Need Cloud Run scale, concurrency, or traffic splittingCloud Run functions (2nd gen)
Pick this when: match the invocation source