Google Cloud Functions
medium 29 minGoogle 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
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
One instance holds 10 connections.
Step 1: Calm
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Work after the reply
criticalThe CPU is taken away and the work stalls.
Wrongdef handler(request): Thread(target=send_mail).start() return "ok"Rightdef handler(request): tasks.create(send_mail_task) # Cloud Tasks return "ok"Request data in a global
criticalTwo requests share the process and mix their data.
Wrongcurrent_user = Nonedef handler(request): global current_user current_user = request.args["user"]Rightdef handler(request): user = request.args["user"] return page(user)Client made per request
majorEvery call pays for a new connection.
Wrongdef handler(request): client = storage.Client()Rightclient = storage.Client()def handler(request): ...Handler that is not repeatable
majorEvents come at least once, and the second run counts again.
Wrongdef on_order(event): total.add(event.data["amount"])Rightdef 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.