AlgoViz

Google Cloud Functions

medium 29 min

Google Cloud Functions, called Cloud Run functions since August 2024, runs one piece of your code when a request or an event arrives.

See it run

Deploy source, wake a cold function, let one instance serve many, survive a repeated event and release in steps.

Operations

Deploy

From source to a running Cloud Run service.

Step 1 of 4

Upload

Your projectDeveloperCloud StoragesourceCloud BuildbuildpacksArtifact RegistryimageCloud RunserviceInstanceyour function

gcloud run deploy sends your source to a bucket.

Step 1: Upload

upload(source)image = buildpacks.build(source, "functions-framework")registry.push(image)revision = run.deploy(image)run.route_traffic(revision)
Time
minutes
What you need
a project

Say that the function is a container in the end. That is why it can grow out of the form.

In the real world

The same google cloud functions doing real jobs. Pick one and step through it.

Functions grow in seconds, the database does not.

Step 1 of 3

Calm

Your projectCallersCloud Runrouter, scalerInstance 110 connectionsDatabase10 of 200

One instance holds 10 connections.

Step 1: Calm

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Work after the reply

    critical

    The CPU is taken away and the work stalls.

    Wrong
    def handler(request):    Thread(target=send_mail).start()    return "ok"
    Right
    def handler(request):    tasks.create(send_mail_task)   # Cloud Tasks    return "ok"
  • Request data in a global

    critical

    Two requests share the process and mix their data.

    Wrong
    current_user = Nonedef handler(request):    global current_user    current_user = request.args["user"]
    Right
    def handler(request):    user = request.args["user"]    return page(user)
  • Client made per request

    major

    Every call pays for a new connection.

    Wrong
    def handler(request):    client = storage.Client()
    Right
    client = storage.Client()def handler(request):    ...
  • Handler that is not repeatable

    major

    Events come at least once, and the second run counts again.

    Wrong
    def on_order(event):    total.add(event.data["amount"])
    Right
    def on_order(event):    ledger.create(id=event["id"], amount=event.data["amount"])

Interview tips

  • How to explain it

    • Source becomes a container.
    • Requests and events are HTTP.
    • Zero to many instances.
  • Memory trick

    • In flight = rate times time.
    • 80 per vCPU.
    • Limit from the database.
  • Reach for it when

    • A file or message arrives.
    • A webhook calls.
    • Load has quiet hours.
  • Be careful with

    • Retries off in the console.
    • Globals under concurrency.
    • Loops through a bucket.