GcpIntermediate

Serverless Computing with Google Cloud Functions

9 min read

TL;DR

Explore serverless computing with Google Cloud Functions. Learn how to build, deploy, and manage event-driven applications with automatic scaling and zero infrastructure management.

Serverless Computing with Google Cloud Functions

Executive Summary

Cloud Functions runs single-purpose code in response to events: an HTTP request, a Pub/Sub message, a file landing in a Cloud Storage bucket, a Firestore write. You supply a function and a trigger; Google supplies the machine, the scaling, and the bill only for the compute you consume. This guide covers the two function shapes (HTTP and background/event-driven), deployment with gcloud, configuration through environment variables and Secret Manager, and the disciplines that make functions reliable in production: idempotency, retry and dead-letter handling, cold-start management, least-privilege identity, and structured logging. It ends with an honest account of when a function is the wrong tool and a container on Cloud Run is the right one.

Why This Matters

Functions fail in production for architectural reasons, not syntax errors. Event-driven systems deliver events at least once, so a function that is not idempotent will charge a customer twice or send the email three times when a retry happens. A function that does slow work synchronously inside an HTTP request will hit timeouts under load. A function deployed with a broad service account turns one code flaw into project-wide access. And a fleet of tiny functions with no logging or tracing discipline becomes undebuggable precisely when traffic grows. The platform is simple; using it well requires designing for retries, partial failure, and least privilege from the start.

Core Concepts

HTTP Functions

An HTTP function is a small web handler. It receives a request object and returns a response, which suits webhooks, lightweight APIs, and glue endpoints:

# main.py
from flask import escape

