All Products
Search
Document Center

Function Compute (2.0):Overview

Last Updated:Feb 20, 2024

An HTTP trigger allows you to invoke a function by using an HTTP request. HTTP triggers can be used in scenarios in which the rapid development of web services is required. Before you use HTTP triggers, make sure that you are familiar with the limits on HTTP triggers and protocols such as HTTP/HTTPS, WebSocket, and gRPC to prevent function invocation failures. This topic describes how to invoke an HTTP trigger, configure authentication, and process cross-origin resource sharing (CORS) requests.

Usage notes

If you set Authentication to No in the configuration of an HTTP trigger for a function, the HTTP trigger is anonymous. In this case, anyone can invoke the function by sending an HTTP request. Consequently, the URL of the HTTP trigger may be leaked. To prevent URL leaks, you can use the Authorization request header to authenticate the validity of a request. For more information, see Signature authentication.

Limits

Before you configure and use an HTTP trigger, make sure that you understand the limits on HTTP triggers and the limits on HTTP/HTTPS, WebSocket, and gRPC protocols.

Limits on triggers

  • HTTP triggers cannot be created for custom container functions that are in non-web server mode.

  • After you configure an HTTP trigger for a function, you cannot configure other types of triggers for the function.

  • You can create only one HTTP trigger for a service that has one version or alias. For more information, see Manage versions and Manage aliases.

  • By default, the built-in domain names provided by HTTP triggers are only for tests. The stability of the built-in domain names may affect your online services. We recommend that you do not use the built-in domain names for external online services.

    Note

    Website services can only be provided by using domain names for which ICP filing is obtained. You can configure a custom domain name, bind the domain name to your function, and then use the domain name to provide services. For more information, see Configure a custom domain name.

Limits on HTTP/HTTPS

Note

You can use various methods, including GET, POST, PUT, DELETE, HEAD, PATCH, and OPTIONS, to trigger functions. The HTTP and HTTPS protocols are suitable for simple request-response scenarios. For more information, see Configure an HTTP trigger for a function and invoke the function by using HTTP requests.

  • Limits on HTTP requests

    • Request headers cannot start with the x-fc- field, and the connection and keep-alive fields are not supported.

    • The system returns the 400 status code and the InvalidArgument error code if a request exceeds one of the following limits:

      • Headers size: The total size of all keys and values in headers cannot exceed 8 KB.

      • Path size: The total size includes all Query Params. The total size of a Path cannot exceed 8 KB.

      • Body size: The total size of the body of a synchronous invocation request cannot exceed 32 MB. The total size of the body of an asynchronous invocation request cannot exceed 128 KB.

  • Limits on HTTP responses

    • Response headers do not support custom fields that start with x-fc-. The following custom fields are also not supported: connection, content-length, date, keep-alive, server, upgrade, and content-disposition:attachment.

    • Note

      If you use the default domain name aliyuncs.com of Function Compute, the server forcibly adds the content-disposition: attachment field to response headers to ensure security. This field allows the returned results to be downloaded from a browser as an attachment. To remove the limit, you must configure a custom domain name. For more information, see Specify a custom domain name.

    • If a response exceeds one of the following limits, the system returns the status code 502 and the error BadResponse:

      • Headers size: The total size of all keys and values in headers cannot exceed 8 KB.

Limits on WebSocket

Note

The GET method can be used to trigger functions. WebSocket is suitable for scenarios that require persistent connection and real-time messaging. For more information, see Configure an HTTP trigger and use WebSocket to trigger an HTTP trigger.

  • Runtime: Only custom runtimes and Custom Container runtimes support WebSocket.

  • Timeout limit: The timeout period of a WebSocket request is subject to the timeout period that is configured for a function.

  • Request limits for a WebSocket handshake request:

    • Request headers that start with the x-fc- field are not supported.

    • Headers size: The total size of all keys and values in headers cannot exceed 8 KB.

    • Path size: The total size includes all Query Params. The total size of a Path cannot exceed 8 KB.

    • Body: The body cannot be sent in a WebSocket handshake request. Even if the body is sent, Function Compute ignores the body.

  • Response limit for a WebSocket handshake request:

    The total size of all keys and values in response headers cannot exceed 8 KB. Otherwise, the system returns the 502 status code and the BadResponse error.

  • Data transmission limits for WebSocket:

    After you establish a WebSocket connection, the maximum size of packets (messages) that can be sent or received at the same time cannot exceed 6 MB.

