Cloud Functions in Google Cloud: Run Your Code Without Running Servers

Cloud Functions in Google Cloud: Run Your Code Without Running Servers

A complete, intermediate-level guide to Google Cloud's function-as-a-service platform: how it works inside, how events trigger it, how it scales, how to secure it, and how to avoid the mistakes that hurt real projects.

Think about a vending machine in a train station. Nobody stands behind it waiting for customers. It sits quietly, and the moment someone presses a button, it does exactly one job: it hands over a snack. If a hundred people press buttons at once, you simply place more machines. If nobody comes for a whole night, you pay nothing extra. Cloud Functions in Google Cloud works in the same way, except the snack is a small piece of your own code, and the button is something that happens in your system, such as a file being uploaded or a web request arriving.

In this guide you will learn what that small piece of code really is, where Google runs it, what wakes it up, how many copies can run at once, what it costs to keep it safe and healthy, and when it is the wrong tool. We will go step by step, explain every new word when it first appears, and use everyday comparisons so each idea sticks.

1What Is a Cloud Function?

A cloud function is a small job that Google runs for you, only when something asks for it.

A cloud function is a short piece of code that does one clear job. It might resize a photo, check a payment, send a welcome message, or copy a row of data into another place. You write the code, give it to Google Cloud, and tell Google when it should run. Google takes care of everything else: the computer it runs on, the operating system, the security updates, the network, and the number of copies needed to handle the work.

This style of computing is called serverless. The name can be confusing, because servers still exist. They are simply not your problem. You do not buy them, you do not log in to them, and you do not worry about them at three in the morning. Another name for the same idea is Function as a Service, often shortened to FaaS. You provide the function, and the platform provides the service of running it.

Simple Analogy

When you switch on a lamp, you do not own a power station. You press a switch, electricity flows, and you pay for what you used. A cloud function is the same: you do not own a computer room. Something presses the switch, your code runs, and you pay for the time it was on.

The three things every function needs

Every function in Google Cloud is built from three simple parts. First comes the code, which is the instructions you wrote. Second comes the trigger, which is the thing that wakes the code up. Third comes the configuration, which is the set of choices such as how much memory the code may use, how long it may run, and who is allowed to call it. If you can describe those three parts, you can describe any function.

1 job
each function does one focused task
0 servers
for you to patch, size or restart
Pay per use
you are billed while code actually runs
i
Good to know

Google has been renaming and reshaping this product. Newer documentation calls it Cloud Run functions, while many people still say Cloud Functions. Chapter 3 explains the difference so the names never confuse you again.

Where functions fit in the big picture

Functions are the glue of a cloud system. A bigger application might have a database, a website, a message system, and a storage area for files. Something has to connect these pieces and react when things change. Functions are perfect for that. They sit between your services and say, “When this happens, do that.”

2The Problem Cloud Functions Solve

Before functions, even a tiny job needed a whole computer waiting around for it.

Imagine you want a small program that creates a thumbnail every time someone uploads a picture to your website. In the old days you would need to rent or buy a server, install an operating system, install your language tools, copy your program onto it, and keep it running day and night. Most of the time nobody uploads anything, yet the server still costs money, still needs updates, and can still break.

Simple Analogy

Owning a server for a tiny job is like buying a car to drive to the shop once a week. The car needs parking, fuel checks, insurance, and repairs even while it sits still. Calling a ride only when you need one is cheaper and simpler. Cloud functions are the ride.

The four pains of always-on servers

Pain 1

Idle waste

You pay for the machine around the clock, even when it does no work at all.

Pain 2

Capacity guessing

Too small and users wait. Too big and money is wasted. Traffic is hard to predict.

Pain 3

Maintenance work

Operating system patches, security fixes and runtime upgrades never stop arriving.

Pain 4

Slow delivery

Setting up machines for each small idea slows teams down and discourages experiments.

How computing grew up to functions

Computing has moved step by step toward doing less manual work. Each step handed another chore to the platform.

1

Physical servers

You buy hardware, fit it in a room, and manage everything from cables to code.

2

Virtual machines

You rent slices of computers in the cloud. No hardware, but you still manage the operating system.

3

Containers

You package your program with what it needs so it runs the same everywhere, and a platform schedules it.

4

Functions

You hand over only the code. The platform builds, places, runs, scales and retires it for you.

Functions are the far end of that journey. You give up some control, such as choosing the operating system, and in return you get speed, simplicity, and a bill that follows real usage.

3Names and Generations: Cloud Functions, Cloud Run Functions, 1st Gen and 2nd Gen

The product has two generations and more than one name, and knowing which is which saves a lot of confusion.

Google first launched Cloud Functions as a simple service with its own special machinery behind it. Later it introduced a new version built on top of two other Google Cloud services: Cloud Run, which runs containers, and Eventarc, which delivers events. The first version is now called 1st gen and the newer one is called 2nd gen. Today, Google’s documentation uses the name Cloud Run functions for the product family, and the 2nd gen design is where new capability arrives.

Simple Analogy

Think of a small shop that grew inside a big shopping mall. The shop is still the same shop with the same owner, but it now shares the mall’s loading docks, security and parking. The 2nd gen function is the shop inside the mall: same idea for you, much stronger foundations underneath.

What actually differs between the generations

Because 2nd gen functions are really Cloud Run services with a friendly wrapper, they inherit Cloud Run’s strengths: bigger machines, longer run times, and the ability to handle many requests at once inside one running copy. The table below shows the differences that matter most.

Topic1st gen2nd gen
Built onIts own original platformCloud Run and Eventarc
Largest memory per instance8 GiB32 GiB
Longest run time540 seconds (9 minutes)Up to 60 minutes for web functions, 540 seconds for event functions, 1800 seconds for scheduled and task-queue functions
Requests per instance at onceOne at a timeMany at once through concurrency
Largest web request10 MB32 MB (non-streaming)
Event deliveryOlder event systemEventarc, with a wide choice of event sources
Default maximum instances for web functionsNo default cap, so setting one is advised100, which can be raised to 1,000
!
Limits change

Numbers like these are updated by Google from time to time. Treat the table as a guide for understanding the design, and always check the official quotas page before you finalise an architecture.

Which one should you choose?

For new work, 2nd gen is the natural choice because it is more powerful and receives the newest features. 1st gen still exists for older projects, and many teams are migrating step by step. A good rule is simple: if you are starting today, start on 2nd gen unless you have a very specific reason not to.

4Core Concepts and Vocabulary

Eleven short definitions that unlock every other chapter.

Before we go deeper, let us fix the words we will keep using. Each card explains a term in plain language. Read them slowly once, and the rest of the guide will feel much easier.

Term 1

Function

Your small piece of code that does one job, such as converting a file or answering a request.

Term 2

Entry point

The exact name inside your code where Google should start when the function is called.

Term 3

Trigger

The thing that wakes the function: a web request or an event from another Google Cloud service.

Term 4

Event

A short message saying that something happened, such as “a file was added to this storage bucket.”

