A Comprehensive Guide to Google Cloud Functions
Tags: serverlessarchitect, googlecloudplatfor, serverless, serverlessapps
Published: 2017-11-13 13:27:15

---
title: "A Comprehensive Guide to Google Cloud Functions"
published: true
tags: serverless-architect,google-cloud-platfor,serverless,serverless-apps
canonical_url: https://divu.in/a-comprehensive-guide-to-google-cloud-functions-465eebf2a738
cover_image: https://cdn-images-1.medium.com/max/2000/1*40qZlS1BXm8AOVCZ6rFKLg.jpeg
---

### Introduction

[Cloud Functions](https://cloud.google.com/functions/) allow us to write business logic without provisioning any infrastructure. In this post, we will talk about the flavors of [cloud functions](https://cloud.google.com/functions/) available at our disposal, limitations, development/deployment workflow, local development with cloud functions emulator and&nbsp;code.

Google describes [Cloud Functions](https://cloud.google.com/functions/) as following: –


> Google Cloud Functions is a lightweight, event-based, asynchronous compute solution that allows you to create small, single-purpose functions that respond to cloud events without the need to manage a server or a runtime environment


Without further ado, let’s dive&nbsp;in.

### Cloud Functions Runtime and Dependencies

[Cloud Function](https://cloud.google.com/functions/) are modules written in Javascript and run in a [Node runtime](https://nodejs.org/en/). The [Cloud Functions](https://cloud.google.com/functions/) execution environment follows the [Node](https://nodejs.org/en/) “LTS” releases, the current Node version running in [Cloud Functions](https://cloud.google.com/functions/) is [Node](https://nodejs.org/en/)&nbsp;v6.11.1.

For dependencies, there is only good news as you can use the powers of [npm and package.json](https://cloud.google.com/functions/docs/writing/dependencies)

P.S. when deploying from local machine as we will see further in this post, you can deploy configuration files/credential keys for access (not advised to version control the credential keys though). Use [Google Cloud Deployment Manager](https://cloud.google.com/deployment-manager/) for provisioning configuration.

### Types of Cloud Functions

Google Cloud Functions come in two flavors:&nbsp;–

#### Foreground (HTTP) Functions

These functions get an HTTP URL to be invoked from out in the wild. Like the one below, check it&nbsp;out.

[https://us-central1-divu-178107.cloudfunctions.net/hello-world](https://us-central1-divu-178107.cloudfunctions.net/hello-world)

Writing an HTTP Cloud Function is pretty straight forward, you export a function with the request, response arguments (like express). This is how the code for the above function looks like:&nbsp;–

{% gist https://gist.github.com/divyenduz/207a2a7d2f0397c372d76acf25a75989 %}

#### Background Functions

This flavor of Cloud Functions allows us to handle events from our cloud infrastructure, such as listening to messages on a Pub/Sub topic or changes in a Google Cloud Storage bucket. Suppose you want to write a cloud function that resizes images to different variations on upload to Google Cloud Storage. That function would look something like&nbsp;this.

{% gist https://gist.github.com/divyenduz/96e4d633c9b24df9bbcaf0009303e07f %}

Important note from the&nbsp;[docs](https://cloud.google.com/functions/docs/writing/background).

_Note: You should always either invoke the callback argument, or return a Promise when your function has completed. Otherwise, your function may continue to run and be forcibly terminated by the system._

Also, refer to the docs for details on event parameters and more information on the callback.

#### How to create Foreground (HTTP), Background Function

You get to choose the type of function you want to create while creating a Cloud Function via choosing a trigger and this is how you choose between creating different types of functions.

![](https://cdn-images-1.medium.com/max/300/1*yqttFy9zxC8X5UOIVWDG-A.png)<figcaption>Choose trigger while creating a CloudÂ Function</figcaption>

The same can be done from command line as well using gcloud utility as follows:&nbsp;–

```
gcloud beta functions deploy <function-name> --stage-bucket <bucket-to-store-the-function-to> --trigger-http # Deploy HTTP function

gcloud beta functions deploy <function-name> --stage-bucket <bucket-to-store-the-function-to> --trigger-bucket=<bucket-on-which-we-want-to-listen-events> # Deploy background function
```

You can also call functions from command line to test them as follows:&nbsp;–

```
functions call <function-name> --data='{"message":"Hello World"}' # HTTP function

functions call <function-name> --data='{"name":"<file-name-that-fake-triggered-this-event>","bucket":"<bucket-name-that-fake-triggered-this-event>"}' # Background function
```

Lastly, cloud functions have [quotas](https://cloud.google.com/functions/quotas) that we should be aware&nbsp;of.

#### **Meta information about cloud functions**

I added this as a bonus in this section because I feel this is important. You have access to /tmp to store temporary files according to the&nbsp;[docs](https://cloud.google.com/functions/pricing).

```
Local Disk

Cloud Functions provides access to a local disk mount point (/tmp) which is known as a "tmpfs" volume in which data written to the volume is stored in memory. There is no specific fee associated with this however writing data to the /tmp mountpoint will consume memory resources provisioned for the function.
```

This is really handy if you want to process files and need a temporary storage before putting it in Google Cloud Storage&nbsp;bucket.

Also, to upload files, you need to convert them to base64 encoded strings (I could not find ability to upload files otherwise in [docs](https://cloud.google.com/functions/docs/writing/http), please correct me if I am wrong). Cloud Functions use [body-parser](https://github.com/expressjs/body-parser) and hence the limitation.

![](https://cdn-images-1.medium.com/max/1024/1*okxdNTvXBbmwAPb6CwyiHA.png)<figcaption>Description of parsing done by HTTP functions</figcaption>

Ending the meta information section with [this nice blog post](https://mhaligowski.github.io/blog/2017/05/15/serving-functions-express.html), that talks about sharing functions between Google Cloud and&nbsp;Express.

### Development and Deployment Workflow

While it is possible to write cloud functions from the google developer console, deploy it and test it from there, it would make for a terrible developer experience as a cloud function may take up to 2 minutes to&nbsp;deploy.

Enter [Cloud Functions Emulator](https://cloud.google.com/functions/docs/emulator), whilst still in alpha at the time of this writing, it is a great tool that helped me a ton while working with Cloud Functions. You can install the emulator using the following command.

```
yarn global add @google-cloud/functions-emulator
```

Once setup, the emulator can be used with functions command. Here is a list of commands (not exhaustive) available at your disposal.

```
functions --help
functions <command> --help
functions start
functions stop
functions kill
functions deploy helloWorld --trigger-http
functions call helloWorld --data='{"message":"Hello World"}'
functions list
functions status
functions debug <function-name>
functions inspect <function-name>
```

Notice how closely the functions emulator follows the syntax of gcloud command to deploy and call functions. This caters for an amazing development experience as now you can write, test, automate-tests for your functions locally and version control them before actual deployment.

You can also deploy Cloud Function directly from [source&nbsp;control](https://cloud.google.com/functions/docs/deploying/repo).

#### Next steps

Play around with Google Cloud Function for fun and glory and jump to [serverless frameworks](https://serverless.com/) for writing production grade&nbsp;code.

[Serverless - The Serverless Application Framework powered by AWS Lambda and API Gateway](https://serverless.com/)

And that’s all for this post, I would really appreciate feedback via comments or [twitter](https://twitter.com/divyenduz) and&nbsp;claps.

<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fbad097%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2Fbad097%2F&amp;image=https%3A%2F%2Fupscri.be%2Fmedia%2Fform.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9d4dcab1161d9df16e59865831303d1/href">https://medium.com/media/e9d4dcab1161d9df16e59865831303d1/href</a></iframe>
* * *