Google Cloud Functions is a serverless computing platform provided by Google Cloud Platform (GCP). It allows developers to build and deploy applications without managing servers or infrastructure, focusing on writing code that responds to events from various cloud services.
Imagine you want to execute some code when an event happens?
- A file is uploaded in Cloud Storage (OR) An error log is written to Cloud Logging (OR) A message arrives to Cloud Pub/Sub (OR) A http/https invocation is received
All these cases we can use Cloud Functions
- Run code in response to events
- Write your business logic in Node.js, python, Go, Java, .NET and Ruby
- Don’t worry about server or scaling or availability (only worry about your code)
- Pay only for what you use
- Number of invocations
- Compute time of the invocations
- Memory and CPU provisioned
- Time Bound – Default 1 min and MAX 60 minutes (3600 seconds)
- 2 product versions
- Cloud Functions (1st gen): First version
- Cloud Function (2nd gen): New version build on top of Cloud Run and Eventarc
Cloud Functons – Concepts
Event: Upload object to cloud storage
Trigger: Response to event with a Function call
- Trigger – Which function to trigger when an event happens
- Functions – Take event data and perform action?
Event are triggered from
- Cloud Storage
- Cloud Pub/Sub
- HTTP POST/GET/DELETE/PUT/OPTIONS
- Firebase
- Cloud Firestore
- Stack driver logging
Example Cloud Function – HTTP – Node.js
const escapeHtml = require('escape-html');
/**
* HTTP Cloud Function.
*
* @param {Object} req Cloud Function request context.
* More info: https://expressjs.com/en/api.html#req
* @param {Object} res Cloud Function response context.
* More info: https://expressjs.com/en/api.html#res
*/
exports.helloHttp = (req, res) => {
res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
};
Example Cloud Function – Pub/Sub – Node.js
/**
* Background Cloud Function to be triggered by Pub/Sub.
* This function is exported by index.js, and executed when
* the trigger topic receives a message.
*
* @param {object} message The Pub/Sub message.
* @param {object} context The event metadata.
*/
exports.helloPubSub = (message, context) => {
const name = message.data
? Buffer.from(message.data,
'base64').toString()
: 'World';
console.log(`Hello, ${name}!`);
};
Point to be remember
- No Server Management: You dont need to worry about scaling or availability of your function
- Cloud Function automatically spin up and back down in response to events
- They scale horizontally
- Cloud Functions are recommended for responding to events:
- Cloud functions are NOT ideal for long running processes
- Time bound – default 1 min and MAX 60 minutes(3600 seconds)
- Cloud functions are NOT ideal for long running processes