Serverless Computing With Google Cloud
Part 1 of 2
Serverless Series
This is part of a Destructive Digital Technical series, we’ll be bringing you three awesome blogs on getting setup with a serverless architecture on Google Clouds Firebase platform. In this blog, we will cover getting setup with Google Cloud and deploying your first cloud function.
What is serverless?
“We have a serverless architecture”.
“Our core operations are micro processes”
You may of heard these words before.
Serverless has become increasingly popular over the past few years but what does it actually mean?
Instead of repeating what has already been well defined i’ll quote from AWS Senior Serverless Developer Paul Johnston:
“A Serverless solution is one that costs you nothing to run if nobody is using it”
This definition hits the nail on the head. When planning your infrastructure there are various factors that must be taken into consideration; How much traffic will the application get? What processing power demands will there be? What locations will the application be accessed from?
However an often overarching factor is cost. Picking an infrastructure that meet the specifications is all very well, however if it costs 10 times the allocated budget then it just won’t do!
Serverless To The Rescue!
Serverless architecture offers a low cost solution to powering applications that do not need to be running all of the time.
Let’s take an example, we have an API which provides weather information. Currently, the API is running 24/7 using up resources and accumulating usage cost for every second that it’s live. Let’s assume that the weather API gets 1000 hits per day, there are 86400 seconds in a day meaning on average the API receives less than 1 request per minute.
It’s clear that this service does not need to be constantly running. This is where serverless architecture saves the day. Switching the API to operate with a serverless architecture means we can deliver the same service, with the same data, without paying for a server to be running 24/7.
Small disclaimer, this approach can mean that response times may be slightly longer than if the request was made on a server that is always running.
For a detailed explanation of how serverless works in comparison to traditional, monolithic server architectures and for benchmark results, read Stephen Grider’s article
Creating a Serverless Location API
Fear not those that are still confused, as i’ve put together a simple demo to demonstrate serverless computing in action. The techniques used in this tutorial will require an understanding of JavaScript, a Firebase account (I’ll explain how to set this up below) and a favourite code editor.
Getting Setup
Before digging into the code, it’s important that we setup our environment with the necessary tools to test and deploy to Google cloud. Make sure you have the following installed:
- Node JS
- Firebase CLI Tools
- A familiar code editor — we’re going to use Sublime 3
Creating a New Project
Prior to jumping straight into coding, let’s start by setting up a new Firebase project. Head over to Firebase, login and select create new project and give your project a name.
It really is that simple… well, not quite, but that’s all the setup that is required and we’ll do the rest with the Firebase CLI.
Setting Up The Project Locally
Create a new folder on your computer for the project and then open a terminal(command prompt) window and navigate to the newly created folder.
Now, let’s login to Firebase with the following command:
firebase login
If you have already used firebase in the past, it will not be necessary to login again. Follow the login process with the CLI and you will become authenticated with your Google Firebase account.
Next to initialise a new Firebase project run the following command:
firebase init
You should now be shown the following Firebase CLI interface:
If asked where you would like to continue, enter ‘y’ and select only functions from the list that it presents you.
Finally select the newly created project from the list and you’ll be ready to start coding!
We’re going to make this API in TypeScript, which is favoured by Google. If you want to learn more about TypeScript, check this out.
Let’s Recap
Incase you missed anything, here’s a summary of the CLI options and what we’re using as our setup:
- Are you ready to proceed? Yes
- Which Firebase CLI features do you want to set up for this folder? Functions
- Select a default firebase project for this directory? Firebase project we created in the console
- What language do you want to use to write Cloud Functions? TypeScript
- Do you want to use TSLint to catch probable bugs and enforce style? Yes
- Do you want to install dependencies with NPM now? Yes
Let The Fun Begin
Load up your code editor with the project folder imported, and within this find the below TypeScript file. This is where we will create all of the functions for our location API.
./functions/src/index.ts
Importing The Firebase API
One of the best features of Firebase is how well integrated it is. Because we authenticate directly with the CLI it means we can import Firebase admin tools and have access to all of the Firebase services listed under the project without any additional setup, this will be very important for accessing our database.
At the top, import Firebase Admin. This will of been installed when we did firebase init. Remember to also initialise the admin tools:
Creating A Collection
Let’s hop back over to the Firebase Console again quickly, we’re going to set up a quick database with a few bits of sample data.
Firstly, select ‘Database’ from the left hand side panel and then select ‘Get Started’ in the ‘Cloud Firestore Beta’ box.
Ensure you create the database in ‘test mode’.
Selecting the database above will prompt us to enter our first collection to the database. We’re going to go ahead and create a collection called cities and add our first record to the collection.
After adding a collection and document to the database, the database will now look like so
Querying The Database
Let’s create a simple Cloud Function that can query the database and get the city data for New York.
Create the following function:
I want to draw attention to the error block, notice if the query errors we still send a response back to the client. All functions must return a response, even if they fail and the 500 status represents an internal server error.
Let’s Lint & Serve
Let’s make sure our code is passing the TypeScript lint inspection. Inside the terminal window, change directory into the functions directory created by the Firebase CLI. Run the following command
npm run-script lint
As we have no errors, the tool will return with no output, we’re ready to proceed. Let’s serve the firebase app. The Firebase CLI allows us to serve a functions API locally speeding up development and testing. Execute the following command
npm run-script build
A new lib folder has been created inside of the functions folder. This contains a file with our compiled TypeScript. If it built without error, we can now serve the functions API by executing the following command
firebase serve --only functions
The CLI will give us a URL for each function so that we can test it locally. Generally it will follow the format:
http://localhost:5000/location-api-89e5f/us-central1/getWeather
With the function name being the last part of the URL.
Testing
Let’s head over to postman to test out our serverless function, paste the URL from the CLI into the postman URL bar and send the request, you should receive a response like so:
Once you’re happy with your first function, you can deploy it using the following command:
firebase deploy
That’s it, we officially have a serverless location API which can tell us some information about each city.
So what’s next?
There are many ways which this API could be expanded upon, currently it is in its most basic state. In the next part of this series, we will build on top of this by adding the following functionality:
- Making our query dynamic
- Adding new cities
- Modifying cities
- Returning groups of data (requests within requests)
Part 2