Term 5

Instance

One running copy of your function. Google may run zero, one, or many instances at the same time.

Term 6

Cold start

The short delay when a brand new instance must start before it can handle its first request.

Term 7

Concurrency

How many requests a single instance may handle at the same moment. Available in 2nd gen.

Term 8

Runtime

The language environment your code runs in, such as Node.js, Python, Go, Java, Ruby, PHP or .NET.

Term 9

Service account

The identity your function uses when it talks to other Google Cloud services, like a staff badge.

Term 10

Eventarc

Google’s event delivery service that finds events and routes them to your function.

Term 11

Region

The physical area of the world where your function lives, such as a city-based data centre location.

i
Remember this pair

A trigger decides when your function runs. The configuration decides how it runs. Keep these two ideas separate in your head and design discussions become much simpler.

5Architecture and Components

Behind a few lines of code sits a quiet assembly line of Google Cloud services.

When you deploy a function, you hand Google your source code. You do not hand over a ready-made package. Google builds that package itself, stores it safely, and then runs it. Knowing these steps helps you understand deployment errors, build times, and costs.

flowchart LR
  A["Your source code"] --> B["Cloud Build"]
  B --> C["Artifact Registry"]
  C --> D["Cloud Run service"]
  D --> E["Function instances"]
  F["Trigger or Eventarc"] --> D
  G["IAM and service account"] --> D
        
FIG 1 — From source code to running instances

The assembly line, piece by piece

1

Source upload

Your code and its list of dependencies are uploaded to Google. There are size limits on what a single function deployment may contain.

2

Build with Cloud Build

Google picks a base image for your language, installs your dependencies, and wraps your code with a small library called the functions framework. This turns your plain function into something that can listen for requests.

3

Store in Artifact Registry

The finished container image is saved in a private storage area so it can be started again and again, quickly.

4

Serve with Cloud Run

Cloud Run creates a service and a numbered revision for your function, then starts instances from the image when traffic or events arrive.

5

Connect triggers

For event functions, Eventarc is set up to watch the event source and deliver matching events to the service.

Simple Analogy

Deploying a function is like handing a recipe to a bakery chain. The bakery buys the ingredients, bakes the first batch, stores it in a warehouse, and opens a counter. You only wrote the recipe, but a whole supply chain served your customers.

What the functions framework does

Your code does not need to know how to open a network port or parse an internet request. The functions framework does that for you. It receives the incoming call, hands your function exactly the data it expects, and sends your answer back. This is why the same function can feel so short and clean, even though a lot of work happens around it.

Revisions: a safety net for change

Each time you deploy a change, a new revision is created. Older revisions remain recorded. This means traffic can move to the new version and, if something goes wrong, return to the previous one. Think of revisions as saved game checkpoints for your function.

i
Why this matters

Because 2nd gen functions are Cloud Run services underneath, the settings, logs and metrics you learn for one carry over to the other. Learning one tool teaches you two.

6Function Types and Triggers

There are two kinds of functions, and the kind you pick decides how it is woken up.

Every function belongs to one of two families. An HTTP function answers web requests. Someone, or some program, calls a web address and waits for an answer. An event-driven function reacts to something happening inside Google Cloud. Nobody waits for an answer, because the event is simply a notification.

Simple Analogy

An HTTP function is like a shop counter: a customer walks up, asks a question, and waits for the reply. An event-driven function is like a smoke alarm: something changes in the building, the alarm reacts, and nobody stands there waiting for it to answer.

QuestionHTTP functionEvent-driven function
Who wakes it?A caller sending a web requestAn event delivered through Eventarc
Does someone wait for an answer?Yes, the caller waits for a responseNo, the platform only checks success or failure
Typical useWeb hooks, small APIs, form handlersFile processing, message handling, data changes
Retry behaviourThe caller decides whether to try againCan be configured so failed events are tried again

Where events come from

Event-driven functions in 2nd gen rely on Eventarc. It supports messages from Pub/Sub (a message delivery service), changes in Cloud Storage (file buckets), and changes in Firestore (a document database). Eventarc also supports a very wide range of other Google Cloud services through audit logs, with over ninety sources available. That means a function can react when a virtual machine is created, a permission changes, or a dataset is updated.

flowchart LR
  S1["Cloud Storage change"] --> E["Eventarc"]
  S2["Pub/Sub message"] --> E
  S3["Firestore change"] --> E
  S4["Audit log event"] --> E
  E --> F["Event-driven function"]
  W["Web request"] --> H["HTTP function"]
  SC["Cloud Scheduler"] --> H
  T["Cloud Tasks"] --> H
        
FIG 2 — Event sources and web callers that reach a function

HTTP functions can be woken by other services too

An HTTP function is not only for human callers. Cloud Scheduler can call it on a timetable, such as every night at midnight. Cloud Tasks can call it from a waiting line of jobs and can also slow the pace so your function is not overwhelmed. Workflows can call it as one step in a longer process. A Pub/Sub push subscription can also deliver messages to it as web requests.

!
One trigger per function

A single function can only be bound to one trigger at a time. If you want the same event to start three different jobs, deploy three functions with the same trigger settings. Each will receive its own copy of the event.

Event size matters

Events travelling through Eventarc are small notes, not heavy parcels. In 2nd gen the size limit for such an event is 512 KB. This is another reason to put references in events, such as the name of a file, and let the function fetch the large content itself from storage.

7Data Flow and the Life of One Invocation

Follow a single request from the moment it arrives to the moment the answer leaves.

An invocation is one run of your function for one request or one event. Understanding what happens during an invocation explains why some calls are fast, why some are slow, and why some strange bugs appear only under load.

sequenceDiagram
  participant C as Caller
  participant G as Google front door
  participant I as Function instance
  participant D as Downstream service
  C->>G: Send request or event
  G->>I: Route to a ready instance
  Note over I: If none is ready, a new one starts
  I->>D: Read or write data
  D-->>I: Reply
  I-->>G: Return response
  G-->>C: Deliver response
        
FIG 3 — Lifecycle of a single invocation

Step by step

1

The call arrives

A web request or an event reaches Google’s front door. Identity checks happen here: is the caller allowed to invoke this function?

2

An instance is chosen

If a warm instance is free, the call goes straight to it. If not, Google starts a new instance, which causes a cold start.

3

Startup work, only when new

A new instance loads the runtime, loads your code, and runs any setup code placed outside the function body. This work is done once per instance, not once per request.

4

Your function runs

Your code reads the input, talks to other services, and produces a result. It must finish before the configured time limit.

5

The response or acknowledgement leaves

For web functions, the answer goes back to the caller. For event functions, a success signal tells the platform the event was handled.

6

The instance waits, then may be retired

The instance stays warm for a while in case more work arrives. If it stays idle, Google eventually shuts it down and you stop paying for it.

Simple Analogy

A warm instance is a chef who has already tied the apron, lit the stove and laid out the tools. A cold start is hiring a chef, dressing them and heating the kitchen after the first order has arrived. After the first meal, the kitchen stays ready for a while.

