Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 45 ยท Compute

Cloud Run Functions

Learn Cloud Run functions on Google Cloud: HTTP and event triggers, CloudEvents, the Functions Framework and cold starts, with a runnable mini framework.

Sometimes you do not want a whole web app, only a small piece of code that runs when something happens: a file lands in a bucket, a message arrives, or someone calls a URL. Cloud Run functions (the product formerly called Cloud Functions) are for exactly that. You write one function; Google builds it into a container, runs it on Cloud Run and scales it for you.

You pay only while the function runs, and it scales to zero when idle. This lesson covers the two kinds of function, how events reach your code, the open-source Functions Framework behind it, and why the first call after a quiet period can be slow.

Two kinds of function

HTTP or event?

HTTP function Gets a request, returns a response. Has its own URL.
Event function Reacts to a CloudEvent from a service like Pub/Sub or Storage.

Same platform, different trigger.

1 / 2

An HTTP function receives a request and sends a response, like a tiny web endpoint. An event-driven function is invoked by Google Cloud when something happens, such as a new object in Cloud Storage or a message on a Pub/Sub topic. The event arrives in the CloudEvents format, an open specification for describing events with common fields: id, source, type, time and a data payload.

Here are both kinds in Node.js with the open-source @google-cloud/functions-framework package (read-only; it needs npm and a deployment):

JavaScript
const functions = require("@google-cloud/functions-framework");

// HTTP trigger
functions.http("helloHttp", (req, res) => {
  const name = req.query.name || "world";
  res.status(200).send(`Hello, ${name}!`);
});

// CloudEvent trigger (for example a Pub/Sub message)
functions.cloudEvent("onUpload", (cloudEvent) => {
  console.log("Event type:", cloudEvent.type);
  console.log("Data:", JSON.stringify(cloudEvent.data));
});

Python and other runtimes have the same idea with different syntax: you register a function under a name and the platform calls it.

Deploying and triggering

You deploy by naming the function entry point and the trigger:

Terminal
# HTTP function
gcloud functions deploy hello-http \
  --gen2 --runtime=nodejs22 --region=us-central1 \
  --source=. --entry-point=helloHttp \
  --trigger-http --no-allow-unauthenticated

# Event function reacting to a Pub/Sub topic
gcloud functions deploy on-upload \
  --gen2 --runtime=nodejs22 --region=us-central1 \
  --source=. --entry-point=onUpload \
  --trigger-topic=uploads

As with Cloud Run, HTTP functions are best kept private with --no-allow-unauthenticated unless they must be public; callers then present an identity token. Give each function its own service account with only the roles it needs.

Delivery of events is generally at least once. Your function may sometimes receive the same event twice, so write it to be idempotent: processing the event again must not cause a second charge, a second email or a duplicate row. A useful technique is to store the event id and skip IDs you have seen.

The Functions Framework

The Functions Framework is a small open-source library that turns your function into a real HTTP server. It is what runs inside the deployed container, and you can run it on your laptop too:

Terminal
npx @google-cloud/functions-framework --target=helloHttp
# then open http://localhost:8080/?name=Ana

For event functions, the framework turns an incoming HTTP request into a CloudEvent object and calls your function with it. This is why local testing is easy: you do not need the cloud to try your code.

A mini framework

This stand-in is not Google's library. It imitates the shape: register functions by name, dispatch HTTP calls and events, and treat each function as a handler that returns a result. It is pure JavaScript and runs on Piston without any network.

Node.js Stand-in: a tiny Functions Framework

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The duplicate is skipped because the function remembers event IDs. In production, the "memory" must live outside the function, for example in Firestore, because separate instances do not share variables.

Cold starts

A cold start happens when a request or event arrives and no instance is ready. The platform has to start a container, load your runtime and run your top-level code before it can call the function. Later calls on the same instance are warm and skip that work. The delay varies with language, package size and what your top-level code does.

How to keep cold starts small:

  • Keep dependencies few and lazily load heavy ones.
  • Create clients (a database connection, an API client) once at module level so warm calls reuse them, but do not do expensive work you might not need.
  • Set a minimum instances value for latency-sensitive functions. It costs money while idle.
  • Keep each function focused; a function with a huge dependency tree starts slower.

Seeing the cold-start effect

This model charges a fixed startup cost for a new instance and a small per-call cost afterward. The numbers are invented for the demonstration. They show the pattern of one slow call followed by fast ones, and how an idle gap brings it back.

JS Stand-in: cold and warm calls

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Calls at 0 s and 1200 s are cold, because the instance had been idle longer than the limit. Setting one minimum instance would make every call look like the warm ones.

When to use a function

Functions suit glue code: resizing an image, forwarding a webhook, reacting to a queue message, a scheduled cleanup. If you have a full application with many routes, a container on Cloud Run is simpler to grow. Both run on the same infrastructure, so you can move between them.

Benefits and typical jobs

Why teams choose functions: there is no server to manage, they scale from zero to many instances automatically and back to zero, you pay only while code runs, they are easy to reach (an HTTPS URL and a deploy command), and because functions are small and use open languages and the open-source Functions Framework, the code is portable, which limits lock-in. The same function can run on your laptop or in a container elsewhere.

What they are good for:

  • Automating back-end processes: resize an image when it lands in a bucket, send a welcome email when a user is created, clean up old files on a schedule.
  • Orchestrating workflows: small steps that start from an event and call the next service (Pub/Sub, Workflows).
  • Integrating services: a webhook receiver that turns a third-party event into a Pub/Sub message or a database write.
  • Connecting devices: lightweight endpoints that receive readings from many devices.
  • Glue and flexibility: a few lines to connect two systems that do not speak the same format.

They are a poor fit for long-running or very stateful work, and for latency-critical paths if cold starts matter (see above). For those, Cloud Run or GKE are better.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What format do event-driven functions receive events in?

    Events use the CloudEvents specification, with fields like id, source, type, time and data.
  2. 2. Why should an event function be idempotent?

    Delivery is at least once, so duplicates are possible. Processing twice must not cause duplicate side effects.
  3. 3. Which technique reduces the effect of cold starts for a latency-sensitive function?

    A minimum instance count keeps some instances warm, trading idle cost for lower latency.
  4. 4. What does the Functions Framework let you do?

    It is the open-source library that wraps your function in an HTTP server, in the cloud and on your laptop.

Summary

  • Cloud Run functions run a single function on HTTP requests or CloudEvents and scale to zero.
  • Events can arrive more than once, so make handlers idempotent.
  • The Functions Framework wraps your function in a server and works locally.
  • Cold starts add latency to the first call on a new instance; small dependencies and minimum instances help.
  • Use functions for glue code and Cloud Run services for full applications.

Next: Containers, Artifact Registry and GKE