def hello_http(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
    """
    request_json = request.get_json(silent=True)
    request_args = request.args

    if request_json and 'name' in request_json:
        name = request_json['name']
    elif request_args and 'name' in request_args:
        name = request_args['name']
    else:
        name = 'World'
    return f'Hello {escape(name)}!'

Return structured responses with explicit status codes for anything real; callers and load balancers depend on them:

# http_function.py
from flask import jsonify

def http_function(request):
    """HTTP function with JSON response.
    """
    request_json = request.get_json(silent=True)

    if request_json and 'message' in request_json:
        message = request_json['message']
        return jsonify({'status': 'success', 'message': message})
    else:
        return jsonify({'status': 'error', 'message': 'No message provided'}), 400

Background Functions and Triggers

Background functions respond to events and return nothing to a caller; success is a side effect completed without error. Pub/Sub triggers suit decoupled processing pipelines, and Cloud Storage triggers suit file processing such as image resizing or import jobs:

# main.py
def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         event (dict):  The dictionary with data specific to this type of
                       event.
         context (google.cloud.functions.Context): Metadata of triggering event.
    Returns:
        None
    """
    import base64

    print("""This Function was triggered by messageId {} published at {}
    """.format(context.event_id, context.timestamp))

    if 'data' in event:
        name = base64.b64decode(event['data']).decode('utf-8')
    else:
        name = 'World'
    print('Hello {}!'.format(name))

# storage_function.py
def process_image(event, context):
    """Background function triggered by Cloud Storage.
    """
    file = event
    print(f"Processing file: {file['name']}")

    # Add your image processing logic here

    print(f"File {file['name']} processed successfully")

The context object carries the event ID, which is your idempotency key: record processed event IDs and skip duplicates, because the platform guarantees delivery, not exactly-once processing.

Deployment and Configuration

Deployment declares the runtime, the trigger, and the function's identity and limits in one command:

# Deploy HTTP function
gcloud functions deploy hello_http \
  --runtime python39 \
  --trigger-http \
  --allow-unauthenticated

# Deploy Pub/Sub function
gcloud functions deploy hello_pubsub \
  --runtime python39 \
  --trigger-topic my-topic

--allow-unauthenticated makes an HTTP function public. That is correct for a webhook endpoint that authenticates payloads itself and wrong for almost everything else; prefer IAM-authenticated invocation and verify callers in code when a function must check identity itself:

# authenticated_function.py
from flask import abort
from google.oauth2 import id_token
from google.auth.transport import requests

def authenticated_function(request):
    """Function that requires authentication.
    """
    if request.method != 'GET':
        return abort(405)

    auth_header = request.headers.get('Authorization')
    if not auth_header:
        return abort(401)

    try:
        token = auth_header.split(' ')[1]
        claim = id_token.verify_oauth2_token(
            token, requests.Request())
        return f'Hello {claim["email"]}!'
    except Exception as e:
        return abort(401)

Configuration follows the same split as everywhere else on Google Cloud: ordinary settings as environment variables, secrets from Secret Manager, never in source:

# Set environment variables
gcloud functions deploy my-function \
  --set-env-vars FOO=bar,BAZ=qux

# Use secrets
gcloud functions deploy my-function \
  --set-secrets MY_SECRET=projects/123/secrets/my-secret:latest

Give each function its own service account with only the permissions its task needs. To reach resources inside a VPC, attach a Serverless VPC Access connector and set ingress controls so the function is not reachable from the open internet:

# vpc-connector.yaml
vpc_connector: projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME
vpc_connector_egress_settings: ALL_TRAFFIC
ingress_settings: ALLOW_INTERNAL_ONLY

Cold Starts and Performance

A cold start is the platform initialising a new instance: loading the runtime, your dependencies, and your module-level code. You cannot eliminate cold starts; you can shrink them. Keep dependencies lean, initialise clients once at module scope so warm invocations reuse them, and set minimum instances for latency-sensitive functions, accepting that you are paying to keep capacity warm:

# Initialize global variables outside function
from google.cloud import storage
client = storage.Client()

def optimized_function(event, context):
    """Function with optimized cold start.
    """
    bucket = client.get_bucket('my-bucket')
    # Function logic here

Memory allocation also controls CPU allocation on the platform, so an under-provisioned function is slow twice over. Size memory and timeout deliberately:

# Configure memory
gcloud functions deploy my-function \
  --memory=512MB \
  --timeout=60s

Errors, Retries, and Dead Letters

For event-driven functions, an unhandled exception signals failure and, if retries are enabled for the trigger, the event is redelivered. That makes the error-handling split the most important design decision in the function: raise for transient failures so the platform retries, and swallow-and-log permanent failures so a poison event does not retry forever:

# retry_function.py
def retryable_function(event, context):
    """Function with retry logic.
    """
    try:
        # Function logic here
        process_data(event)
    except TemporaryError as e:
        # Retry on temporary errors
        raise e
    except PermanentError as e:
        # Don't retry on permanent errors
        logging.error(f"Permanent error: {e}")
        return

Configure a dead-letter topic so events that exhaust retries are preserved for inspection instead of dropped:

# Configure dead letter queue
gcloud functions deploy my-function \
  --dead-letter-topic=projects/PROJECT_ID/topics/dead-letter

Logging and Monitoring

Use structured logs: severity and message as fields, correlated with the invocation, so Cloud Logging can filter and alert on them. Alert on error ratio and on execution time, not just on invocation count; a function can be invoked constantly and failing constantly. Watch for the silent failure modes specific to functions: timeouts that truncate work, out-of-memory kills after a dependency grows, and a dead-letter topic filling up unnoticed.

Decision Framework

SituationRecommendation
Webhook, callback, or small API endpointHTTP function with IAM or in-code authentication
Processing Pub/Sub messages or storage uploadsBackground function, idempotent, with a dead-letter topic
Scheduled housekeepingFunction triggered by Cloud Scheduler
Work that may run for a long time or needs a custom containerCloud Run instead of a function
Latency-critical endpoint with strict cold-start budgetFunction with minimum instances set, or Cloud Run
Function needs VPC resourcesServerless VPC Access connector with internal-only ingress

Implementation Checklist

  • [ ] Every event-driven function is idempotent, keyed on the event ID
  • [ ] Transient errors raise to trigger retry; permanent errors are logged and swallowed
  • [ ] A dead-letter topic is configured and alerted on
  • [ ] Each function runs as its own least-privilege service account
  • [ ] Secrets come from Secret Manager; none are in source or plain environment files
  • [ ] Memory and timeout are set deliberately, not left at defaults
  • [ ] Clients are initialised at module scope to reuse warm instances
  • [ ] Structured logging is in place, with alerts on error ratio and duration
  • [ ] Public invocation (--allow-unauthenticated) is used only where payloads are independently authenticated
  • Trade-offs

    Functions trade control for convenience. You give up the server, the runtime lifecycle, and long-running execution; timeouts are hard limits, local state is ephemeral, and debugging a distributed chain of functions is harder than debugging one service with a debugger attached. Cold starts add tail latency that no amount of code tuning fully removes. Pricing is attractive at low and spiky volumes and less obviously so at sustained high volume, where a container running continuously can be cheaper per request. None of this is a defect; it is the shape of the tool, and the skill is matching workload shape to it.

    When Not to Use

  • Long-running or compute-heavy jobs: video encoding, large ETL, and model training belong on Cloud Run jobs, Compute Engine, or GKE, where execution time and resources are yours to set.
  • A full web application with many routes and shared middleware: that is a service, not a function. Put it on Cloud Run and keep functions for the event-driven edges.
  • Work requiring persistent connections or in-memory state across requests: instances are ephemeral and interchangeable; keep state in a database, cache, or storage bucket.
  • Conclusion

    Cloud Functions is at its best doing small, well-defined work in response to events, with idempotency, retries, and least privilege designed in from the first deploy. Treat each function as a durable part of a system rather than a script that happens to run in the cloud, and the platform's simplicity survives production. When the work outgrows the model, graduate it to Cloud Run rather than stretching the function past its limits.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.