!
Finish your work before you answer

Once your function sends its response, the platform may reduce the resources given to that instance. Any background work you left unfinished can slow down or stop. Complete all important tasks before returning the answer.

8Scaling, Concurrency and Cold Starts

Functions grow and shrink on their own, but you still steer how far and how fast.

Automatic scaling is the headline feature of functions. When more requests arrive, Google starts more instances. When requests slow down, it removes instances, even down to zero. You do not press any button to make this happen. What you can do is set boundaries, so scaling stays helpful and affordable.

0 to many
instances follow demand automatically
100
default max instances for 2nd gen web functions
1,000
upper value you can request for that setting

The three dials you control

Dial 1

Minimum instances

Keeps a number of instances always warm. Cold starts nearly vanish, but you pay for idle readiness.

Dial 2

Maximum instances

Puts a ceiling on growth. It protects databases and budgets from a sudden flood of work.

Dial 3

Concurrency

Lets one instance serve several requests at once in 2nd gen, which reduces instance count and cost.

Understanding concurrency

In 1st gen, each instance handles exactly one request at a time. If ten requests arrive together, ten instances are needed. In 2nd gen, one instance can handle many requests together, as long as your code is safe to run that way. This is like a waiter who can serve several tables at once instead of one waiter per table.

The trade-off is that your code must not mix up data between requests. If two requests share a variable that holds “the current user,” they can overwrite each other. Concurrency rewards clean, stateless code.

Simple Analogy

A single-request instance is a taxi that takes one passenger per trip. A concurrent instance is a bus. The bus is cheaper per person, but passengers must not take each other’s bags.

Ways to soften cold starts

A cold start is usually short, but for a user-facing page even a short delay can be felt. Several habits reduce its effect:

  • Keep the package small. Fewer and lighter dependencies load faster.
  • Do heavy setup once. Create connections and load settings outside the function body so warm instances reuse them.
  • Load rarely used parts lazily. Do not load something at startup if only one request in a hundred needs it.
  • Use minimum instances for important, latency-sensitive functions.
  • Choose a lighter runtime when startup speed truly matters.
!
Scaling can hurt your neighbours

A function that scales to hundreds of instances can open hundreds of database connections in seconds. Many databases cannot cope. Always set a sensible maximum, and consider a waiting line such as Cloud Tasks or Pub/Sub to smooth sudden bursts.

9Runtimes, Resources and Configuration

The settings you choose decide how fast, how large and how safe your function is.

Writing the code is only half the job. The other half is deciding the size of the “room” where the code lives. Google Cloud lets you tune several settings, and each one has a trade-off between speed, safety and cost.

Languages you can use

Cloud functions support popular runtimes including Node.js, Python, Go, Java, Ruby, PHP and .NET. The exact versions supported change over time as older versions retire and newer ones arrive. A healthy habit is to review your runtime versions regularly, because running an out-of-support version can leave you without security fixes.

The main settings

Setting

Memory and CPU

More memory and CPU mean faster work but a higher price per second. In 2nd gen, memory can reach 32 GiB per instance.

Setting

Timeout

The longest a single run may last before Google stops it. Choose a value that matches real work, not an extreme one.

Setting

Environment variables

Plain settings such as a project name or mode. They change behaviour without changing code.

Setting

Secrets

Sensitive values like passwords and keys, stored in Secret Manager and attached to the function safely.

Setting

Region

Where the function runs. Pick a region close to users and close to the data the function touches.

Setting

Ingress and egress

Who may reach the function and how the function reaches the outside world. Chapter 10 explains both.

Limits worth knowing

LimitWhat it means
Deployment sizeA single function deployment is limited, roughly 100 MB compressed for sources and 500 MB uncompressed with modules.
Number of functionsEach region allows up to 1,000 functions, shared with Cloud Run services in 2nd gen.
Web request sizeUp to 32 MB in 2nd gen for non-streaming requests.
Event sizeEventarc events are limited to 512 KB.
Project resource capsTotal memory and CPU across a project in a region are capped and can be raised by request.
i
Right-size by measuring

Start with a modest memory size, watch real metrics, and adjust. Guessing high wastes money, and guessing low causes slow runs or crashes. Data beats opinions.

!
Quota surprises

If a project reaches a resource quota, other functions in the same project can suffer too. Keep important production functions in a project that has healthy headroom, and request increases before a big launch.

10Networking and Connectivity

Who can reach your function, and which doors your function may open to the outside.

Networking in functions has two directions. Ingress is traffic coming in to your function. Egress is traffic going out from your function to other places. Each direction has its own controls.

Simple Analogy

Picture an office building. Ingress is the front desk that decides which visitors may walk in. Egress is the phone system that decides which outside numbers staff may call. You can control both separately.

Ingress choices

By default, a function can be reached from the internet at its public address, although whether a caller is allowed is a separate question handled by identity checks. You can narrow the doors. You may allow only traffic from inside your own Google Cloud network, or allow internal traffic plus traffic that arrives through a Cloud Load Balancer. The second choice is popular when you want a custom domain, protection from attacks at the edge, and a single controlled entrance.

Egress and private resources

Some systems you need, such as a database that has no public address, live inside a private network called a VPC (Virtual Private Cloud). A function sits outside that network by default. To reach private resources, you connect the function to the VPC using a serverless connector or the newer direct network egress option. You can also choose to send all outgoing traffic through the VPC so it passes your firewall rules and a fixed outgoing address, which is helpful when a partner only accepts calls from known addresses.

flowchart LR
  U["Internet users"] --> LB["Cloud Load Balancer"]
  LB --> F["Cloud function"]
  F --> V["VPC network"]
  V --> DB["Private database"]
  F --> API["External partner API"]
        
FIG 4 — A function behind a load balancer reaching a private database

Practical networking advice

  • Make functions that serve only internal systems private, so the public internet cannot even knock.
  • Place the function in the same region as the database it talks to, to keep delay low.
  • Remember that private network paths add configuration work, so use them where the data deserves it.
  • Keep outgoing calls short and set time limits on them so a slow partner cannot hold your function hostage.
i
Layers of protection

Network controls and identity controls work together. A closed door and a checked badge are stronger than either alone.

11Security and Identity

Security for functions is mostly about two questions: who may call me, and what may I touch?

Because functions are small and numerous, a team can end up with dozens or hundreds of them. If each one is casually set up, the total risk grows quickly. A few clear habits keep things safe.

Who may call the function

Access to invoke a function is controlled through IAM, Google Cloud’s permission system. A caller must hold an invoker permission for that specific function. For 2nd gen functions this is the Cloud Run invoker role. You may deliberately open a function to the public, for example a public web hook, but this should be a conscious choice and not an accident. For calls between your own services, require the caller to present a signed identity so the receiving function can verify who is knocking.

What the function itself may touch

