Google Cloud Functions is the second most popular serverless execution platform. Similar to AWS Lambda it is stateless, namely you need to access external resources to read or write your applications state. In this post, we will introduce Redis as a database for your Google Cloud functions.
This tutorial shows how to build a serverless API with Redis on Google Cloud Functions. The API will simply count the page views and show it in JSON format.
- Serverless compute: Google Cloud Functions (Node.js)
- Serverless data store: Redis via Upstash
- Deployment tool: gcloud
- A GCP account for Google Cloud functions.
- Install Google Cloud SDK.
- An Upstash account for Serverless Redis.
- Create a folder, then run
npm initinside the folder.
Our only dependency is redis client. Install go-redis via
npm install ioredis
Create a Redis database from Upstash console. Select the GCP US-Central-1 as the region. Free tier should be enough. It is pretty straight forward but if you need help, check getting started guide. In the database details page, click the Connect button. You will need the endpoint and password in the next step.
Create index.js as below:
Replace the "REPLACE_YOUR_UPSTASH_REDIS_URL" with your database's ioredis url.
The code simply increments a counter in Redis database and returns its value in json format.
Now we are ready to deploy our API. Deploy via:
You will see the URL of your Cloud Function. Click to the URL to check if it is working properly.
In case of an issue, you can check the logs of your Cloud Function in the GCP console as below.