Limits on gRPC

Note

The gRPC protocol can be used to trigger functions and is suitable for scenarios that require low latency, high performance, and ProtoBuf-based multi-language communication. For more information, see Configure an HTTP trigger that invokes a function with gRPC requests.

  • Runtime: Only custom runtimes and Custom Container runtimes support gRPC.

  • Restrictions:

    • Before you use gRPC to trigger the execution of a function, make sure that the POST method is included in Request Method of the HTTP trigger.

    • Use a subdomain fcapp.run or a custom domain name to initiate gRPC invocation.

  • Timeout period: gRPC requests are subject to the timeout period that is configured for the function. The maximum retention period of a streaming gRPC connection cannot exceed the value that is specified for the Execution Timeout Period parameter of the function.

  • Data transmission of gRPC requests: After you establish a gRPC streaming connection, the maximum amount of data that can be sent or received in a single packet (message) cannot exceed 6 MB.

Benefits

Both HTTP triggers and API Gateway triggers can be used to create web applications. The following items describe benefits of HTTP triggers and API Gateway triggers:

  • HTTP triggers: You can bind a custom domain name to map different HTTP access paths to HTTP functions. For more information, see Specify a custom domain name.

  • API Gateway triggers: You can use API Gateway, select HTTP service as the backend service of an API, and then specify the address of the backend service for HTTP functions to implement features similar to those provided by HTTP triggers. For more information, see Use Function Compute as the backend service of an API.

Compared with API Gateway triggers, HTTP triggers provide the following benefits:

  • HTTP triggers are easier for developers to learn, use, and debug. This helps developers build web applications and APIs by using Function Compute.

  • You can use HTTP triggers to optimize request processing. HTTP triggers support more efficient request and response formats. You do not need to encode or decode requests to the JSON format. This delivers better performance with HTTP triggers.

  • You can use HTTP test tools that you are familiar with to test the features and performance of HTTP triggers in Function Compute.

  • You can easily connect HTTP triggers to other services, such as Alibaba Cloud CDN (CDN) and Message Service (MNS), that support webhooks.

  • WebSocket and gRPC protocols are supported.

Invocation methods

Synchronous invocations

During a synchronous invocation, results are returned after a function processes an event. By default, an HTTP trigger synchronously invokes a function. For more information, see Synchronous invocations.

Asynchronous invocations

During an asynchronous invocation, Function Compute persists the request and immediately returns a response without the need to wait for the execution of the request to be complete.

  • Asynchronous invocation: When an HTTP function is triggered, you can add the "X-Fc-Invocation-Type":"Async" request header to implement asynchronous invocation at the request level.

  • Asynchronous task: After you configure an asynchronous task for an HTTP function, you can add the "X-Fc-Stateful-Async-Invocation-Id":"g6u*****iyvhd3jk8s6bhj0hh" request header to configure the invocation ID for the asynchronous task.

For more information about request headers, see InvokeFunction.

If the asynchronous invocation is successful, Function Compute returns the 202 status code, which indicates that the request is received. Then, the values of Request ID and Stateful Invocation ID are returned in the "X-Fc-Request-Id": "80bf7****281713e1", "X-Fc-Stateful-Async-Invocation-Id": "7522ba40****1c22e" format.

Note

If the status code returned from Function Compute is not 202, the asynchronous invocation fails. For more information about the causes of failed invocations, see Error handling.

In specific scenarios, after you submit an asynchronous invocation request, you may want Function Compute to defer the invocation. If you want Function Compute to defer the invocation, you can add the x-fc-async-delay HTTP request header to code. The value range of the header is (0,3600). Unit: seconds. Function Compute invokes the function after the period specified for x-fc-async-delay elapses. For more information, see the "Deferred invocation of a function" section of the Overview topic.

Authentication

You can configure authentication for HTTP triggers. After you configure authentication for an HTTP trigger, external requests must pass the authentication before functions can process the requests. Signature authentication and JSON Web Token (JWT) authentication can be configured for HTTP triggers.

Signature authentication

