Prepare and test your skills
Prepare and test your skills
Deployment Models for Cloud Run and Cloud Functions are the three serverless shapes for running code without managing servers or clusters. Cloud Run (opens in a new tab) runs containers and services on Google's scalable infrastructure, while Cloud Run functions (opens in a new tab) (formerly Cloud Functions) runs lightweight, event-driven functions. Together they support long-lived request-driven services, finite batch jobs, and single-purpose event handlers with automatic provisioning, instant autoscaling to zero, and pay-per-use billing rounded up to the nearest 100 milliseconds.
Cloud Run services are request-driven deployments that run containerized applications in response to web requests or events. A developer provides source code or a container image, and Cloud Run builds the container when needed, routes incoming requests to back-end container instances, and performs load balancing automatically. Each revision automatically scales to the number of container instances needed to handle all incoming requests, and a revision with no traffic scales to zero by default. An operator can set minimum instances to keep one or more instances warm and idle to reduce cold starts, trading higher cost for lower latency.
Cloud Run services are best suited for stateless web services, APIs, and event-driven services built with mature web technologies such as Nginx, Express.js, and Django. A service container can access a SQL database on Cloud SQL (opens in a new tab) over the network and render dynamic HTML pages, but the container itself remains ephemeral. Because Cloud Run abstracts infrastructure management, teams deploy updates quickly and pay only for the time code runs.
Cloud Run jobs are container executions designed to run to completion for finite batch and background work. A job starts a container, runs its task such as updating product catalogs or analyzing user behavior, and then finishes, with logs available for review after execution. Unlike a service that waits for requests, a job does not serve traffic and does not scale in response to concurrent requests. Choose Cloud Run jobs when the work is periodic processing, data transformation, or operational tasks that start, do work, and exit.
Cloud Run functions are event-driven deployments for single-purpose pieces of logic that respond to cloud events. An event from storage, messaging, or another Google Cloud service invokes the function, the platform provisions compute automatically, runs the code, and scales out as event volume grows. Data flows from the event source through Eventarc or Pub/Sub to the function, and the function can then call downstream systems such as a Cloud Run service to start broader workflows. For example, a Cloud Run function can initiate batch processing jobs on Cloud Run, enabling seamless event-to-batch workflows without managing servers.
Cloud Run functions fit naturally with other inherently elastic serverless services such as BigQuery, Spanner, Eventarc, Workflows, and Pub/Sub. Unlike autoscaling in virtual-machine systems that requires fine-tuning rules, serverless autoscaling for functions is instant and can scale down to zero resources when no events arrive. Choose Cloud Run functions when the problem is reacting to events with small, independent units of code rather than serving sustained HTTP traffic or running a full containerized application.
Storage, networking, and operations for Cloud Run define where state lives, how traffic arrives, and how behavior is observed. Files can be written temporarily inside a container instance for processing, but that storage comes out of the available memory for the service and disappears when the instance stops. For persistent storage, the service depends on external systems:
Networking for Cloud Run starts with automatic request routing from clients to the Cloud Run service by default. Operators can place an HTTP(S) load balancer in front to enable Cloud CDN caching, serve traffic from multiple regions, or add middleware such as API Gateway. To reach private resources, a Cloud Run service sends outbound traffic directly to a Virtual Private Cloud (VPC) network using Direct VPC egress, and operators can add serverless network endpoint groups for enterprise controls. Operations are built in with no setup required for core monitoring: request logs created automatically for services and container logs emitted from code flow to Cloud Logging, while metrics, uptime checks, and alerts flow to Cloud Monitoring where metrics for fully managed Cloud Run carry no charge.
Exam tip: Cloud Run containers are ephemeral and temporary file writes consume service memory, so any data that must survive must be written to Cloud Storage, Firestore, Cloud SQL, or another external store.
Selecting a deployment model for Cloud Run depends on packaging, trigger shape, and reuse of existing work. Cloud Run accepts existing containerized workflows directly, while Cloud Run functions accept function code that handles discrete events. The choice determines what unit is deployed and how traffic or events flow to it:
| Deployment model | Primary unit | Trigger and flow | Choose when |
|---|---|---|---|
| Cloud Run services | Container image or source code | HTTP requests flow from clients to revision instances that scale with concurrency | The workload is a stateless web service, API, or containerized app using frameworks such as Nginx, Express.js, or Django |
| Cloud Run jobs | Container task | Manual or scheduled execution runs the container to completion | The workload is finite batch processing such as catalog updates or behavior analysis |
| Cloud Run functions | Event-driven function | Cloud events flow from Eventarc or Pub/Sub to the function, which can call Cloud Run | The workload is lightweight, event-driven logic that starts workflows or integrates messaging services |
Scalability and resource optimization for serverless computing means using platforms that add and remove capacity automatically to match traffic while minimizing idle cost. Cloud Run (opens in a new tab) and Cloud Run functions provide this elasticity with instant autoscaling that can scale down to zero resources when there is no traffic. Unlike Compute Engine (opens in a new tab), which requires fine-tuned autoscaling rules, serverless services scale without operator configuration and start quickly even after scaling to zero. Efficient use depends on setting baselines, keeping apps stateless, and minimizing startup time.
Serverless autoscaling is automatic adjustment of compute instances in response to incoming requests without manual provisioning. Traffic flows from clients to the Cloud Run service or function, and the platform adds container or function instances to handle the current load and removes them when load drops. When a Cloud Run service receives no traffic, it scales in to zero instances by default, so no compute is paid for while idle. This behavior contrasts with virtual machines or Kubernetes nodes that must be created and initialized and often require a minimum baseline even with no traffic.
Scale-to-zero compute works best when surrounding integration and data services also expand and contract without pre-provisioned servers. Inherently elastic serverless building blocks include:
How Cloud Run and Cloud Run functions add capacity explains the relationship between incoming traffic, the autoscaler, and available instances. Requests flow from the load balancer or direct client to the service, the autoscaler determines the number of container instances necessary for the current load, and traffic is routed only to available instances. Cloud Run functions scaling assigns each inbound request to an instance of the function, and if request volume exceeds the number of existing instances, the platform automatically starts new instances. Both models depend on stateless design, where no local persistent data is tied to a single instance, so any instance can handle any request and instances can be created or destroyed unexpectedly.
| Compute option | Scaling control | Behavior when idle |
|---|---|---|
| Compute Engine with managed instance groups | Operator defines autoscaling policies with minimum and maximum instances and trigger conditions | Typically keeps a minimum set of virtual machines running because new VMs take time to create and initialize |
| Google Kubernetes Engine (GKE) | Operator configures cluster autoscaling to add or remove nodes based on workload metrics | Typically keeps baseline nodes running because new nodes need to be created and initialized |
| Cloud Run services and functions | Platform scales automatically based on incoming traffic without required configuration | Scales to zero instances when there is no traffic and starts quickly on new demand |
The comparison shows the tradeoff between configuration flexibility and management effort: virtual machines and containers offer more control but need baselines, while serverless trades control for instant scaling and zero idle cost.
Baselines, profiles, and stateless design determine how much capacity stays ready and how safely instances can be replaced. A scaling profile is the combination of performance goals, cost limits, and minimum resources that guides autoscaling behavior. A consumer-facing app with strict latency goals may justify more baseline capacity to respond quickly, while an internal app tolerant of small delays may use a less aggressive profile to keep costs low. Autoscaling behavior should be configured based on key application metrics, cost profile, and defined minimum required resources.
For stateless components, storing session state outside the instance, such as in Memorystore for Redis, allows horizontal scaling to remain seamless because any compute instance can handle requests from any user. The compute tier therefore depends on the external state store, while the state store does not depend on any single compute instance. This separation lets the platform add or remove instances without losing user sessions.
Reducing startup time and cold starts focuses on how quickly new capacity can serve traffic after scaling to zero. Startup time determines whether new capacity comes online fast enough to handle increasing load, and a cold start is the delay when a scaled-to-zero instance must initialize before serving its first request. Containerized apps help because a container packages code, runtime, system tools, libraries, and settings into a lightweight unit that is portable and typically fast to start. Cloud Run hosts these stateless containers on a serverless platform, which makes them suitable for scalable and resilient apps that grow and shrink frequently. To reduce cold-start impact before a known traffic spike, pre-warm resources ahead of time because autoscaling alone may not catch up with the velocity of event traffic.
App-level optimizations for fast startup focus on reducing work done before the first request is served:
These steps lower the time from instance creation to serving traffic, which improves both scale-out speed and user-perceived latency when instances start from zero.
Exam tip: Pre-warm virtual machines, caches, and serverless components to prevent cold starts before peak traffic, while Cloud Load Balancing does not require pre-warming.
Secure integration and event-driven orchestration is the practice of connecting serverless workloads to private resources without exposing traffic to the internet, while using events and identities to decouple components. In Google Cloud, Cloud Run (opens in a new tab) handles request-driven containers and Cloud Run functions (2nd gen) handles event-driven code, and both use the same building blocks for secure connectivity: Serverless VPC Access, Shared VPC, Eventarc, Pub/Sub, and Identity and Access Management (IAM). Together these services create asynchronous architectures where producers emit events, queues deliver them, and least-privilege identities authorize each step.
Private connectivity from serverless to Virtual Private Cloud (VPC) resources is provided by a Serverless VPC Access connector that bridges the serverless environment to a VPC network. Requests flow from the Cloud Run service or Cloud Run functions instance through the connector into the VPC subnet, and responses return the same way, so traffic to Compute Engine, Google Kubernetes Engine, Cloud SQL, or internal servers is never exposed to the public internet. The recommended design uses Shared VPC, which centralizes network policy in a host project while serverless workloads run in a service project. By default the connector is created in the service project, but it can be created in the host project by setting connector_on_host_project to true.
Trust boundaries are enforced with ingress controls, firewall rules, and perimeters around that path. On ingress, an external Application Load Balancer receives internet traffic and forwards it to Cloud Run, and the Internal and Cloud Load Balancing ingress setting restricts Cloud Run so it accepts requests only from the load balancer. Google Cloud Armor sits with the load balancer as a web application firewall against denial of service and web attacks. On egress, VPC firewall rules deny all egress except TCP port 443 to restricted.googleapis.com, which forces workloads to use Private Google Access for Google APIs and ensures only services that support VPC Service Controls are reachable. VPC Service Controls then places Cloud Run services and supporting resources in a security perimeter that isolates data, controls authorization, and enables secure data exchange.
Asynchronous orchestration with Eventarc (opens in a new tab) and Pub/Sub decouples event producers from serverless consumers through queued, asynchronous delivery. Eventarc routes events from Google Cloud sources and encrypts those events in transit and at rest, while Pub/Sub queues the events and delivers them as triggers to Cloud Run functions. Because the producer does not call the function directly, each side can scale, retry, and evolve independently. Cloud Run functions in this blueprint is deployed with an internal IP address only and without public internet access, so the function can only be reached through its configured trigger and can only reach private resources through the VPC connector.
A left-to-right process flow showing Cloud Storage, Scheduler or BigQuery events routed by Eventarc to Pub/Sub, triggering an internal-only Cloud Run function, which reaches private resources through a VPC connector or starts a Cloud Run batch job.
A common flow for a storage-driven workload moves data through an ordered sequence:
This same pattern supports scheduled aggregation against Cloud SQL and BigQuery-triggered processing, with Cloud Scheduler or BigQuery as the source and VPC firewall rules controlling flow into the destination subnet.
Least-privilege identity with Identity and Access Management (IAM) means every human, group, and workload identity receives only the permissions required for its task. Access is organized with IAM groups bound to projects, such as a serverless administrator with roles/run.admin plus roles/compute.networkViewer and roles/compute.networkUser, a developer with roles/run.developer or roles/cloudfunctions.developer plus Artifact Registry writer access, and an end user or invoking service with only roles/run.invoker or roles/cloudfunctions.invoker. Resource hierarchy and separation of duties isolate administration in security and service projects while keeping runtime access narrow.
Workload identities are further split so no single service account carries broad power:
roles/run.invoker and roles/secretmanager.secretAccessor to run code and read only assigned secrets.roles/compute.networkUser so the Serverless VPC Access connector can create firewall ingress and egress rules in the host project.roles/vpcaccess.user to use the connector, while a separate serverless service identity holds roles/artifactregistry.reader to pull container images.Secrets themselves are stored in Secret Manager and mounted as a volume into Cloud Run or Cloud Run functions, which provides stronger protection than passing secrets as environment variables. Images and binaries are stored in Artifact Registry and protected with customer-managed encryption keys (CMEKs) from Cloud Key Management Service (Cloud KMS), with keys kept in the same region as the resources and rotated every 30 days by default.
Choosing between requests and events for secure flows depends on trigger type, language flexibility, and container control. Cloud Run and Cloud Run functions differ in which service should start an event-driven flow and how external traffic reaches it:
| Service | Trigger | Language and runtime control |
|---|---|---|
| Cloud Run | Requests, such as HTTP requests forwarded by the external Application Load Balancer | Any programming language with full control of container configuration |
| Cloud Run functions | Events, such as Pub/Sub messages, Cloud Storage changes, or schedule events | Limited to supported runtimes, with Google managing containers and web server infrastructure |
Choose Cloud Run when external clients send requests that must pass through load balancing, Cloud Armor, and optionally Identity-Aware Proxy (IAP) for central application-level authorization. Choose Cloud Run functions when work should start only after something changes in data, messaging, or time, and let Eventarc and Pub/Sub deliver that change as the trigger.
Exam tip: Cloud Run accepts requests only from the load balancer when ingress is set to Internal and Cloud Load Balancing, while Cloud Run functions with internal-only networking is reached only through its event trigger, not directly from the internet.
Use Cloud Run services for stateless web services, APIs, and containerized apps that scale with HTTP request concurrency, Cloud Run jobs for finite batch work that runs a container to completion, and Cloud Run functions for lightweight, event-driven logic that responds to cloud events from Eventarc or Pub/Sub. Services scale with concurrent requests, jobs do not serve traffic and do not scale in response to concurrent requests, and functions can call Cloud Run to start broader workflows.
Cloud Run services and Cloud Run functions automatically add container or function instances to handle the current load and scale to zero instances by default when there is no traffic, so no compute is paid for while idle. Unlike Compute Engine with managed instance groups and Google Kubernetes Engine (GKE), which typically keep minimum virtual machines or nodes running, serverless scaling requires no operator configuration and starts quickly on new demand.
Persistent data must be stored outside the container in Cloud Storage for objects and website assets, Firestore for document and application state, or Cloud SQL for relational data accessed over the network. Files written temporarily inside a Cloud Run container consume service memory and disappear when the instance stops because containers are ephemeral.
Requests flow from the Cloud Run service or Cloud Run functions instance through a Serverless VPC Access connector into the VPC subnet, so traffic to Compute Engine, Google Kubernetes Engine, Cloud SQL, or internal servers is never exposed to the public internet. The recommended design uses Shared VPC to centralize network policy in a host project while serverless workloads run in a service project.
An e-commerce organization hosts a latency-sensitive public web service on Google Cloud using App Engine standard environment with automatic scaling. The service currently scales down to zero instances during inactive overnight periods to save costs. However, during sudden morning traffic spikes, users experience latency degradation caused by instance cold starts and request queuing before new instances can spin up.
You need to optimize the autoscaling behavior to satisfy the following requirements:
Which configuration should you specify in the application's automatic scaling configuration?
Last updated