When a function talks to other Google Cloud services, it uses a service account, which is like a staff badge. The badge carries a list of permissions. By default, functions may use a shared general-purpose badge that is often far too powerful. A much better habit is to create a dedicated service account for each function or each small group of functions, and give it only the exact permissions it needs. This is the principle of least privilege.

Simple Analogy

A hotel does not give every worker a master key. The cleaner gets keys to rooms, the chef gets keys to the kitchen, and the accountant gets keys to the office. If one key is lost, only a small area is at risk.

Protecting secrets

Passwords, tokens and keys must never live inside your code or in plain settings. Store them in Secret Manager and attach them to the function. Secrets are then delivered to the function when it runs, access is recorded in audit logs, and you can rotate a secret without rewriting the code.

More layers you can add

Layer

Customer-managed keys

Use your own encryption keys through Cloud KMS when rules require you to control encryption.

Layer

VPC Service Controls

Draw a protective boundary around sensitive services to reduce the chance of data leaving by mistake.

Layer

Organisation policies

Set rules across all projects, such as banning public functions or forcing certain regions.

Layer

Dependency hygiene

Keep libraries updated and scan them, because most real attacks arrive through outdated packages.

!
Never trust input

Data arriving at a function, whether from a web request or an event, can be wrong or hostile. Check its shape and size before acting on it, exactly as you would for any web application.

12Monitoring, Logging and Metrics

You cannot fix what you cannot see, and functions are easy to forget once they are running.

Because you never log in to a machine, observation happens through Google Cloud’s operations tools. They are built in, so a function starts producing useful signals from day one.

The four views of a healthy function

View 1

Logs

Cloud Logging collects what your function prints, plus platform messages. Structured messages make searching easy.

View 2

Metrics

Cloud Monitoring tracks numbers over time, such as request counts, errors, run time, memory use and instance count.

View 3

Traces

Cloud Trace shows how long each step of a request took across several services.

View 4

Error reports

Error Reporting groups similar failures together so you see one problem instead of ten thousand lines.

Metrics that tell the real story

Invocation count and error rate

Shows how busy the function is and what share of calls fail. A sudden jump in either deserves attention.

Execution time

Watch the slow end of the range, not only the average. A few very slow calls hurt real users even when the average looks fine.

Memory use

If usage stays close to the limit, crashes are near. If it stays tiny, you are paying for memory you do not need.

Instance count and cold starts

Shows how often new instances start and whether scaling is behaving as planned or hitting your maximum.

Alerting that people actually read

Create alerts for the few things that truly matter: error rate rising above a normal level, run time becoming too slow, and failed events piling up. Too many alerts teach teams to ignore all of them. Each alert should say what is wrong and where to look first.

i
Log with purpose

Write messages that include an identifier for the request or event being processed. When something fails at midnight, that single identifier lets you follow the whole story across many functions.

!
Do not log secrets

Logs are widely readable inside a team. Never print passwords, tokens, or private personal data. Mask them before they reach the log.

13Reliability: Retries, Duplicates and Idempotency

Things fail, networks blink, and the same event can arrive twice. Good functions expect all of this.

Event-driven systems usually promise at-least-once delivery. This means an event will be delivered one or more times, but not zero. The promise protects you from lost events, but it also means duplicates are possible. Your function must be built to handle a repeat without causing damage.

Simple Analogy

Imagine ordering a pizza and the delivery driver is not sure you received it, so they bring a second one. If your doorbell rule is “pay for every pizza that arrives,” you pay twice. If your rule is “pay once per order number,” the second pizza changes nothing. The second rule is called idempotency.

What idempotent means

An operation is idempotent when doing it once or doing it many times gives the same final result. Setting a value to “paid” is idempotent. Adding ten rupees to a balance is not. To make a function idempotent, remember what you have already processed, usually by recording the unique identifier of each event or order, and skip anything you have seen before.

Retries: a double-edged tool

For event-driven functions you can choose whether failed events should be tried again. Retrying helps with short problems such as a brief network failure. It hurts when the problem is permanent, because a broken event can be retried again and again, wasting money and filling logs. These repeated failures are sometimes called poison messages.

1

Separate the two kinds of failure

Temporary failures, like a busy service, deserve a retry. Permanent failures, like invalid data, do not.

2

Make the work safe to repeat

Record processed identifiers so duplicates become harmless.

3

Park the hopeless events

Send events that keep failing to a holding area, such as a dead-letter topic in Pub/Sub, so people can inspect them later.

4

Alert on the holding area

A growing pile of parked events is an early warning that something upstream has changed.

“A function that cannot survive a duplicate event is a bug waiting for a busy day.”

Timeouts and partial work

If a function is stopped at its time limit halfway through a job, some work may be done and some not. Break big jobs into smaller steps, save progress as you go, and design every step so it can be repeated safely. Short, repeatable steps are the secret of dependable serverless systems.

!
The endless loop trap

If a function reacts to a file change and then writes a file into the same place, it can trigger itself forever and create a surprise bill. Write results to a different location than the one being watched.

14Design Patterns That Work Well

Five proven shapes that solve most function-based problems.

A design pattern is a tried and tested way of solving a common problem. Functions fit certain patterns especially well because they are small, quick to start, and easy to connect.

Pattern 1: The Event Reactor

Something changes, and a function reacts. A file lands in a bucket, and a function checks it, converts it, or records it. This is the most natural pattern and the best starting point for teams new to functions.

Pattern 2: Fan-Out

One event needs several different jobs. Publish a single message to Pub/Sub, and let several functions, each with its own subscription, do their own work independently. Adding a new job later requires no change to the others.

Pattern 3: The Queue Buffer

Put a waiting line, such as Cloud Tasks or Pub/Sub, between a busy source and a delicate target. The queue smooths bursts so your database or partner service is never overwhelmed.

Pattern 4: The Thin API Facade

A tiny HTTP function accepts a request, checks it, hands the real work to a queue or another service, and answers immediately. Users get fast replies and heavy work happens in the background.

Pattern 5: The Scheduled Chore

Cloud Scheduler wakes a function on a timetable to clean old data, send reports, or refresh a cache. You get cron-style jobs with no machine kept running.

A pipeline example

The diagram below combines several patterns into one small data pipeline. A file arrives, a function validates it, a message announces the result, and another function loads the clean data into an analytics warehouse.

flowchart TD
  A["File uploaded to Cloud Storage"] --> B["Eventarc trigger"]
  B --> C["Validation function"]
  C --> D["Pub/Sub topic"]
  D --> E["Loader function"]
  D --> F["Notification function"]
  E --> G["BigQuery table"]
  C --> H["Dead-letter topic for bad files"]
        
FIG 5 — A small event-driven data pipeline
i
Single responsibility

Each function in the pipeline does one thing and can be tested, scaled and replaced alone. That small size is the real power of the model.

15Anti-Patterns to Avoid

Four common habits that look clever on day one and hurt by month six.

ANTI-PATTERN-01 Avoid
Problem

One giant function that handles many unrelated jobs, chosen by a hidden switch inside the code.

Why It’s Harmful

