Understand and Compare Cloud Functions vs Cloud Run | by Sue Lynn | Towards Data Science

As a data scientist, you will need to decide how to perform model deployment steps, which could involve converting your scripts and deploying them as a microservice. In my case, I was confused about which GCP components should I use to deploy the microservice. Should I deploy on Cloud Run or Cloud Function? Both are GCP serverless products, easy to be deployed and handle HTTP requests/events. So, I decided to perform some research and deploy the same microservice on both cloud functions and cloud run and observe the differences. In this article, I will share the difference between cloud functions and cloud runs and the approach of deploying these two components.
Before diving into the difference between these two components, let’s have an understanding of each of these components.
The first Beta release of Cloud Function was in March 2017. Cloud Function is an event-driven serverless platform for a lightweight solution to support individual services and can be called via HTTP Request or triggered based on background events. Cloud Function only supports specific languages such as JavaScript, Python, Go, etc. and the code requires to be packaged as a function and the cloud function component will handle the packaging, deployment, and execution of the code. As Cloud Function only handles one request at a time for each instance, it would be suitable only if the use case is a single-purpose workload.
Cloud Run Beta release came later than Cloud Function which was first introduced in April 2019 as an addition to other GCP serverless products. Cloud Run is a fully-managed compute platform that is suitable for deploying containerized applications. Cloud Run allows user to write their script based on the user's favorite programming language then push it and package it as a container with Cloud Build. Compare with Cloud Function which only supports one request at a time, Cloud Run is able to be configured to support multiple concurrent requests on a single container instance which allows to save time and save cost.
Let’s test deploying a simple service that can be triggered via HTTP endpoints and return a message based on user inputs on both platforms — Cloud Function and Cloud Run.
The expected output will return a message based on user input:
Steps to Deploy on Cloud Function:
We can create an HTTP trigger with a python script that receives user requests and set it up on Cloud Function.
(1) Create a function and test it (*The environment I am using is Vertex AI Jupyternotebook on GCP)
(2) Go to Cloud Function in Google Cloud Console and select “Create Function” (*Enable Cloud Function API and Cloud Build API If this is your first time)
Give your Cloud Function a Name
Select a Region
Choose HTTP trigger
Allow Unauthenticated Invocations if you would like to trigger and call the service from a browser (*Not recommended for production pipeline, but easier while development to see output)
(3) Next, Under the code section — select Runtime to “Python 3.9”, Entry Point to the function name “print_message” and add your python function into the main.py file.
Note that to pass parameters in a cloud function, you will need to change the function to handle and retrieve parameters using request.args.get()
def print_message(request):         message = request.args.get('msg')    final_message = f"My Name is {message}, Nice meeting you! "         return final_message
(4) Once the code has been updated, deploy the function by selecting the “Deploy” button at the bottom — The function will then begin deploying on your GCP environment.
(5) Test and Call your newly deployed function in the browser
You can retrieve your HTTP URL under the trigger tab of the Cloud Function deployed.
Call the endpoint from your browser and pass in your input via the URL.
Congrats, for walking through with me on the steps required to deploy a microservice to cloud function. Now let’s look at the steps required to create the same microservice on Cloud Run.
Steps to Deploy on Cloud Run:
The approach to creating a microservice on Cloud Run will require preparing several files — which are:
main.py
Dockerfile
(1) Prepare main.py file & Dockerfile
The main.py file consists of the web framework (FastAPI) and python function that receives user input and returns a message.
import uvicornfrom fastapi import FastAPIimport osapp = FastAPI()@app.get("/{msg}")async def print_message(msg:str):         message = msg    final_message = f"My Name is {message}, Nice meeting you! "         return final_message
Dockerfile:
In Cloud run to deploy and create a microservice, a python script is required to be deployed into a Docker Container. A Dockerfile specify how the container will be created and run the web service on container startup.
# Use official lightweight Python image as base OS.FROM python:3.7-slim# Copy local code to the container image.ENV APP_HOME /appWORKDIR $APP_HOMECOPY . ./# Install production dependencies.RUN pip install fastapi uvicorn[standard] gunicornENV PORT 8080#Run the web service on container startup using gunicorn webserver.CMD exec gunicorn --bind :$PORT --workers 1 --worker-class uvicorn.workers.UvicornWorker  --threads 8 main:app
(2) Build and Deploy Docker Image
There are different approaches that can be used on Google Cloud Console to build & deploy cloud-run microservice. In my previous articles, I shared the approach to deploy a cloud-run microservice via Cloud Shell Editor. In this article, I will be deploying from the Vertex AI Jupyternotebook environment.
In your notebook, create a specific folder and upload the files — main.py & Dockerfile
Launch / Open Terminal console in Jupyternotebook
In the terminal navigate to the folder that contains the files
cd cloud-run-demo
Configure and set the region where the microservice will be deployed.
gcloud config set run/region asia-southeast1
Run the command to build a new docker image on the selected region. This process will take a few minutes.
gcloud builds submit --tag gcr.io/sue-gcp-learn/cloud-run-demo
Deploy the newly build image and provide a Cloud Run Service Name.
gcloud run deploy --image gcr.io/sue-gcp-learn/cloud-run-demo --platform managed
(3) Check & Test deployed Cloud Run Service
Microservice URL will be provided upon finished deploying. The service will also be available from the Cloud Run console.
Test and call the cloud run endpoint from your browser and pass in your input via the URL.
Congrats, for walking through with me on the steps required to deploy a microservice to cloud run. Now you have the knowledge to create a microservice on two different GCP components.
Cloud Function allows users to deploy code based on several languages supported whereas Cloud Run does not have this limitation as you will be able to build and deploy container images based on user-selected language.
Cloud Functions only supports a single request at a time for each cloud function instance whereas Cloud Run is able to handle multiple requests at the same time and is able to scale up based on demand.
Cloud Functions is able to handle specific triggers such as FireStore events and trigger based on changes on Cloud Storage whereas Cloud Run does not come with this additional functionality.
Having experience on both component Cloud Function and Cloud Run, I would prefer Cloud Run due to its flexibility and the ability to handle concurrency. As cloud run uses containerization, it is considered portable and can be easily deployed into another environment such as on-prem, on another region, etc. which reduces rework in the future.
Nonetheless, I strongly advise you to test creating your microservice on both components if you have the additional time and compare them from your own perspective.
Thanks for reading my article and if you enjoyed and would like to support me:
Follow me on Medium 🙆🏻
Become a member on Medium through my referral link 🙋
References & Links: