13 min read

    17 - Cloud Functions - Event-Driven Code

    gcpcloudserverlesscloud-functionsfaas

    Welcome to Day 17 of Learn GCP in 30 Days! Yesterday, you deployed containerized web apps to Google Cloud Run. Today, we go one level simpler: writing individual snippets of code that run automatically in response to events using Google Cloud Functions.

    ๐ŸŽฏ

    Today's Goal Today, you will understand what Event-Driven Architecture means in plain English, why Cloud Functions (Function-as-a-Service / FaaS) let you run microservices without writing Dockerfiles or web servers, and how to write, deploy, and trigger your first Python Cloud Function live!


    ๐Ÿ”” The Core Problem: The Overhead for Tiny Tasks

    Imagine you want to build a simple helper task: "Whenever a user uploads a profile picture, automatically resize it to a thumbnail."

    mermaid

    What Existed Previously:

    To run a tiny 15-line script, developers had to write Dockerfiles, configure web servers, launch Virtual Machines, and write infinite background loops (while True: check_new_files()) to constantly poll the system.

    Problems Faced:

    • ๐Ÿ“ฆ Container Boilerplate Overkill: Writing and building a Docker container just to run 1 small function is tedious and slow.
    • ๐Ÿ’ธ Wasted Idle Compute: Keeping a server running 24/7 just waiting for someone to upload a file wastes money.
    • ๐Ÿ”„ Polling Latency: Constant polling wastes CPU cycles and creates delays between when an event happens and when the code runs.

    How Present Technology Solves It:

    Google created Cloud Functions (Function-as-a-Service / FaaS):

    1. Just Write the Function: You don't write Dockerfiles, configure servers, or manage networking. You write a single Python or JavaScript function.
    2. Instant Event Triggers: Google watches for events (an HTTP request, a file uploaded to Cloud Storage, a database change, or a message in Pub/Sub) and executes your function instantly!
    3. Automatic Lifecycle: The function boots up, executes the task in 200 milliseconds, and shuts down immediately. You are billed strictly for the exact milliseconds your code executes!
    mermaid

    ๐Ÿšช Real-World Analogy: The Motion-Sensor Porch Light

    mermaid
    • Traditional Server = A Porch Light Turned ON 24/7:
      • Burning electricity 24 hours a day even when nobody is at the door.
    • Cloud Function = A Smart Motion-Sensor Light:
      • Sits completely dormant at 0 Watts ($0.00 cost).
      • The moment a visitor walks in front of the sensor (The Event), the sensor trips (The Trigger), turning the light on for 10 seconds (The Execution), and turning off the moment the person leaves!

    ๐Ÿ”‘ Everyday Cloud Terms Explained in Plain English


    1. HTTP Triggers vs. Event Triggers

    Cloud Functions can be triggered in 2 main ways:

    mermaid
    • ๐ŸŒ HTTP Trigger: The function gets a public URL address. When a user or webhook visits https://...cloudfunctions.net/my-func, the function runs and returns a direct response (like an API endpoint).
    • ๐Ÿ“ฆ Event Trigger: The function runs quietly behind the scenes when a specific GCP cloud event occurs:
      • A new file is saved in a Cloud Storage bucket.
      • A new message is published to a Pub/Sub topic.
      • A document is created or updated in Firestore Database.

    2. Cloud Functions 1st Gen vs. 2nd Gen (The Modern Standard)

    Google Cloud offers two generations of Cloud Functions:

    Feature๐Ÿข 1st Generation (Legacy)๐Ÿš€ 2nd Generation (Modern Standard)
    Under the HoodCustom Google infrastructurePowered by Google Cloud Run
    Max Timeout9 minutesUp to 60 minutes
    Concurrency1 request per instanceUp to 1,000 requests per instance
    Max MemoryUp to 8 GB RAMUp to 32 GB RAM / 8 vCPUs
    Event SystemLegacy GCP event handlersPowered by Eventarc (90+ event sources)
    ๐Ÿ’ก

    Rule of Thumb Always use Cloud Functions (2nd Gen) for all new projects. It combines the extreme simplicity of writing single functions with the high concurrency and power of Google Cloud Run!


    3. Cloud Functions vs. Cloud Run: When to Use Which?

    Both are serverless and scale to zero, so how do you choose?

    mermaid
    Factorโšก Cloud Functions๐Ÿš€ Cloud Run
    What do you write?Single code file (main.py)Any containerized app (Dockerfile)
    Best ForWebhooks, file processing, event handlersFull-stack web apps, microservices, REST APIs
    ConfigurationZero setup (Google builds it)Full control over Linux OS packages & ports

    4. "Can't I Just Write This in My Main Backend Server?"

    Yes, you can! But separating background tasks into Cloud Functions solves 4 big production headaches:

    1. ๐Ÿ›‘ Don't Freeze Your Main App: Heavy tasks (resizing 4K photos or generating PDF invoices) consume 100% CPU. Offloading them ensures your main shopping cart and login pages stay blazing fast for customers.
    2. โšก Instant Viral Scaling: If 5,000 users upload files at once, Google spawns 5,000 micro-functions in parallel. Your main backend server never runs out of memory.
    3. ๐Ÿ›ก๏ธ Failure Isolation: If a bug crashes the email-sending function, your main website and payment checkout remain 100% safe and unaffected.
    4. ๐Ÿ’ฐ 99% Cost Savings on Nightly Jobs: For a daily report running at midnight for 2 minutes, pay $0.0001 per run instead of paying for an expensive 24/7 server!

    ๐ŸŽฏ Short & Sweet Decision Guide:

    What Are You Building?Best Home in GCP
    Main Website, Login API, Product CatalogCloud Run / Main Backend
    File Resizing, Payment Webhooks, Daily Midnight JobsCloud Functions

    ๐Ÿงช Hands-on Lab Activity: Write & Deploy an HTTP Cloud Function

    In this lab, you will write a lightweight Python function that accepts a user's name via URL query parameter and returns a personalized greeting!


    Step 1: Enable Cloud Functions & Cloud Build APIs

    Option A: Web Console UI

    1. Open console.cloud.google.com.
    2. Enable both Cloud Functions API and Cloud Build API.

    Option B: Cloud Shell CLI

    bash
    gcloud services enable cloudfunctions.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com run.googleapis.com
    

    Step 2: Write the Function Code in Cloud Shell

    Create a clean folder with two files: main.py (the Python code) and requirements.txt (the dependencies).

    2.1: Create Project Directory

    bash
    mkdir -p ~/gcp-functions-lab && cd ~/gcp-functions-lab
    

    2.2: Create main.py (The Function)

    bash
    cat << 'EOF' > main.py
    import functions_framework
    from flask import jsonify
    
    @functions_framework.http
    def hello_http(request):
        """HTTP Cloud Function that greets the visitor."""
        # 1. Extract name from URL query parameter (e.g. ?name=Alex) or JSON body
        request_args = request.args
        request_json = request.get_json(silent=True)
        
        if request_args and 'name' in request_args:
            name = request_args['name']
        elif request_json and 'name' in request_json:
            name = request_json['name']
        else:
            name = 'Cloud Explorer'
        
        # 2. Return a friendly JSON response
        response_data = {
            "status": "success",
            "message": f"Hello, {name}! Welcome to Google Cloud Functions (2nd Gen)!",
            "serverless": True
        }
        return jsonify(response_data), 200
    EOF
    

    Anatomy Breakdown: What is happening in main.py line-by-line?

    Code LineWhat It Does In Plain English
    import functions_frameworkImports Google's open-source library that turns normal Python functions into HTTP handlers.
    from flask import jsonifyImports Flask's JSON helper to format output cleanly for web clients.
    @functions_framework.httpThe Decorator: Tells Google Cloud that this specific function will be triggered by incoming HTTP web requests.
    def hello_http(request):The entry-point function. request contains all incoming HTTP data (headers, query params, body).
    request.argsReads URL parameters (e.g., if the user visits ?name=Alex, request.args['name'] is 'Alex').
    request.get_json(silent=True)Safely reads JSON payloads sent in POST requests without crashing if the payload is empty.
    return jsonify(response_data), 200Sends the JSON greeting back to the user with standard HTTP 200 OK success status.

    2.3: Create requirements.txt (Dependencies)

    bash
    cat << 'EOF' > requirements.txt
    functions-framework==3.*
    flask>=2.0.0
    EOF
    

    Anatomy Breakdown: What is requirements.txt?

    • Informs Google's build system which external Python packages to install automatically during deployment.

    Step 3: Deploy the Cloud Function

    Option A: Web Console UI (Click-by-Click)

    1. In the GCP Console, press / โ†’\rightarrow type Cloud Run (or Cloud Functions) โ†’\rightarrow select it.
    2. Click Create Service (or Create Function) at the top.
    3. Under Deployment Options, select Function (Use an inline editor to create a function).
    4. Fill in the configuration: - Service name: hello-http-function
      • Region: Select asia-south1 (or your nearest region)
      • Runtime: Select Python 3.11
    5. Under Authentication:
      • Select Allow public access (Allows direct web access without authentication checks).
    6. Under Billing:
      • Keep default Request-based (Charged only when processing requests; scale to zero when idle).
    7. In the Inline Code Editor:
      • Paste your Python code into main.py.
      • Paste your dependencies into requirements.txt.
      • Set Entry point: hello_http.
    8. Click Create (or Deploy)!
    9. Wait 30 to 60 seconds. A green checkmark will appear with your live public HTTPS URL!

    Option B: Cloud Shell CLI (Fast Track)

    Run this single command from inside ~/gcp-functions-lab:

    bash
    gcloud functions deploy hello-http-function \
        --gen2 \
        --runtime=python311 \
        --region=asia-south1 \
        --source=. \
        --entry-point=hello_http \
        --trigger-http \
        --allow-unauthenticated
    

    Anatomy Breakdown: What does each flag in gcloud functions deploy do?

    CLI FlagWhat It Does In Plain English
    gcloud functions deploy hello-http-functionNames our serverless function hello-http-function.
    --gen2Deploys using modern 2nd Generation architecture (powered by Cloud Run).
    --runtime=python311Tells Google to execute the code using Python 3.11 environment.
    --region=asia-south1Deploys the function in Google's Mumbai data center.
    --source=.Tells Google to upload the code from the current folder (.).
    --entry-point=hello_httpSpecifies which Python function to call when a request arrives (def hello_http).
    --trigger-httpAssigns an automatic public HTTPS web URL to the function.
    --allow-unauthenticatedAllows public internet visitors to invoke the URL without an IAM login.

    Step 4: Test Your Live Cloud Function

    1. Once deployment finishes, retrieve your function's live HTTPS URL:

      bash
      gcloud functions describe hello-http-function \
          --gen2 \
          --region=asia-south1 \
          --format="value(serviceConfig.uri)"
      
    2. Test default invocation:

      bash
      curl $(gcloud functions describe hello-http-function --gen2 --region=asia-south1 --format="value(serviceConfig.uri)")
      

      Output:

      json
      {
        "message": "Hello, Cloud Explorer! Welcome to Google Cloud Functions (2nd Gen)!",
        "serverless": true,
        "status": "success"
      }
      
    3. Test with a custom name parameter:

      bash
      curl "$(gcloud functions describe hello-http-function --gen2 --region=asia-south1 --format="value(serviceConfig.uri)")?name=Alex"
      

      Output:

      json
      {
        "message": "Hello, Alex! Welcome to Google Cloud Functions (2nd Gen)!",
        "serverless": true,
        "status": "success"
      }
      

    ๐Ÿงน Step 5: Clean Up All Resources (Credit Safety Guarantee)

    To guarantee your trial balance remains completely untouched ($0.00), delete the function and local directory:

    Option A: Web Console UI

    1. Go to Cloud Functions โ†’\rightarrow Check the box next to hello-http-function.
    2. Click Delete at the top โ†’\rightarrow Confirm deletion.

    Option B: Cloud Shell CLI

    bash
    # 1. Delete the Cloud Function
    gcloud functions delete hello-http-function \
        --gen2 \
        --region=asia-south1 \
        --quiet
    
    # 2. Clean up local files
    rm -rf ~/gcp-functions-lab
    

    Signal vs. Noise: Key Concepts & Noise Filter

    ๐Ÿง 

    Good to Know (Key Concepts)

    • Cloud Functions: Lightweight, event-driven serverless compute to execute single snippets of code without managing servers or Dockerfiles.
    • 2nd Gen Standard: Cloud Functions 2nd Gen is powered by Cloud Run behind the scenes, offering up to 60-minute execution timeouts and concurrency.
    • Entry Point: The exact Python function name in your code that GCP calls when triggered.
    • Triggers: Can be HTTP URLs or background cloud events (Cloud Storage bucket uploads, Pub/Sub messages, Firestore changes).
    โ„น๏ธ

    Noise Filter (Don't Memorize)

    • Do NOT memorize low-level Eventarc CloudEvent specification schemas; standard Python dictionaries give you all event payload data directly.
    • Do NOT worry about 1st Gen Cloud Functions limitations; always use --gen2 for modern workflows.

    Common Doubts & Interview Traps

    Q1: What is the difference between AWS Lambda and Google Cloud Functions?

    • Answer: Both are Function-as-a-Service (FaaS) platforms. However, Google Cloud Functions (2nd Gen) runs on top of Google Cloud Run, supporting concurrency (multiple requests per instance) and up to 60-minute execution timeouts, whereas standard AWS Lambda functions are strictly single-request per instance with a 15-minute maximum timeout.

    Q2: What is "Idempotency" and why is it crucial for Event-Driven Functions?

    • Answer: In cloud networking, an event (like a message or file upload) might occasionally be delivered more than once (at-least-once delivery). An Idempotent function ensures that if the exact same event runs twice, it produces the exact same safe result without creating duplicate database records or charging a customer twice!

    Q3: Can a Cloud Function process background files uploaded to Google Cloud Storage?

    • Answer: Yes! By changing the trigger from --trigger-http to --trigger-event-filters="type=google.cloud.storage.object.v1.finalized", Google will automatically trigger the function whenever a file is uploaded to your bucket.

    Daily Practice Drill & Self-Check

    Test your understanding of today's lesson:

    text
    // Try answering these:
    1. What is the real-world analogy for an event-driven Cloud Function: a 24/7 porch light or a motion-sensor light?
    2. In a Cloud Function deployment, what parameter specifies which Python function name inside main.py should be executed?
    3. Which generation of Cloud Functions runs on top of Google Cloud Run infrastructure: 1st Gen or 2nd Gen?
    
    ๐Ÿ’ก Click for Solutions
    1. A Motion-Sensor Light! It stays 100% off drawing zero power until an event triggers it.
    2. --entry-point!
    3. 2nd Gen!

    ๐ŸŽ‰ Congratulations! You have completed Day 17!

    You have mastered the principles of Event-Driven Serverless architecture, written and deployed a Python Cloud Function (2nd Gen), and understood how microservices execute instantly on demand.

    Tomorrow on Day 18, we will explore how asynchronous events flow across Google Cloud with Eventarc and Pub/Sub Integration!


    โ† 16 - Cloud Run - Serverless Container Apps | Next Topic โ†’ 18 - Eventarc and Pub/Sub Integration