It grows large, starts slowly, and a bug in one job can break all the others. Permissions must be wide enough for every job, which weakens security. Scaling cannot be tuned per job.

Correct Approach

Create one function per clear responsibility. Share common helper code through a library, not through a shared giant.

ANTI-PATTERN-02 Avoid
Problem

Functions that call other functions directly and wait, forming long chains.

Why It’s Harmful

Each waiting function is billed while it does nothing. Time limits add up, a failure at the end wastes all earlier work, and tracing the problem becomes painful.

Correct Approach

Connect steps through Pub/Sub, Cloud Tasks or Workflows, so each step finishes quickly and hands over cleanly.

ANTI-PATTERN-03 Avoid
Problem

Using the default shared service account and storing secrets in plain settings.

Why It’s Harmful

If the function is ever compromised, an attacker inherits broad power across the project, and secrets are visible to anyone who can view the configuration.

Correct Approach

Create a dedicated, minimal service account for each function and keep secrets in Secret Manager.

ANTI-PATTERN-04 Avoid
Problem

Keeping important information in the instance’s memory or local disk between requests.

Why It’s Harmful

Instances come and go at any time, and several may run at once. Data held inside one instance disappears or becomes inconsistent.

Correct Approach

Keep functions stateless. Store lasting information in a database, a storage bucket, or a cache service designed for it.

16Understanding the Cost Model

Functions are cheap for light and bursty work, but the bill has several parts worth knowing.

The big promise of functions is that you pay for what you use. That is true, but “what you use” has several parts. Exact prices change and differ by region, so always read the current pricing page. What stays steady is the shape of the bill.

Part 1

Invocations

A small charge for each request or event handled, after a free allowance each month.

Part 2

Compute time

Charged for the CPU and memory your function uses for the seconds it is running.

Part 3

Idle instances

If you keep minimum instances warm, you pay for their readiness even when no requests come.

Part 4

Network traffic

Data leaving Google Cloud, or crossing regions, can add cost that surprises people.

Part 5

Supporting services

Cloud Build, Artifact Registry, logging storage, Pub/Sub and Secret Manager each have their own small charges.

How to keep the bill friendly

  • Right-size memory. Oversized instances multiply cost for every second.
  • Use concurrency in 2nd gen so one instance serves many requests.
  • Finish fast. Avoid waiting on slow services without time limits.
  • Set maximum instances so a runaway loop or attack cannot scale spending without limit.
  • Trim logs. Very chatty functions can spend more on log storage than on compute.
  • Set budget alerts on the project so surprises arrive as a message, not as an invoice.
Simple Analogy

A taxi meter charges for distance and waiting time. A function meter charges for work and time spent. If your driver keeps the engine running at every red light while nobody rides, the meter still counts. Fast, focused functions keep the meter low.

!
Cheap is not always cheapest

For steady, heavy traffic that runs all day, an always-on container service may cost less than millions of function calls. Compare both models against your real traffic before deciding.

17Advantages, Disadvantages and Alternatives

Every tool has a sweet spot. Here is where functions shine and where they struggle.

Advantages

  • No servers to patch, size or restart
  • Automatic scaling from zero to many instances
  • Pay only for the time code actually runs
  • Very fast path from idea to working feature
  • Native links to Pub/Sub, Storage, Firestore and many Google services
  • Built-in logging, monitoring and identity controls

Disadvantages / Trade-offs

  • Cold starts can add delay to the first request
  • Time, memory and size limits restrict very heavy jobs
  • Many small functions can be harder to understand as a whole
  • Debugging across events and services takes practice
  • Less control over the operating system and runtime details

Choosing among Google Cloud compute options

Functions are one of several ways to run code on Google Cloud. The right choice depends on how much control you need and what shape your workload has.

OptionBest forYou manage
Cloud Run functionsSmall event-driven or web jobsOnly the code and settings
Cloud Run servicesContainerised web apps and APIs with any language or libraryThe container image and its settings
App EngineTraditional web applications on a managed platformApplication code and app settings
Google Kubernetes EngineLarge, complex systems needing deep controlClusters, nodes policies and workloads
Compute EngineFull virtual machines and special softwareOperating system and everything above it
flowchart TD
  Q1["Is the job small and triggered by an event or request?"] -->|Yes| F["Use Cloud Run functions"]
  Q1 -->|No| Q2["Do you have a container or need custom libraries?"]
  Q2 -->|Yes| R["Use Cloud Run services"]
  Q2 -->|No| Q3["Need deep control or complex orchestration?"]
  Q3 -->|Yes| K["Consider GKE or Compute Engine"]
  Q3 -->|No| R
        
FIG 6 — A simple decision path for choosing where code should run
i
Easy to move later

Because 2nd gen functions are Cloud Run services underneath, a function that outgrows its limits can usually move to a regular Cloud Run service without a total redesign.

18Best Practices and Common Mistakes

A short checklist of habits that separate calm production systems from stressful ones.

Habits worth building

Practice 1

Stay stateless

Treat every invocation as independent. Keep lasting data in proper storage services.

Practice 2

Be idempotent

Assume any event may arrive twice and design so repeats cause no harm.

Practice 3

Reuse connections

Create clients and connections once per instance, outside the function body, and reuse them.

Practice 4

Set limits

Choose sensible maximum instances, time limits and memory so one mistake cannot grow into a disaster.

Practice 5

Least privilege

Give every function its own minimal identity and keep secrets in Secret Manager.

Practice 6

Observe everything

Use structured logs, useful metrics and a few focused alerts from the first deployment.

Practice 7

Pin dependencies

Fix library versions so a surprise update cannot break a function that worked yesterday.

Practice 8

Automate deployment

Use a pipeline that tests and deploys the same way every time, with an easy way back to the previous revision.

Mistakes teams make again and again

!
Mistake 1

Treating a function like a long-running server and giving it jobs that take far too long. Break big jobs into steps or move them to a service built for long work.

!
Mistake 2

Leaving a function open to the public by accident. Always check who holds the invoker permission after every deployment.

!
Mistake 3

Ignoring retries until a permanently failing event is replayed thousands of times. Decide your retry and dead-letter plan before launch.

!
Mistake 4

Forgetting that scaling affects other systems. A function that scales freely can overwhelm a small database in seconds.

!
Mistake 5

Testing only on a laptop. Real behaviour depends on permissions, networking and event formats, so test in a cloud environment that matches production.

19Real-World Use Cases

Everyday examples that show how small functions solve large business needs.

Functions appear in many industries because they handle the small reactions that every digital business needs. Here are scenarios that teams commonly build.

Media processing for an online shop

When a seller uploads a product photo, a function creates thumbnails in several sizes, checks the image for unwanted content, and stores the results. During a big sale, hundreds of uploads arrive at once, and the platform simply starts more instances.

Order notifications

When a new order record appears in a database, a function sends a confirmation message to the customer and a note to the warehouse team. Each notification is a separate small function, so a problem with one never blocks the other.

