SCF will execute a function for you when the function receives a triggering request. Instance is the resource for SCF to execute the request. SCF will allocate resources based on the function configuration information (such as memory size) and launch one or multiple instances to process the function request. The SCF platform is responsible for the creation, management, and deletion of all function runtime instances, and you have no permissions to manage them.
The lifecycle of an instance is as shown below:
Coldstart
field in the Init Report
or Provisioned Report
line of the function execution log.Method to accelerate the three phases of instance startup:
PullCode
field in the Init Report
or Provisioned Report
line of the function execution log.InitRuntime
field in the Init Report
or Provisioned Report
line of the function execution log.InitFunction
field in the Init Report
or Provisioned Report
line of the function execution log.main_handler
, all the code logic before main_handler
will be executed.scf_bootstrap
and the code logic before listening port 9000 will be executed during instance startup.scf_bootstrap
and listening port 9000 will be executed.In order to minimize the additional time caused by instance startup, the platform will try to reuse the instance for subsequent invocations. After the instance processes the function request, it will be stored for a period of time according to the actual situation of the platform for next invocations and will be used first during this period.
The meaning of instance reuse is as follows:
/tmp
directory. The contents of this directory are retained when the container is retained, providing a temporary cache that can be used for multiple invocations. It is possible to use the contents of the disk directly when the function is invoked again. You can add extra code to check whether such data is in the cache.Note:Do not assume that the instance is always reused in the function code, because reuse is related to the single actual invocation, and it cannot be guaranteed whether a new instance will be created or an existing one will be reused.
The platform will repossess instances that have not processed requests for a certain period of time.
Each function has a temporary disk space of 512 MB (/tmp
) during execution. You can perform certain read and write operations on the space in the execution code or create subdirectories, but this part of data may not be retained after function execution is completed. Therefore, if you need to persistently store the data generated during execution, use COS or external persistent storage services such as Redis/Memcached.
The SCF platform supports both sync and async calls of functions.
Sync invocation will wait for the execution result of the function after the invocation request is sent.
The call type is independent of the configuration of the function itself and can only be controlled when the function is called.
In the following call scenarios, you can freely define the call type of the function:
invokeType=Event
parameter.If you use another Tencent Cloud service as the event source, the invocation type of the cloud service is predefined.
For the restrictions on function usage quotas and related environments, see Quota Limits.
The function concurrency is the number of executions of the function code in any given period of time. For the current SCF function, the request is executed once each time an event is published. Therefore, the number of events (i.e., requests) published by the trigger affects the function concurrency. You can use the formula below to estimate the total number of concurrent function instances.
Requests per second * function execution duration (in seconds)
For example, for a function that handles COS events, if the function takes an average of 0.2 seconds (i.e., 200 milliseconds) for execution and COS publishes 300 requests per second to the function, then 300 * 0.2 = 60 function instances will be generated simultaneously.
Currently, SCF has a limit on the amount of concurrency for each function. You can view the limit for the current function in Concurrency Overview.
If an invocation causes the function concurrency to exceed the default limit, the invocation will be blocked and not executed by SCF. Restricted invocations are handled differently depending on the function invocation type:
The current SCF execution environment is built based on the following:
If you need to include executable binaries, dynamic libraries, or static libraries in your code, make sure that they are compatible with this execution environment.
Based on different language environments, there are base libraries and additional libraries installed for the corresponding language in the SCF execution environment. You can view the additional libraries installed in the environment in the descriptions of each language:
Serverless Cloud Function (SCF) provides two deployment methods of code deployment and image deployment and supports two function types of event-triggered function and HTTP-triggered function. Different deployment methods and function types require different specifications during code development. This document describes the writing specifications and related concepts of event-triggered function in code deployment. For more information on image deployment and HTTP-triggered function, see the corresponding documents.
An SCF event-triggered function involves three basic concepts: execution method, function input parameter, and function return.
The above concepts correspond respectively to the following in general project development:
When the SCF platform invokes a function, it will first find an execution method as the entry point to execute your code. At this time, you need to set in the format of filename.execution method name.
For example, if the user-configured execution method is index.handler
, the SCF platform will first look for the index
file in the code package and find the handler
method in the file to start execution.
In the execution method, you can process the input parameters of the entry function and call other methods in the code arbitrarily. In SCF, the completion of the execution of the entry function or the exception of the execution of the function marks the end of execution.
Function input parameters refer to the content that is passed to the function when the function is triggered. Usually, there are two input parameters: event
and context
. However, the number of input parameters may vary by programming language and environment. For more information, see Code Development.
The event
parameter is of dict
type and contains the basic information that triggers the function. It can be in a platform-defined or custom format. After the function is triggered, the event can be processed inside the code.
There are two ways to trigger an SCF function:
These two SCF trigger methods correspond to two event formats:
dict
type between the invoker and the function code, where the invoker passes in the data in the format agreed upon, and the function code gets the data in the format.Sample:
You can define a data structure {"key":"XXX"}
of dict
type, and when the invoker passes in the data {"key":"abctest"}
, the function code can get the value abctest
through event [key]
.
event
parameter in a platform-predefined unchangeable format. You can write code based on this format and get information from the event
parameter.Sample:
When COS triggers a function, the specific information of the bucket and the file will be passed to the event
parameter in JSON format. The processing of the triggering event can be completed by parsing the event
information in the function code.
After understanding the basic usage of event
and context
input parameters, you should pay attention to the following points when writing function code:
The SCF platform will get the returned value after the function is executed and handle according to different trigger type as listed below.
Trigger Type | Handling Method |
---|---|
Sync triggering |
|
Async triggering |
|
When the code in a function returns a specific value, it usually returns a specific data structure; for example:
Runtime Environment | Returned Structure Type |
---|---|
Python | Simple or dict data structure |
Node.js | JSON Object |
PHP | Array structure |
GO | Simple data structure or struct with JSON description |
To ensure uniformity for different programming languages and environments, the function return will be uniformly encapsulated in the JSON data format. For example, after SCF gets the returned value of the function in the above runtime environment, it will convert the returned data structure to JSON and return it to the invoker.
Note:
- You should ensure that the returned value of the function can be converted to JSON format. If the object is returned directly and there is no JSON conversion method, SCF will fail when executing JSON conversion and prompt an error.
- For example, the returned value in the above runtime environment does not need to be converted to JSON format before it is returned; otherwise, the output string will be converted again.
If an exception occurs during testing and executing a function, the SCF platform will handle the exception as much as possible and write the exception information into the log. Exceptions generated by function execution include caught exceptions (handled errors) and uncaught exceptions (unhandled errors).
You can log in to the SCF console and follow the steps below to test exception handling:
This document provides the following three ways to throw exceptions, and you can choose how to handle exceptions in the code based on your actual needs.
Sample
def always_failed_handler (event,context):
raise Exception ('I failed!')
File "/var/user/index.py", line 2, in always_failed_handler
raise Exception ('I failed!')
Exception: I failed!
If exception handling and error capture are not performed in your code logic, the SCF platform will capture errors as much as possible such as when your function suddenly crashes and exits during execution. The platform will return a general error message if it cannot capture an error that occurs.
The table below lists some common errors in code execution:
Error Scenario | Error Message |
---|---|
raise is used to throw an exception |
{File "/var/user/index.py", line 2, in always_failed_handler raise Exception ('xxx') Exception: xxx} |
The handler does not exist | {'module' object has no attribute 'xxx'} |
The dependent module does not exist | {global name 'xxx' is not defined} |
Timed out | {"time out"} |
The SCF platform stores all the records of function invocations and the outputs of the function code in logs. You can use the printout or log statement in the programming language to generate the output logs for debugging and troubleshooting. For more information, see Log Search Guide.
Because of the nature of SCF, you must write your function code in a stateless style. State characteristics in the lifecycle of a function such as local file storage will be destroyed after the function invocation ends.
Therefore, we recommend you store persistent states in TDSQL, COS, TencentDB for Memcached, or other cloud storage services.
For more information on the function development process, see User Guide.
Was this page helpful?