Cloud Functions in Google Cloud
A friendly, complete guide to running small pieces of code in the cloud without ever managing a server. Learn how functions start, scale, stay secure, and fit into real systems.
Imagine you own a small shop. Every time a customer buys something, you need someone to print a receipt. You could hire a full-time worker who sits there all day, even when nobody is buying. Or you could call a helper who appears the moment a sale happens, prints the receipt, and disappears. You pay only for the seconds the helper actually worked. That second idea is the heart of Cloud Functions.
Cloud Functions is a service from Google Cloud that lets you write a small piece of code, called a function, and have Google run it for you whenever something happens. Nobody needs to set up a computer, install an operating system, or keep it patched. You hand over the code. Google handles everything else. In this guide you will learn what it is, how it works inside, how to keep it safe, and how to use it well in real projects.
In 2024 Google began calling the second generation of this product “Cloud Run functions”, because it now runs on top of Cloud Run. Many people, books, and job descriptions still say “Cloud Functions”, so this guide uses that familiar name. Always check the official Google Cloud documentation for the newest limits and names, because cloud products change often.
1What Is Cloud Functions?
Start here. This chapter explains the big idea in plain words before we look at any details.
The simple definition
Cloud Functions is a serverless compute service. “Compute” means a place where your code runs. “Serverless” does not mean there are no servers. Servers still exist, but they are Google’s problem, not yours. You never log in to them, you never choose how many to buy, and you never fix them when they break.
A function is a small block of code that does one job. For example: resize one picture, send one email, check one payment, or save one row of data. It starts, finishes its job, and stops.
Think of a taxi app instead of owning a car. A car you own costs money every day, even when parked. A taxi costs money only for the trips you take. Cloud Functions is the taxi. Your own virtual machine is the parked car.
Why it exists
Before serverless, a team that wanted to run even tiny code had to rent a server, install software, secure it, watch it, and pay for it twenty-four hours a day. Most of that time the server sat idle. Cloud Functions was created to remove that waste and that busywork, so developers can focus on the code that matters to their business.
Where it is used
Teams use it for web hooks, small web APIs, file processing, chat bots, data clean-up, scheduled jobs, and glue code that connects one Google Cloud service to another. It is a favourite tool for “when this happens, do that” tasks.
2Core Concepts You Must Know
Six simple ideas explain almost everything about Cloud Functions. Learn these and the rest becomes easy.
Function
One small unit of code with one job. It receives input, does the work, and returns a result or simply finishes.
Trigger
The thing that wakes the function up. It can be a web request, a new file, a message, or a timer.
Event
A small note that says “something happened”, such as “a photo was uploaded”. It carries details about what happened.
Instance
One running copy of your function. If many requests arrive, Google starts many instances at the same time.
Runtime
The programming language environment your code runs in. Supported choices include Node.js, Python, Go, Java, .NET, Ruby, and PHP.
Entry point
The exact function name inside your code that Google should call first when a trigger fires.
Two kinds of functions
The first kind is an HTTP function. It gets its own web address. Anyone allowed to call that address can wake it up by sending a request, just like opening a web page. It answers with a response. This kind is good for small APIs and webhooks.
The second kind is an event-driven function. It has no public address of its own. Instead it listens for an event from another Google Cloud service and runs when that event happens. This kind is good for background work, such as processing a file after it lands in storage.
An HTTP function is like a shop with a front door and a bell. Visitors ring it and wait for an answer. An event-driven function is like a mail clerk who only moves when a package arrives at the back dock. Nobody rings a bell. The package itself is the signal.
Stateless by design
A function must be stateless. That means it should not rely on remembering anything from earlier runs. Google may reuse an instance for the next request, or may throw it away at any time. If you need to remember something, write it to a database or storage service. We return to this rule many times because breaking it is the most common beginner mistake.
3First Generation and Second Generation
Cloud Functions exists in two generations. Knowing the difference helps you read older tutorials and choose wisely for new work.
The first generation was the original product. Each instance handled exactly one request at a time. If ten requests came together, Google started ten instances. It was simple, but it also meant more cold starts and less control.
The second generation was rebuilt on top of Cloud Run and Eventarc. Cloud Run is Google’s service for running containers. Eventarc is Google’s service for routing events. Because of this foundation, second generation functions gained longer time limits, bigger machine sizes, the ability to handle many requests inside one instance, and a much wider list of event sources.
| Topic | First generation | Second generation |
|---|---|---|
| Built on | Its own original platform | Cloud Run and Eventarc |
| Requests per instance | One at a time | Many at a time if you allow it |
| Machine size | Smaller choices | Larger memory and more CPU choices |
| Time limit for web functions | Short | Much longer, up to about an hour |
| Event sources | Fewer, mostly core services | Many, through Eventarc |
| Traffic splitting and revisions | Not available | Available through Cloud Run features |
| Best choice today | Existing older workloads | New projects |
Exact numbers for memory, time limits, and instance counts change over time. Treat the table above as a picture of the general difference, and confirm the current figures in the official quotas page before you design anything critical.
4Architecture and Components
Let us look at the building blocks that sit around your code and make the magic happen.
flowchart LR
A["Client or Browser"] --> B["HTTPS Endpoint"]
B --> C["Cloud Functions Service"]
C --> D["Function Instance"]
D --> E["Firestore Database"]
D --> F["Cloud Storage Bucket"]
G["Pub/Sub Topic"] --> H["Eventarc Router"]
H --> C
I["Cloud Scheduler"] --> B
The picture shows two doors into your function. The first door is the HTTPS endpoint, used by browsers, mobile apps, and other programs. The second door is Eventarc, which listens to other Google Cloud services and delivers their events. Cloud Scheduler can ring the first door on a timetable, like an alarm clock for your code.
The main parts
Your source code
The files you write, plus a list of the libraries your code needs. You upload them or point to a repository.
Cloud Build
A Google service that takes your source code and turns it into a ready-to-run package called a container image.
Artifact Registry
A storage shelf where the finished container image is kept until Google needs to start an instance.
The function service
The manager that receives triggers, decides how many instances are needed, and sends each request to a ready instance.
Eventarc and Pub/Sub
The messengers. They carry events from storage, databases, and other services to your function.
Identity and access control
Rules that decide who may call your function and what your function may touch. We cover this in the security chapter.
The Functions Framework
Google publishes a free, open-source helper called the Functions Framework. It wraps your code so that it follows the same rules locally as it does in the cloud. You can run your function on your own laptop, test it, and then deploy the same code unchanged. This is a big help, because it means you do not have to deploy every small change just to see if it works.
5How It Works Inside
This chapter follows one request from the moment it arrives until the answer goes back out.
sequenceDiagram
participant U as User
participant P as Platform
participant I as Instance
participant D as Database
U->>P: Send request
P->>P: Look for a free instance
alt No instance is ready
P->>I: Start a new instance
I->>I: Load code and run setup
end
P->>I: Hand over the request
I->>D: Read or write data
D-->>I: Return result
I-->>P: Send response
P-->>U: Reply to user
Note over P,I: Idle instances are removed later
Cold starts and warm starts
When a request arrives and no instance is ready, Google must create one. It finds a machine, loads your container, starts the language runtime, and runs your setup code. This extra waiting time is called a cold start. It can take from a fraction of a second to a few seconds, depending on your language, your libraries, and how much your setup code does.
If an instance is already running and idle, the next request reuses it. This is a warm start, and it is much faster because all the setup is already done.
A cold start is like walking into a restaurant kitchen that is switched off. The chef must turn on the stove, heat the oil, and gather the tools before cooking. A warm start is a kitchen that was cooking a minute ago. The chef is ready, so your meal begins at once.
Scaling up and down
Google watches how many requests are coming in. If traffic grows, it starts more instances. If traffic falls, it removes instances, and when no traffic remains, it can remove all of them. This is called scale to zero, and it is why you pay nothing when nobody uses your function.
You can place limits on this behaviour. A minimum instances setting keeps some instances always ready, which reduces cold starts but costs a little even when idle. A maximum instances setting puts a ceiling on growth, which protects other systems from being overwhelmed.
Concurrency in the second generation
In the second generation, one instance can serve several requests at the same moment. This setting is called concurrency. If one instance handles ten requests together, you need far fewer instances, you see fewer cold starts, and your bill is usually smaller. The trade-off is that your code must be safe when many tasks share the same memory. Shared variables that change are dangerous here. The default is often one request at a time, so you must turn higher concurrency on deliberately and give the function enough CPU.
Where the code really runs
Every instance runs inside a secure sandbox. A sandbox is a sealed room: your code can use the room’s resources but cannot peek into the neighbouring rooms that belong to other customers. This isolation is how Google safely runs code from millions of different people on shared hardware.
6Data Flow and Lifecycle
Follow the data and the life of a function from first idea to retirement.
The lifecycle of a function
Write
You write the code and test it on your laptop with the Functions Framework.
Deploy
You send the code to Google. Google builds it into a container and stores it.
Trigger
A request, event, or timer wakes the function.
Execute
An instance starts or is reused, and your code runs.
Observe
Logs and metrics flow automatically into the monitoring tools.
Update or retire
You release a new version or delete the function when it is no longer needed.
A real data flow: photo upload
Picture a photo-sharing app. A user uploads a picture. Nobody wants to wait while the server makes thumbnails, so the work happens in the background through a chain of small functions.
flowchart TD
A["User uploads photo"] --> B["Cloud Storage bucket"]
B --> C["Eventarc trigger"]
C --> D["Thumbnail function"]
D --> E["Resized image bucket"]
D --> F["Pub/Sub topic image-ready"]
F --> G["Notification function"]
F --> H["Metadata function"]
G --> I["Email or push message"]
H --> J["Firestore record"]
The upload lands in a bucket. Storage emits an event. Eventarc delivers it to the thumbnail function. That function creates smaller images and then publishes a short message to a Pub/Sub topic. Two other functions listen to that topic. One sends a notification, and the other saves details to a database. Each function is small, easy to understand, and can fail or be fixed on its own without breaking the others.
Delivery guarantees and retries
Event-driven delivery is usually at least once. That means Google promises the event will arrive one or more times, but it does not promise exactly once. If your function crashes and retries are on, the same event may be delivered again. For this reason you should write functions that are idempotent, a long word that simply means “doing it twice gives the same result as doing it once”.
Pressing the lift button twice does not call two lifts. The lift system treats the second press as the same request. Your function should treat a repeated event the same way: if the receipt is already printed, do not print another.
7Triggers in Depth
A function is useless until something wakes it. Here are the most common wake-up calls.
Web request
The function gets a web address. Perfect for webhooks from payment providers, chat tools, and code hosting sites, or for tiny APIs.
Pub/Sub message
A message published to a topic wakes the function. Ideal for decoupling parts of a system so they do not need to know each other.
Cloud Storage change
Reacts when a file is created, replaced, or deleted. Great for image, video, and document processing.
Firestore change
Reacts when a document is added or updated. Useful for keeping related data in sync or sending alerts.
Audit log events
Through Eventarc, a function can react to many actions across Google Cloud, such as a new virtual machine being created.
Scheduled run
Cloud Scheduler calls your function on a timetable, like every night at two in the morning.
Cloud Tasks for controlled work
Sometimes you want to send work to a function slowly and carefully, not all at once. Cloud Tasks is a queue service that hands out jobs at a rate you choose, retries failures, and can delay jobs to a later time. It pairs well with functions when a downstream system, such as an old database, can only handle a trickle of requests.
Pick the trigger that matches the job. Use HTTP when someone is waiting for an answer. Use Pub/Sub or storage events when the work can happen in the background. Choosing wisely keeps your design calm and simple.
8Settings That Shape Behaviour
A handful of settings decide how fast, how safe, and how costly your function will be.
| Setting | What it controls | Simple advice |
|---|---|---|
| Memory and CPU | How big each instance is | Start small, measure, then increase only if needed |
| Timeout | How long one run may last before Google stops it | Set it just above the normal run time, not at the maximum |
| Minimum instances | How many instances stay warm | Use for user-facing functions where speed matters |
| Maximum instances | The ceiling on growth | Set it to protect databases and paid outside services |
| Concurrency | Requests handled together by one instance | Raise it only when your code is safe for sharing |
| Environment variables | Plain settings passed to the code | Never place passwords here |
| Region | Which Google data centre area runs the code | Choose close to users and close to your data |
The region choice deserves a moment. Running your function far from your database adds delay to every call, because data must travel a long distance. Put the function and its data in the same region whenever you can. This single choice often makes a bigger speed difference than any code tuning.
9Advantages, Disadvantages, and Trade-offs
No tool is perfect. Here is an honest look at both sides.
Advantages
- No servers to build, patch, or watch.
- Automatic scaling from zero to a very large number of instances.
- You pay only while code runs, with a free monthly allowance.
- Fast to start: a useful function can be live within minutes.
- Deep connection to other Google Cloud services.
- Built-in logging and monitoring without extra setup.
Disadvantages
- Cold starts can add delay to the first request.
- Time and size limits make it unfit for very long or very heavy jobs.
- Debugging a chain of many small functions can be tricky.
- Sudden scaling can overload a database that cannot keep up.
- Costs can surprise you at very high steady traffic.
- Your design becomes tied to Google’s way of doing things.
The big trade-offs
Simplicity versus control. You give up the ability to tune the machine, the network, and the operating system. In return you get freedom from running them. For most small and medium jobs this is a very good bargain.
Cost at low traffic versus cost at high traffic. Paying per use is wonderful when traffic is small or uneven. When a service receives heavy, constant traffic all day, an always-on container can be cheaper than millions of separate function runs. Run the numbers for your own case.
Speed of development versus ease of debugging. Small functions are quick to write. But a business flow spread across fifteen functions needs good logs and tracing, or finding the cause of a problem feels like searching for a lost sock in a big house.
10Security
Security answers two questions. Who may call my function? And what may my function do once it runs?
Who may call it: invoker permissions
By default a function is private. Only callers with the right permission, called the invoker role, may wake it. You can choose to allow anyone on the internet to call it, which suits a public website, but you should do that on purpose and never by accident. For calls between your own services, each caller proves who it is with a signed identity token, much like showing an ID card at a door.
What it may do: service accounts
Every function runs as a service account, which is an identity made for programs instead of people. That identity decides what your function can read or write. If it has too much power, a single bug or stolen token could cause great damage.
A building gives the cleaner a key to the cleaning cupboard and the hallways, not the key to the vault. Give each function only the keys it needs for its own job. This idea is called the principle of least privilege.
Protecting secrets
Passwords, API keys, and tokens must never be written inside your code or left in plain environment variables. Use Secret Manager, a service that stores secrets safely, controls who can read them, and keeps old versions. Your function asks for the secret when it needs it.
Network controls
Ingress settings decide where calls may come from: anywhere, only from inside your own private network, or only through a load balancer you control. Egress settings and VPC connectivity decide how your function reaches private resources, such as a database that has no public address. Combining these lets you build functions that are invisible from the internet but still useful inside your system.
Other protections
- Keep libraries updated. Old libraries often contain known security holes.
- Check every input. Treat anything that arrives in a request as untrusted until you have checked it.
- Verify webhook signatures. Outside services sign their messages so you can confirm they are real.
- Use your own encryption keys when rules demand it. Customer-managed keys let a team control how stored data is protected.
- Keep audit logs. They record who changed or called what, which helps during an investigation.
Leaving a function open to the whole internet while it holds powerful permissions is a classic mistake. Anyone who finds the address could trigger it. Lock the door first, then decide carefully who gets a key.
11Monitoring, Logging, and Metrics
You cannot fix what you cannot see. Cloud Functions connects to Google’s observability tools automatically.
Cloud Logging
Anything your code prints to normal output or error output is collected here. Structured logs, written in a tidy key and value form, are easy to search.
Cloud Monitoring
Charts for how many times the function ran, how long it took, how many instances existed, and how much memory it used.
Error Reporting
Groups similar crashes together so you can see which problem is most common and when it began.
Cloud Trace
Follows one request across several services so you can see which step was slow.
The numbers worth watching
- Execution count. How often the function runs. A sudden jump or drop is a warning sign.
- Execution time. Look at the slow end of the range, not just the average. A few very slow runs can hurt real users.
- Error rate. The share of runs that fail. Set an alert when it rises above a normal level.
- Instance count. Shows how hard the platform is working to keep up.
- Memory use. If it is close to the limit, a crash is coming.
Set up alerting policies so the right person gets a message when something drifts out of normal range. Also add a correlation identifier, a unique label copied through every function in a chain. With that label you can search one word in the logs and see the whole story of a single customer order from start to finish.
12Design Patterns and Anti-patterns
A pattern is a proven way to solve a common problem. An anti-pattern is a popular way to cause one.
Helpful patterns
Fan-out
One event is published to a topic and many functions react in parallel, each doing its own job. The photo example in Chapter 6 uses this pattern.
Queue-based load levelling
Put a queue between a bursty source and a delicate target. The queue absorbs the rush and functions drain it at a safe speed.
Idempotent consumer
Record which event identifiers have already been handled, so a repeated delivery changes nothing.
Dead-letter topic
Messages that keep failing are moved aside into a special topic. Engineers can study them later instead of letting them clog the main flow.
Webhook receiver
A tiny HTTP function accepts a message from an outside service, checks its signature, and quickly hands the real work to a queue.
Anti-patterns to avoid
What it looks like
A function writes a file into the same bucket that triggers it. The new file wakes the function again, which writes another file, and so on.
Why it hurts
This endless loop can run thousands of times in minutes and produce a very large bill.
Better approach
Write results into a different bucket or folder that has no trigger, and add a maximum instances limit as a safety brake.
What it looks like
Function A calls function B and waits, B calls C and waits, and so on in a long synchronous chain.
Why it hurts
You pay for every function while it waits. One slow link slows the whole chain, and one failure breaks everything.
Better approach
Connect functions with messages so each step finishes quickly and passes the baton onward.
More things to steer clear of
- The giant function. One function that does twenty jobs is slow to start, hard to test, and hard to secure. Keep each one focused.
- Hidden state. Storing user data in a global variable and expecting it to still be there next time.
- Heavy work in setup code. Loading large files at startup makes every cold start longer.
- Unlimited scaling against a small database. A thousand instances opening a thousand database connections can knock the database over.
- Ignoring retries. Turning retries on without making the function safe to repeat.
13Best Practices and Common Mistakes
A checklist of habits that experienced engineers rely on every day.
Habits that work
- One job per function. Small functions are easy to name, test, and replace.
- Reuse expensive things. Create database clients and similar helpers once in the setup area, outside the main handler, so warm instances can reuse them.
- Use lazy loading. Load rarely used libraries only at the moment they are needed.
- Keep dependencies lean. Fewer and smaller libraries mean faster cold starts and fewer security worries.
- Use a dedicated service account for each function. Do not share one powerful identity across everything.
- Pin library versions. This keeps today’s working build the same as tomorrow’s.
- Write idempotent code. Assume every event may arrive twice.
- Return quickly from HTTP functions. If real work will take long, accept the request, queue the job, and answer at once.
- Use minimum instances for user-facing paths. One or two warm instances can remove most visible slowness.
- Automate deployment. Use a pipeline so every release follows the same tested steps.
- Use revisions and gradual rollout. In the second generation you can send a small share of traffic to a new version first and roll back fast if it misbehaves.
Mistakes beginners often make
| Mistake | What goes wrong | Fix |
|---|---|---|
| Passwords inside the code | Anyone who reads the code can steal them | Store them in Secret Manager |
| Using the default powerful identity | A bug can reach too many resources | Create a narrow service account |
| Timeout left at the maximum | A stuck run keeps costing money | Set a sensible limit |
| No maximum instance limit | A traffic spike or a loop overloads other systems | Set a ceiling that fits downstream capacity |
| Writing to local disk for permanent storage | Local files vanish when the instance goes away | Use Cloud Storage or a database |
| Printing secrets in logs | Logs can be read by many people | Mask or never log sensitive values |
| Skipping local tests | Slow deploy and test cycles | Use the Functions Framework on your laptop |
14Real-World Usage Examples
Here are common ways teams use Cloud Functions. The scenarios are typical examples, not claims about any single company.
Image and video processing
A social photo app resizes every upload into several sizes, adds a watermark, and checks for unsafe content. Each upload triggers the work, and thousands of uploads in a minute simply start thousands of instances.
Online shop order events
When an order is saved, a function emails a receipt, another updates stock, and a third tells the delivery partner. A busy sale day scales up on its own, and a quiet night costs almost nothing.
Webhook handling
Payment providers, source-code hosts, and chat tools send small messages to a web address whenever something happens. A function receives each message, checks its signature, and passes it along for processing.
Data clean-up and loading
When a spreadsheet export lands in a bucket, a function reads it, fixes bad rows, and loads the clean data into BigQuery, Google’s analytics warehouse, ready for reports.
Scheduled housekeeping
Every night a timer wakes a function that deletes old temporary files, produces a daily summary, or checks that important systems are healthy.
Mobile and web back ends
Firebase Cloud Functions, used widely by app developers, is built on the same foundation. A mobile app can call a function to run trusted logic, such as checking a purchase, that should never run on the user’s phone.
Automatic cloud governance
A function reacts to audit events. If someone creates a storage bucket that is open to the world, the function closes it and alerts the security team within seconds.
15Choosing the Right Tool
Cloud Functions is one of several compute choices in Google Cloud. Here is how it compares.
| Service | Best for | You manage |
|---|---|---|
| Cloud Functions | Small event-driven or HTTP code | Only the function code |
| Cloud Run | Whole containerised services and apps | The container and its contents |
| App Engine | Classic web applications with managed scaling | The application code and settings |
| Google Kubernetes Engine | Large, complex systems with many services | Clusters, nodes, and deployments |
| Compute Engine | Full control over virtual machines | Everything from the operating system up |
A simple rule of thumb: if the job is small and reacts to something, choose Cloud Functions. If you already have a container or a bigger application, choose Cloud Run. If you need very tight control or run a huge platform, look at Kubernetes or virtual machines. Because the second generation runs on Cloud Run, moving up from a function to a full service later is usually a smooth step.
Is it fine to start with a function and outgrow it? Yes. Many successful systems began with a few functions and grew into larger services as needs became clearer. Starting small is a feature, not a limit.
16Frequently Asked Questions
17Summary and Key Takeaways
What to remember
- Cloud Functions runs your small piece of code on demand, with no servers for you to manage, and you pay only while the code runs.
- Triggers wake functions up. Use HTTP for answers people wait for, and events from Pub/Sub, storage, or databases for background work.
- Cold starts are the main speed cost. Reduce them with lean code, small libraries, and minimum instances where it matters.
- Functions must be stateless and repeat-safe. Keep memory out of the plan, and assume any event can arrive twice.
- Security has two halves. Control who can call the function, and give the function only the permissions it truly needs. Keep secrets in Secret Manager.
- Watch your system. Use logs, metrics, traces, and alerts, and protect other systems with maximum instance limits and queues.
- Choose second generation for new projects, and move to Cloud Run or another service when your needs outgrow a single function.