Payment and chat webhooks

Outside services such as payment providers and chat tools send web hooks, which are automatic calls announcing that something happened. An HTTP function receives each call, verifies it is genuine, and places the work in a queue for background handling.

Sensor and device data

Devices send readings to Pub/Sub. A function cleans each reading, marks unusual values, and writes the results to an analytics store. Traffic rises and falls with the devices, which suits automatic scaling very well.

Nightly housekeeping

Cloud Scheduler wakes a function every night to remove old temporary files, close expired sessions, and prepare a summary report for the morning team. Nothing runs, and nothing costs, for the rest of the day.

Security and compliance reactions

Through audit log events, a function can notice when a storage bucket is made public or a risky permission is granted, then alert the security team or automatically correct the setting.

Glue between systems

When two systems speak different formats, a small function translates between them. It receives a message in one shape, reshapes it, and passes it on. This is one of the most common and valuable jobs for functions.

20Inside the Machine: Instances, Isolation and Event Delivery

A closer look at what really happens below the surface when your function runs.

So far we have treated an instance as a magic box. Let us open the lid a little. Understanding the inside of the box explains many behaviours that otherwise feel mysterious, such as why global variables survive between requests, why two functions never see each other’s files, and why events sometimes arrive late.

What an instance really is

An instance is a running container started from the image that Cloud Build created for you. Inside the container, the functions framework listens for incoming calls and passes each one to your code. The container runs inside a secure sandbox, which is a protected space that keeps your workload apart from every other customer’s workload on the same physical machine. Even if two customers share one computer, neither can look into the other’s container.

Simple Analogy

An instance is like a hotel room in a large building. Many guests stay in the same building and share the plumbing and the lifts, but each room has its own locked door. What you leave inside your room stays in your room, and housekeeping may clear it when you check out.

What survives between requests, and what does not

While an instance stays alive, anything stored in memory outside the function body stays alive too. This is why connections and loaded settings can be reused, and it is the reason warm calls are so much faster than cold ones. But the instance can be removed at any moment, for example when traffic drops or when Google moves workloads around. Any data kept only in memory, or written to the instance’s temporary disk, will vanish when that happens. The temporary disk is also held in memory in this environment, so writing large files there uses up the memory you have paid for.

Survives

Global objects

Clients, caches and settings created at start-up remain while the instance lives and are shared by later requests on that instance.

Lost

Instance memory

Everything in memory disappears when the instance is stopped, so never treat it as a database.

Lost

Temporary files

Files written to the local temporary area are not shared with other instances and are not kept.

Shared safely

External services

Databases, buckets and queues are the right homes for anything that must outlive a single instance.

How an event reaches your function

Event-driven delivery has its own journey. When something happens in a source service, such as a new file in a bucket, an event is created. Eventarc receives it, checks it against the filters of every trigger you have defined, and wraps it in a standard envelope format called a CloudEvent. That envelope carries the type of event, the source, the time, and the details. Eventarc then calls your function over the internal network with an identity that is allowed to invoke it.

1

Something happens

A file is added, a message is published, or a record is changed in a Google Cloud service.

2

Eventarc matches the trigger

The event is compared with trigger filters such as event type, bucket name or topic. Only matches continue.

3

The event is packaged

The details are wrapped in the standard CloudEvent format so every function sees events in a familiar shape.

4

Delivery with identity

Eventarc calls the function with a service account that holds the invoker permission, and waits for a success signal.

5

Success or retry

On success the event is finished. On failure, if retries are enabled, delivery is attempted again according to the retry rules.

i
Delivery is not instant magic

Events usually arrive within moments, but some sources are slower than others, and audit-log based events can take longer than direct ones. If a job needs a guaranteed fast response, use a direct web call instead of waiting for an event.

!
Order is not guaranteed

Events can arrive out of order. If a “delete” notice arrives before an “update” notice for the same item, naive code can bring a deleted item back to life. Compare timestamps or version numbers before applying a change.

21Deployment, Testing and Release Habits

A function is only as dependable as the way it is tested, shipped and rolled back.

Because functions are small, it is tempting to edit them directly in a console and press deploy. That works for a first experiment, but it is a risky habit for anything real. Teams that run many functions in production treat them like any other software: code lives in version control, changes are reviewed, tests run automatically, and releases follow a repeatable path.

A healthy delivery path

1

Keep code in version control

Every change has an author, a reason and a history. You can see what changed before a problem began.

2

Test the logic locally

Because the functions framework runs on a normal computer, you can start the function locally and send it sample requests or sample events before it ever reaches the cloud.

3

Run automated checks

A pipeline runs unit tests, scans dependencies for known weaknesses, and checks that the configuration follows your rules.

4

Deploy to a test environment

A separate project, with real permissions and real event sources but fake data, reveals problems that a laptop cannot.

5

Release gradually

Send a small share of traffic to the new revision first, watch the error rate, then increase the share.

6

Roll back quickly if needed

Because earlier revisions are kept, moving traffic back to the last good version takes moments.

The kinds of tests that matter

Unit tests

Test the pure logic, such as how a message is parsed or how a price is calculated, without touching any cloud service. These are fast and catch most simple mistakes.

Integration tests

Deploy the function to a test project and trigger it for real, for example by uploading a file to a test bucket. This proves that permissions, event filters and network settings are right.

Duplicate and failure tests

Deliberately send the same event twice, send a broken event, and make a downstream service fail. Confirm the function behaves safely each time.

Load tests

Send a large burst of work and watch instance counts, run times and downstream pressure. This is how you discover that your database cannot handle five hundred connections.

Simple Analogy

Releasing a function is like opening a new bridge. You test the design on paper, test the materials in a lab, let a few light vehicles cross first, and only then open it to heavy traffic. You also keep the old road open until you trust the new one.

Configuration as part of the release

Settings such as memory, timeout, maximum instances and network rules are part of what makes a function work. Store them alongside the code, ideally in infrastructure definitions that are reviewed like code. When settings live only in someone’s memory or in a console, no one can tell why production behaves differently from the test environment.

!
Do not skip the dependency check

Every library you add is code you did not write but are still responsible for. Pin versions, scan regularly, and remove packages you no longer use, because each one makes the package larger and the cold start slower.

22Moving from 1st Gen to 2nd Gen

If you already run older functions, here is a calm, step-by-step way to modernise them.

Many organisations still run 1st gen functions that were written years ago and work fine. There is no need to panic, but there are good reasons to plan a move: access to larger machines, longer run times, concurrency, richer event sources, and the full range of Cloud Run features. A careful migration is mostly about checking differences, not rewriting everything.

What usually changes

Change 1

Event format

Event-driven functions in 2nd gen receive events in the CloudEvent format, which differs from the older style. Code that reads event details must be adjusted.

Change 2

Concurrency behaviour

Code that quietly assumed one request at a time may break when several run together. Shared variables deserve special care.

Change 3

Permissions model

Invoking is controlled through the Cloud Run invoker role, and Eventarc needs its own identity with the right permissions.

