Skip to main content

GitHub Repository

You can find the project source code on GitHub.
Google Cloud Functions is one of the most popular serverless execution platforms, now part of Cloud Run as Cloud Run functions. 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 Cloud Run functions. The API will simply count the views and show it in JSON format.

Prerequisites

  1. Create a Google Cloud Project.
  2. Enable billing for your project.
  3. Enable the Cloud Run, Cloud Build, Artifact Registry, and Cloud Logging APIs.

Database Setup

Create a Redis database using Upstash Console or Upstash CLI. Copy UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN for the next steps.

Counter Function Setup & Deploy

  1. Go to Cloud Run in Google Cloud Console.
  2. Click Write a function.
  3. Enter a service name, pick a region, and select a recent Node.js runtime.
  4. Under Authentication, select Allow public access.
  5. Expand the Containers, Volumes, Networking, Security section. In the Variables & Secrets tab, add the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables with the values from your database.
  6. Click Create. The console creates the service and opens the inline source editor.
  7. Set Function entry point to counter.
  8. Update index.js
index.js
  1. Update package.json to include @upstash/redis.
package.json
  1. Click Save and redeploy.
  2. Visit the URL shown at the top of the service page.