Write event-driven functions

In Cloud Run functions, you use event-driven functions when you want a function to be invoked automatically in response to an event that occurs in your cloud environment.

CloudEvent functions

You use CloudEvent functions to invoke your function.

CloudEvent functions are based on CloudEvents, an industry-standard specification for describing event data in a common way. You can learn more about the CloudEvents specification at the CloudEvents GitHub repository. The CloudEvents project also provides a set of CloudEvents SDKs to help work with CloudEvents objects in your code.

The following example shows a basic CloudEvent function source file for each runtime. See Source directory structure for information about where to locate your source code.

Node.js

const functions = require('@google-cloud/functions-framework');

// Register a CloudEvent function with the Functions Framework
functions.cloudEvent('myCloudEventFunction', cloudEvent => {
  // Your code here
  // Access the CloudEvent data payload via cloudEvent.data
});

In Node.js, you register a CloudEvent handler function with the Functions Framework for Node.js. Your handler function must accept a CloudEvent object as an argument.

The function entry point is the name with which the handler is registered with the Functions Framework. In this example, the entry point is myCloudEventFunction.

Python

import functions_framework

# Register a CloudEvent function with the Functions Framework
@functions_framework.cloud_event
def my_cloudevent_function(cloud_event):
  # Your code here
  # Access the CloudEvent data payload via cloud_event.data

In Python, you register a CloudEvent handler function with the Functions Framework for Python. Your handler function must accept a CloudEvent object as an argument.

The function entry point is the name of the handler function registered with the Functions Framework. In this example, the entry point is my_cloudevent_function.

Go

package mycloudeventfunction

import (
    "context"

    "github.com/GoogleCloudPlatform/functions-framework-go/functions"
    "github.com/cloudevents/sdk-go/v2/event"
)

func init() {
    // Register a CloudEvent function with the Functions Framework
    functions.CloudEvent("MyCloudEventFunction", myCloudEventFunction)
}

// Function myCloudEventFunction accepts and handles a CloudEvent object
func myCloudEventFunction(ctx context.Context, e event.Event) error {
    // Your code here
    // Access the CloudEvent data payload via e.Data() or e.DataAs(...)

    // Returning an error causes its message to be logged.
    // Example:
    err := myInternalFunction() // may return an error
    if err != nil {
        // Append error message to log
        return err
    }

    // Return nil if no error occurred
    return nil
}

In Go, you register a CloudEvent handler function with the Functions Framework for Go. Your handler function must accept a CloudEvents event.Event object as an argument.

The function entry point is the name with which the handler is registered with the Functions Framework. In this example, the entry point is MyCloudEventFunction.

Java

package mycloudeventfunction;

import com.google.cloud.functions.CloudEventsFunction;
import io.cloudevents.CloudEvent;

// Define a class that implements the CloudEventsFunction interface
public class MyCloudEventFunction implements CloudEventsFunction {
  // Implement the accept() method to handle CloudEvents
  @Override
  public void accept(CloudEvent event) {
    // Your code here
    // Access the CloudEvent data payload via event.getData()
    // To get the data payload as a JSON string, use:
    // new String(event.getData().toBytes())
  }
}

In Java, you use the Functions Framework Java API to implement a CloudEvent handler class with the CloudEventsFunction interface. The accept() method must accept a CloudEvent object as an argument and perform any processing on the event.

The function entry point is the fully-qualified name of the CloudEvent handler class, including the package name. In this example, the entry point is mycloudeventfunction.MyCloudEventFunction.

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using System.Threading;
using System.Threading.Tasks;

namespace MyProject
{
    // Define a class that implements the ICloudEventFunction<T> interface
    public class MyCloudEventFunction : ICloudEventFunction<CloudEventDataType>
    {
        // Implement the HandleAsync() method to handle CloudEvents
        public Task HandleAsync(CloudEvent cloudEvent, CloudEventDataType data, CancellationToken cancellationToken)
        {
            // Your code here
            // The data argument represents the CloudEvent data payload

            // Signal function completion
            return Task.CompletedTask;
        }
    }
}

In .NET runtimes, you use the Functions Framework for .NET to implement a CloudEvent handler class with the ICloudEventFunction<T> interface. The HandleAsync() method accepts a CloudEvent object and the associated CloudEvent data payload as arguments.

The type of the CloudEvent data payload argument, shown in the above example as CloudEventDataType, must correspond to the type of event the function handles. The Google CloudEvents .NET library provides data types for the various events supported by Google.

The function entry point is the fully-qualified name of the CloudEvent handler class, including the namespace. In this example, the entry point is MyProject.MyCloudEventFunction.

Ruby

require "functions_framework"

# Register a CloudEvent function with the Functions Framework
FunctionsFramework.cloud_event "my_cloudevent_function" do |cloud_event|
  # Your code here
  # Access the CloudEvent data payload via cloud_event.data
end

In Ruby, you register a CloudEvent handler function with the Functions Framework for Ruby. Your handler function must accept a CloudEvents Event object as an argument.

The function entry point is the name with which the handler is registered with the Functions Framework. In this example, the entry point is my_cloudevent_function.

PHP

<?php

use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;

// Register a CloudEvent function with the Functions Framework
FunctionsFramework::cloudEvent('myCloudEventFunction', 'myCloudEventHandler');

// Define your CloudEvent handler
function myCloudEventHandler(CloudEventInterface $event): void
{
    // Your code here
    // Access the CloudEvent data payload via $event->getData()
}

In PHP, you register a CloudEvent handler function with the Functions Framework for PHP. Your handler function must accept an argument that conforms to the CloudEventInterface interface.

The function entry point is the name with which the handler is registered with the Functions Framework. In this example, the entry point is myCloudEventFunction.

For CloudEvent functions, event data is passed to your function in the CloudEvents format, with a CloudEvent data payload corresponding to the event type that triggers your function. See Cloud Run functions triggers for information about supported triggers, event types, and associated event data formats.

The Google Events repository contains resources for working with CloudEvents issued by Google.

Function termination

Cloud Run functions considers event-driven function execution complete when the function returns. If the function creates background tasks (such as with threads, futures, JavaScript Promise objects, callbacks, or system processes), you must terminate or otherwise resolve these tasks before returning from your function. Any tasks not terminated before the function returns might not be completed, and might cause undefined behavior.

Automatic retries

Event-driven functions can be configured to automatically retry failed invocations. See Retrying event-driven functions for more information.

Next steps