Change 4

Triggers and sources

Some older trigger types map neatly to Eventarc, while others need a different but equivalent design.

Change 5

Address and settings

The function receives a new address, and some settings are named or grouped differently. Callers must be updated.

Change 6

Quotas and defaults

Default maximum instances, timeouts and request sizes differ, so review them rather than assuming they are the same.

A safe migration path

1

Take inventory

List every function, its trigger, its callers and its owner. Forgotten functions are the usual source of surprises.

2

Start with low-risk functions

Migrate small, rarely used, easily tested functions first. Learn the pattern before touching critical ones.

3

Deploy the new version alongside the old

Run both side by side with separate names so there is no downtime and the old one remains a fallback.

4

Compare behaviour

Check results, error rates, run times and costs between the two versions under real or realistic traffic.

5

Switch callers and triggers

Point web callers to the new address and move event triggers, taking care not to process the same event in both versions.

6

Retire the old function

After a quiet period with no traffic on the old version, delete it and update your documentation.

Simple Analogy

Migrating is like moving to a bigger house while still living in the old one. You carry boxes over a few at a time, check that the new kitchen works, and only hand back the old keys when the last box has safely arrived.

!
Avoid double processing

While old and new functions both listen to the same source, every event may be handled twice. Disable the old trigger at the moment you enable the new one, and make the work idempotent as a second line of defence.

i
Check the official guidance

Google publishes migration guidance and may announce support timelines for older generations. Read the current documentation before planning your schedule, because dates and tools can change.

23Where to Keep State: Storage and Data Options

Functions forget everything, so the memory of your system must live somewhere else.

Since a function instance can disappear at any time, every piece of information that matters must be kept in a service built for that purpose. Choosing the right home for your data is one of the most important design decisions you will make. A wrong choice can make a simple function slow, expensive or fragile. Google Cloud offers several storage services, and each one fits a different kind of information.

Simple Analogy

A function is like a clerk who has a very short memory but excellent filing cabinets nearby. The clerk does not try to remember every customer. Instead, the clerk opens the right drawer, reads the file, does the work, and puts the file back. Picking the right cabinet decides how quickly the clerk can work.

Choosing the right home for your data

ServiceKind of dataGood fit when
Cloud StorageFiles and large objects such as images, documents and exportsYou store whole files, and events from file changes should trigger work
FirestoreFlexible documents with fast reads and writesYou need a simple, scalable store for records that change often
Cloud SQL and AlloyDBTraditional relational tablesYou need joins, transactions and a familiar database, with care about connection counts
BigtableVery large, fast key-based dataYou handle huge volumes such as device readings or time series
BigQueryAnalytics over large datasetsYou load data for reporting and analysis, not for fast single-record lookups
MemorystoreIn-memory cacheYou want to reduce repeated slow lookups and share a cache across instances
Secret ManagerPasswords, keys and tokensYou must keep sensitive values out of code and settings

Protecting databases from your own success

Because functions scale quickly, they can open a very large number of database connections within seconds. Traditional relational databases allow only a limited number of connections, and too many can make the whole database unresponsive. Several habits help. Reuse one connection per instance rather than opening one per request. Use a connection pool or a managed proxy that shares connections. Set a sensible maximum instance count. Or place a queue in front so work arrives at a steady pace.

Habit 1

Reuse connections

Create the database client once when the instance starts and reuse it for every request.

Habit 2

Cap the instances

Limit how many instances may run so the total number of connections stays below the database limit.

Habit 3

Smooth the bursts

Use Cloud Tasks or Pub/Sub so sudden floods of work are released gradually.

Habit 4

Prefer scalable stores

For very bursty, simple data, a store designed to scale horizontally avoids connection limits altogether.

Caching and the cost of repetition

If many requests ask for the same slow-to-fetch information, such as a settings table or a list of product categories, fetching it every time wastes time and money. A small in-memory copy that lives for the life of the instance can help, as long as the information changes rarely and slightly stale data is acceptable. For information that must be consistent across all instances, a shared cache service is a better choice. Always decide how long cached data may be trusted, because stale data is a quiet source of confusing bugs.

i
Ask two questions

For each piece of data, ask how long it must live and who else needs to see it. If the answer is “longer than one request” or “other instances,” it does not belong inside the function.

!
Keep storage and function close

Placing a function in one region and its database in another adds delay to every call and may add network charges. Choose the same region whenever the rules of your business allow it.

24Operating Functions at Scale

What changes when you go from a handful of functions to hundreds across many teams.

A single function is easy to understand. A hundred functions owned by ten teams are a different matter. Without shared habits, you end up with unknown owners, unclear names, forgotten experiments still running, and permissions nobody remembers granting. Operating at scale is mainly about discipline and visibility.

Ownership and naming

Every function should have a clear owner and a clear purpose that can be read from its name. Names that describe the job, such as one that mentions the event and the action, are far more useful than names like “test2” or “newfunction.” Labels, which are small key and value tags attached to resources, can record the team, the environment, the cost centre and the service the function belongs to. Labels make it possible to filter logs, split the bill by team, and find all functions owned by a team that is being reorganised.

Label

Team or owner

Tells you who to contact when the function misbehaves at night.

Label

Environment

Separates development, testing and production so nobody changes the wrong one.

Label

Cost centre

Lets finance teams see which part of the business is responsible for each portion of the bill.

Label

Criticality

Shows which functions need strict alerts and careful release steps, and which can be handled more simply.

Projects, environments and boundaries

A common approach is to give each environment its own Google Cloud project, so a mistake in testing can never touch production data. Larger organisations also group projects into folders and apply organisation policies at the folder level. These policies can enforce rules automatically, such as allowing only certain regions, blocking public access to functions, or requiring that functions use private networking. Rules enforced by the platform are far more reliable than rules written in a document that people may forget.

Simple Analogy

Running a few functions is like keeping a small family kitchen. Running hundreds is like running a restaurant chain. You need labelled shelves, written recipes, hygiene rules checked by someone other than the cook, and a manager who knows which branch is losing money.

Quotas, budgets and guard rails

Quotas protect the platform and also protect you. Limits exist on the total memory and processing power a project may use in a region, on how many functions you may deploy, and on how fast you may change them. If one noisy function consumes the project’s allowance, other functions can fail. To avoid this, separate critical and experimental functions into different projects, monitor how close you are to quotas, and request increases early.

1

Set budgets and alerts

Receive a message when spending reaches a share of the monthly plan, long before the month ends.

2

Review a regular inventory

Once a quarter, list all functions, check their traffic, and retire the ones nobody uses.

3

Audit permissions

Check who may invoke each function and which service account it runs as, and remove anything broader than needed.

4

Update runtimes

Plan upgrades before a language version loses support so that security fixes never stop arriving.

Documentation people will actually read

For every function, write a short page that states its purpose, its trigger, what it reads and writes, which settings matter, how to tell whether it is healthy, and what to do when it fails. A page that takes two minutes to read can save two hours of confusion during an incident.