If signature authentication is configured for an HTTP trigger, requests must be signed by using the assigned AccessKey IDs and AccessKey secrets. The AccessKey IDs and AccessKey secrets are passed to Function Compute for authentication. For more information, see Signature authentication.

Signature authentication provides a high level of security. However, the signature algorithm must be implemented on clients, which requires high costs. In addition, the AK and SK must be stored on the client, which may pose data leakage risks. Alibaba Cloud temporary security token (STS) can be used to prevent data leakage, but this may result in increased architectural complexity.

JWT authentication

JWT is a popular and secure mechanism for API authorization and access. JWT is suitable for low-security client scenarios, such as JavaScript or web frontend. For more information, see Configure JWT authentication for an HTTP trigger.

CORS request processing

By default, the Function Compute system allows cross-origin access to HTTP functions. Function Compute also allows you to specify a custom processing behavior for CORS requests in function code.

Simple requests

Preflight requests are not required for simple requests. You can configure a header that starts with Access-Control-Allow-* in function code to implement access control with ease. For simple requests, Function Compute supports the following custom headers: Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Request-Method, and Access-Control-Max-Age.

If a request does not include the preceding custom headers, the following response headers in Function Compute are used as the corresponding headers in a request:

  • Access-Control-Allow-Origin: the origin header of a request.

  • Access-Control-Allow-Credentials: true

  • Access-Control-Expose-Headers: custom headers in Function Compute.

Not-so-simple requests

Preflight requests are sent ahead of not-so-simple requests. The browser sends a preflight request by using the OPTIONS method, and then initiates the actual request to invoke a function. The rules to initiate a not-so-simple request are the same as the rules to initiate a simple request. If you want to specify a custom response for the preflight request, you must add the OPTIONS method to an HTTP trigger and process the OPTIONS request in function code. You can configure the header that starts with Access-Control-Allow-* to control the cross-origin behavior of the function.

For preflight requests, Function Compute supports the following custom headers: Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Request-Method, and Access-Control-Max-Age.

In this example, Node.js is used to describe how to process preflight requests in function code:

exports.handler = (req, resp, context) => {
    console.log('hello world');

    if (req.method === 'OPTIONS') {
        // Send response to OPTIONS requests
        resp.setHeader('Access-Control-Allow-Origin', 'http://www.fc.com')
        resp.setHeader('Access-Control-Allow-Methods', 'POST');
        resp.setHeader('Access-Control-Allow-Headers', 'Content-Type');
        resp.setHeader('Access-Control-Max-Age', '3600');
        resp.setStatusCode(204)
        resp.send('');
     } else {
           resp.send("hello world");
     }
}

Troubleshooting

Do I need to configure listening ports?

You must configure listening ports only if you create a function by using Use Custom Runtime or Use Container Image.

Does Function Compute support a server-sent event (SSE)?

SSE is short for Server-Sent Events. The functions created by using the Use Custom Runtime and Use Container Image methods support SSE. However, functions created by using the Use Built-in Runtime method does not support SSE.

When you deploy a function by using the Use Custom Runtime or Use Container Image method, Function Compute determines whether a response is a streaming response based on whether the response header contains Transfer-Encoding:chunked. To facilitate your use, you can select the sample code of SSE in the runtime when you deploy a function by using the Use Custom Runtime method.

What do I do if a function requires a long period of time to be invoked?

What do I do if the 499 status code is returned on a client and the client actively cancels requests?

  • If the 499 status code is returned on a client, function instances are restarted. You can configure health check for function instances to prevent instances from being restarted. For more information, see Why is a function instance restarted after a 499 status code occurs on a client?

  • If function invocation times out on a client, you can move the logic that is time-consuming to the code of new functions. Then, the asynchronous invocation feature can be used to invoke the new functions, or you can use asynchronous invocation on the client.

How do I update the configurations of a running function?

  • You can update the configurations of a running function only after the function executes requests. After you update the configurations of the function, the previous configurations still take effect for requests that are being executed. The updated configurations take effect for new requests.

  • You can delete the current function and create another function by configuring settings based on your business requirements.

References

The configurations of an HTTP trigger to invoke a function are different from those of a handler function of an event function. Make sure that the parameters of your function are valid. For more information, see the following topics: