aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • Software Engineering
  • Solutions
  • Technology

Avoiding GCF Anti-Patterns Part 5: How To Run Background Processes Correctly In Python

  • aster.cloud
  • November 23, 2021
  • 3 minute read

Editor’s note: Over the past several weeks, we’ve posted a series of blog posts focusing on best practices for writing Google Cloud Functions based on common questions or misconceptions as seen by the Support team.  We refer to these as “anti-patterns” and offer you ways to avoid them.  This article is the fifth post in the series.

Scenario

You see finished with status: 'timeout' in the logs before a background process has completed in your Python Function.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

Most common root issue

Although this timeout error can happen for Functions using any runtime, we most often see this issue occur when Python developers try to use os.fork() or  multiprocessing.Process() in their Cloud Function.

Why you should try to avoid async work in a Function:

A background task started by a Cloud Function is not guaranteed to complete. As soon as the Functions completes, e.g. the Function returns or a timeout error occurs, the Function instance can be terminated at any time. You can read more about the Function execution timeline in the documentation.

We often see customers test their functions locally where these execution timeouts do not exist. Additionally, customers’ local machines may be more powerful than what they have provisioned for their Cloud Functions. Customers may see these multiprocessing scenarios working locally and therefore assume their code will work in the same way in the Cloud Function instance.

For Python developers who require such async operations, we suggest using Cloud Tasks Service instead to schedule the background operation. See example below.

Using Cloud Tasks in a Python Cloud Function

The following Function demonstrates how you can use Cloud Tasks to schedule an async operation. This example shows a Cloud Function (named “create_task“) that creates a Cloud Task to invoke another Cloud Function that will run the background task. You can learn more about creating HTTP target tasks.

Read More  Introducing Vertical Autoscaling In Streaming Dataflow Prime Jobs
"""Create a task for a given queue with an arbitrary payload."""
from flask import escape
from google.cloud import tasks_v2
from google.protobuf import timestamp_pb2
import datetime
import json


def create_task(request):

   # Create a client.
   client = tasks_v2.CloudTasksClient()

   # TODO(developer): Uncomment these lines and replace with your values.
   project = '<PROJECT_ID>'
   queue = 'my-queue'
   location = '<your-region>'
   url = '<url-to-Cloud-Function-to-run-background-task>'
   payload = {'message': 'Hello from Cloud Tasks'}
   in_seconds = 60

   # Construct the fully qualified queue name.
   parent = client.queue_path(project, location, queue)

   # Construct the request body.
   task = {
       "http_request": {  # Specify the type of request.
           "http_method": tasks_v2.HttpMethod.POST,
           "url": url,  # The full url path that the task will be sent to.
           "oidc_token": {
               "service_account_email": "<your-service-account-with-function-invoker-role>@<PROJECT_ID>.iam.gserviceaccount.com",
               "audience": url
           }
       }
   }
   if payload is not None:
       if isinstance(payload, dict):
           # Convert dict to JSON string
           payload = json.dumps(payload)
           # specify http content-type to application/json
           task["http_request"]["headers"] = {
               "Content-type": "application/json"}

       # The API expects a payload of type bytes.
       converted_payload = payload.encode()

       # Add the payload to the request.
       task["http_request"]["body"] = converted_payload

   if in_seconds is not None:
       # Convert "seconds from now" into an rfc3339 datetime string.
       d = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)

       # Create Timestamp protobuf.
       timestamp = timestamp_pb2.Timestamp()
       timestamp.FromDatetime(d)

       # Add the timestamp to the tasks.
       task["schedule_time"] = timestamp

   # Use the client to build and send the task.
   response = client.create_task(request={"parent": parent, "task": task})

   print("Created task {}".format(response.name))
   return 'Task Created!'

Other helpful tips

  • Although this tutorial is written for Node.js, it walks you through creating a Cloud Task queue and setting up a service account that will invoke the Function from Cloud Task. By specifying a service account for the Task, you can use an authenticated Function.
  • If you’re using a different service account to invoke the Function (rather than your Function’s identity), you need to verify that the service account has the Cloud Functions Invoker role `roles/cloudfunctions.invoker`.
  • If you’re using a different service account for your “create_task” Function’s identity than the default, you need to verify that the service account has permissions to create Tasks. It will need the Cloud Tasks Enqueuer role `roles/cloudtasks.enqueuer`.
Read More  Shopify Engineers Deliver On Peak Performance During Black Friday Cyber Monday 2021

You can also read more about Cloud Tasks in our third blog post in this series on making outbound connections.

 

By: Sara Ford (Cloud Developer Advocate) and Martin Skoviera (Technical Solutions Engineer)
Source: Google Cloud Blog


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

aster.cloud

Related Topics
  • Cloud Functions
  • Cloud Tasks
  • Google Cloud
  • Python
You May Also Like
View Post
  • Technology

IBM Study: One in Four Malicious Breaches are AI-Enabled, Costing Companies $6 Million on Average

  • July 29, 2026
View Post
  • Technology

3 Questions: Neural transparency and the future of AI design

  • July 17, 2026
View Post
  • Technology

IBM and Red Hat Expand Lightwell with New Offerings to Build the Trust Infrastructure for AI-Era Open Source

  • July 8, 2026
View Post
  • Technology

The AI investment surge hasn’t produced the expected results yet. That could change in 2026

  • June 26, 2026
zedreviews-valerion
View Post
  • Gears
  • Technology

Father’s Day Outdoors – Build Dad the Ultimate Backyard Watch Party

  • June 20, 2026
zedreviews-fathers-day-50830
View Post
  • Gears
  • Technology
  • Tools

Father’s Day Outdoors, Round Two – Gear for the Action, the Tailgate, and Beating the Heat

  • June 20, 2026
zedreviews-fathers-day-2147684744
View Post
  • Gears
  • Technology
  • Tools

The Ultimate Father’s Day Gift Guide – Home Entertainment Upgrades Dad Actually Wants

  • June 20, 2026
zedreviews-fathers-day-21306
View Post
  • Gears
  • Technology

A Father’s Day Gift Guide for Every Dad – Timepieces and Travel Gear

  • June 20, 2026

Stay Connected!
LATEST
  • 1
    IBM Study: One in Four Malicious Breaches are AI-Enabled, Costing Companies $6 Million on Average
    • July 29, 2026
  • 2
    Accelerating the frontiers of scientific discovery: Google’s $40M commitment to the Genesis Mission
    • July 26, 2026
  • 3
    3 Questions: Neural transparency and the future of AI design
    • July 17, 2026
  • 4
    Intel Invests €5 Billion to Expand Manufacturing in Europe
    • July 13, 2026
  • 5
    IBM and Red Hat Expand Lightwell with New Offerings to Build the Trust Infrastructure for AI-Era Open Source
    • July 8, 2026
  • 6
    When I Was Young
    • July 4, 2026
  • 7
    The Fastest AI Fried Chicken In The World
    • June 29, 2026
  • 8
    Zed Approves | How to Stay Cool in Extreme Heat
    • June 29, 2026
  • 9
    The AI investment surge hasn’t produced the expected results yet. That could change in 2026
    • June 26, 2026
  • 10
    Zed Approves | It’s Prime Day 2026! Time to Upgrade Your World Cup Viewing Setup and Beat the Heat
    • June 25, 2026
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    Zed Approves | The Best Prime Day PC Deals: Top Gaming Rigs, Workstations, and Everyday Laptops
    • June 24, 2026
  • neon-cart 2
    Zed Approves: How to Gear Up for GTA 6 This Amazon Prime Day (2026 Quick Guide)
    • June 22, 2026
  • zedreviews-valerion 3
    Father’s Day Outdoors – Build Dad the Ultimate Backyard Watch Party
    • June 20, 2026
  • zedreviews-fathers-day-50830 4
    Father’s Day Outdoors, Round Two – Gear for the Action, the Tailgate, and Beating the Heat
    • June 20, 2026
  • zedreviews-fathers-day-2147684744 5
    The Ultimate Father’s Day Gift Guide – Home Entertainment Upgrades Dad Actually Wants
    • June 20, 2026
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.