i
Make the safe path the easy path

Provide a starter template that already includes sensible memory, a dedicated service account, structured logging and standard labels. People follow whatever is easiest, so make the correct way the easiest way.

!
Forgotten functions are risk

An unused function with an old library and broad permissions is a quiet security hole. Retiring what you no longer need is as valuable as building something new.

25How Google’s Approach Compares with Other Clouds

The idea of functions is shared across providers, but the details feel different.

Function-as-a-Service is not unique to Google. Other major cloud providers offer their own versions, and the basic promise is the same everywhere: send code, get automatic scaling, pay for use. Knowing how the ideas line up helps you move knowledge between platforms and avoid being surprised when you switch.

Simple Analogy

Different airlines all fly you from one city to another. The seats, the snacks and the baggage rules differ, but once you understand how flying works, you can sit comfortably in any of them. Functions across providers are much the same.

Ideas that carry over

Shared idea

Event-driven design

Every provider lets storage changes, messages and schedules start functions. The pattern thinking from this guide applies everywhere.

Shared idea

Statelessness

Instances are temporary on every platform, so lasting data always belongs in external services.

Shared idea

Cold starts

Every provider has start-up delays and offers some way to keep instances ready for a price.

Shared idea

Identity-based access

Each cloud gives functions an identity with permissions, and least privilege is the rule on all of them.

What feels distinctive about Google’s approach

The most noticeable difference is that 2nd gen functions are built directly on Cloud Run, a general container platform. This blurs the line between a function and a small containerised service. A team can start with a function and later promote the same workload to a full Cloud Run service with little redesign. This also means that features such as concurrency per instance, longer web request times and larger memory sizes come from the same foundation as container workloads.

A second distinctive point is Eventarc, which gives one consistent way to receive events from a very wide range of Google Cloud services, including those that report activity through audit logs. This makes it simple to build rules like “when this resource changes, run this function” without writing special code for each service.

QuestionTypical answer on Google Cloud
What is the foundation?Cloud Run for serving, Cloud Build and Artifact Registry for building and storing
How are events delivered?Through Eventarc using the CloudEvent format
How are many requests handled?Through concurrency per instance in 2nd gen
How do I grow beyond a function?Promote the workload to a Cloud Run service that uses a container
How is access controlled?Through IAM invoker permissions and dedicated service accounts
i
Avoid unnecessary lock-in worry

Keep business logic in plain code that does not depend on any provider, and put the provider-specific parts in a thin outer layer. Then moving between platforms means rewriting a small wrapper, not the whole function.

!
Do not compare by names alone

Limits, defaults, pricing and features differ between providers and change often. Before choosing a platform, compare current documentation for the exact numbers that matter to your workload instead of relying on general reputation.

26Frequently Asked Questions

Quick answers to the questions beginners and intermediate engineers ask most.

Q1Is “serverless” really without servers?

No. Servers exist, but Google owns, patches and scales them. You never manage them directly, which is why the word serverless describes your experience rather than the hardware.

Q2What is the difference between Cloud Functions and Cloud Run functions?

Cloud Run functions is the newer name Google uses for the product family. The 2nd gen design runs on Cloud Run and Eventarc, while 1st gen is the earlier implementation. For new projects, 2nd gen is the usual choice.

Q3How long can a function run?

It depends on the generation and type. 1st gen is limited to nine minutes. In 2nd gen, web functions can run up to sixty minutes, event-driven functions up to nine minutes, and scheduled or task-queue functions up to thirty minutes. Always confirm current numbers in the quotas page.

Q4What exactly is a cold start and can I remove it?

A cold start is the extra time needed to start a new instance before it handles its first request. You cannot remove it completely, but you can reduce it with smaller packages, lazy loading, and minimum instances that keep some instances warm.

Q5Can one function handle many requests at the same time?

In 2nd gen, yes, through concurrency. In 1st gen, each instance handles one request at a time. Concurrency saves money but requires code that keeps each request’s data separate.

Q6Can a function be triggered by more than one event type?

Not directly. Each function has one trigger. If several events must run the same logic, deploy more than one function that shares the same helper code, or send all events through one Pub/Sub topic that feeds a single function.

Q7How do I stop duplicate events from causing problems?

Design for idempotency. Record a unique identifier for each processed event or order, and skip anything already seen. Also store results in a way that makes repeating the final step harmless.

Q8Is it safe to make a function public?

It can be, when that is the purpose, such as a public web hook. Even then, validate every incoming request, check signatures where the sender provides them, limit the maximum instances, and avoid giving the function powerful permissions.

Q9How can a function reach a private database?

Connect the function to your VPC network using a serverless connector or direct network egress. Then the function can reach private addresses. Place it in the same region as the database and set a sensible maximum instance count to protect the database from too many connections.

Q10When should I choose Cloud Run services instead?

Choose Cloud Run services when you already have a container, need custom system libraries, want several routes in one application, or need full control over how the application starts. Functions are best for small, focused, event or web reactions.

Q11How do I keep costs under control?

Right-size memory, use concurrency, set maximum instances, avoid long waits, trim noisy logs, and add budget alerts. Review the bill monthly in the first few months, because early habits shape long-term spending.

Q12Where do I look first when a function fails?

Start with the logs for the failing time window and search by the request or event identifier. Then check error reports for grouped failures, and look at metrics for sudden changes in memory, run time, or instance count.

27Summary and Key Takeaways

Cloud Functions, now described by Google as Cloud Run functions, lets you focus on the single job your code must do while the platform takes care of machines, scaling and many security chores. You learned that functions are woken by web requests or by events delivered through Eventarc, that 2nd gen is built on Cloud Run and brings bigger limits and concurrency, and that automatic scaling is powerful but needs boundaries. You also saw that dependable systems come from habits: stateless code, idempotent handling, least-privilege identities, protected secrets, careful retries, and clear monitoring.

Functions are not the answer to everything. Heavy, long, always-busy workloads may fit better on container services or virtual machines. But for small reactions, glue between systems, scheduled chores and bursty events, they are one of the quickest and most economical tools in the whole cloud. Start small, measure honestly, and grow with confidence.

Key Takeaways

  • One job per function — small, focused functions are easier to test, secure, scale and replace.
  • Triggers decide when, configuration decides how — HTTP calls and Eventarc events wake functions, while memory, time, scaling and network settings shape their behaviour.
  • Prefer 2nd gen for new work — it runs on Cloud Run and Eventarc, with larger limits, longer run times and concurrency.
  • Plan for duplicates and failures — events can arrive more than once, so build idempotent logic with a clear retry and dead-letter plan.
  • Protect scale and security together — set maximum instances, use dedicated service accounts, keep secrets in Secret Manager, and restrict who can invoke.
  • Stay stateless and reuse setup work — keep lasting data in proper services and create connections once per instance to soften cold starts.
  • Choose the tool by workload shape — functions suit small and bursty jobs, while containers or virtual machines suit heavy, long-running or highly customised work.