All Products
Search
Document Center

Function Compute:Best practices for accessing Redis

Last Updated:Sep 05, 2025

In Function Compute, states are not shared between different execution environment instances. You can use databases to persist structured data to achieve state sharing. By accessing cloud databases through Function Compute, you can perform operations such as data queries and data insertion. This topic uses Python 3 as an example to describe how to access Tair (Redis OSS-compatible) within the same VPC or across VPCs and regions.

Prerequisites

Create a Redis instance

Procedure

Step 1: Configure the database whitelist

Scenario 1: Access a Redis database within the same VPC

Important
  • Make sure that the database instance that you create is in the same region as the function that needs to access the database instance.

  • You create a database instance in a zone that is supported by Function Compute. For more information, see Zones supported by Function Compute.

  • If your database instance is not deployed in a zone that is supported by Function Compute, create a vSwitch in your VPC. The vSwitch must be in the same zone as Function Compute. In addition, you must specify the vSwitch ID in the VPC configuration of the specified service in Function Compute. Because private networks can communicate with each other between different vSwitches in the same VPC, Function Compute can access resources in VPCs in other zones through the vSwitch. For more information, see What do I do if the vSwitch is in unsupported zone error occurs?.

  1. Log on to the Tair (Redis OSS-compatible) console, select a region in the top navigation bar, click the target instance ID, click Instance Information, and view the VPC information of the Redis instance.

    image

  2. Log on to the Function Compute console, create a Python web function, enable VPC access for the function, and configure the target VPC resource.

    Note

    Make sure that the VPC configured for the function is the same as the VPC to which the database instance is attached.

    image

  3. On the function details page, choose Configuration > Network, and then obtain the CIDR block of the vSwitch in the function configuration on the Network page.

    image

  4. Add the CIDR block of the vSwitch in the function configuration obtained in the previous step to the database access whitelist.

    Important

    Use an IP address whitelist to authorize functions to access the database. Do not use the security group mode. Otherwise, functions may occasionally fail to connect to the database, which affects the businesses.

    1. Log on to the console, select a region in the top navigation bar, and then click the target instance ID.

    2. In the left-side navigation pane of the instance details page, click Whitelist Settings. On the Whitelist Settings tab, find the target whitelist group and click Modify in the Actions column.

    3. In the Modify Whitelist Group panel that appears, enter the CIDR block of the vSwitch to which the target instance is attached in the IP Addresses In Whitelist Group field, and then click OK.

      image

After the configuration is complete, the function can access the Redis database through the internal endpoint of the database.

Scenario 2: Access a Redis database across VPCs or regions

Different VPCs and regions are completely logically isolated from each other. In general, you cannot access databases across VPCs or regions. If you need to access a database across VPCs or regions, you can configure a static public IP address for the function. In this case, the system creates a public NAT Gateway in the virtual private cloud (VPC) to which the function is attached. You can access the database through the public IP address by using the public gateway.

  1. Log on to the Tair (Redis OSS-compatible) console, click Instance Information, and view the VPC information of the Redis instance.

    image

  2. Log on to the Function Compute console, create a Python web function. On the function details page, choose Configuration > Network. In the Network panel, configure a static public IP address for the function, and then click Deploy.

    image

  3. In the Static Public IP Configuration dialog box that appears, select the check box in the prompt box, and then click OK. After the configuration is complete, set the Allow Default NIC To Access Internet parameter to No to make the configured static public IP address take effect. For more information, see Configure a static public IP address.

    Note

    After you set the Allow Default NIC To Access Internet parameter to No, the static public IP address takes effect. Function Compute disables the default network interface card (NIC) to force traffic to access the Internet through the NIC that is attached to the VPC.

  4. On the function details page, choose Configuration > Network, and then obtain the static public IP address configured for the function on the Network page.

    image

  5. Add the static public IP address of the function obtained in the previous step to the database access whitelist.

    Important

    Use an IP address whitelist to authorize functions to access the database. Do not use the security group mode. Otherwise, functions may occasionally fail to connect to the database, which affects the businesses.

    1. Log on to the Management Console, select a region at the top, and then click the target instance ID.

    2. In the left-side navigation pane of the instance details page, click Whitelist Settings. On the Whitelist Settings tab, find the target whitelist group and click Modify in the Actions column.

    3. In the Modify Whitelist Group panel that appears, configure the static public IP address in the whitelist in the IP Addresses In Whitelist Group dialog box, and then click OK.

      image

After the configuration is complete, the function can access the Redis database through the public endpoint of the database.

Step 2: Access Redis in a function

  1. Log on to the Function Compute console, find the target function in the function list, click the Code tab on the function details page, and write the following sample code in the code editor.

    from flask import Flask,jsonify
    import os
    import redis
    
    app = Flask(__name__)
    
    # Global variable for storing Redis singleton connection
    _redis_connection = None
    
    # Create database connection (singleton pattern)
    def getConnection():
        global _redis_connection
        try:
            # If the connection already exists and is not disconnected, return it directly
            if _redis_connection is not None:
                try:
                    # Test if the connection is valid (simple ping command)
                    if _redis_connection.ping():
                        return _redis_connection
                except redis.ConnectionError:
                    # If the connection is disconnected, reset it
                    _redis_connection = None
    
            # If the connection does not exist or is disconnected, recreate it
            _redis_connection = redis.Redis(
                host=os.environ['REDIS_HOST'],
                password=os.environ['REDIS_PASSWORD'],
                port=os.environ['REDIS_PORT'],
                db=1,
                decode_responses=True
            )
            # Test if the new connection is successful
            if not _redis_connection.ping():
                raise Exception("Redis connection failed after creation.")
            return _redis_connection
        except Exception as e:
            print(f"Failed to initialize Redis connection: {e}")
            raise
    
    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
    def hello_world(path):
        try:
            r = getConnection()
            counter = r.get('counter')
            if counter is None:
                counter = 0
            else:
                counter = int(counter)
            print('counter: ' + str(counter))
            r.set('counter', str(counter + 1))
            return str(counter)
        except Exception as e:
            print(f"An error occurred: {e}")
            return jsonify({"error": str(e)}), 500
       
    
    if __name__ == '__main__':
            app.run(host='0.0.0.0',port=9000)
    
  2. On the Function Details page, choose Configuration > Environment Variables, click Edit, and configure the following environment variables in the Environment Variables panel.

    Environment variable name

    Environment variable value

    Description

    REDIS_HOST

    r-bp*****.redis.rds.aliyuncs.com

    The endpoint of the database instance. If you select the Redis database within the same VPC scenario, set this environment variable to the VPC endpoint of the database. If you select the Redis database across VPCs or regions scenario, set this environment variable to the public endpoint of the database.

    Visit the Instance List, select a region in the top navigation bar, and then click the target instance ID. In the left-side navigation pane, click Instance Information. In the Connection Information section, obtain the connection address information for connecting to the database.

    image

    REDIS_PASSWORD

    *****

    The password of the database.

    REDIS_PORT

    6379

    The port number of the database

  3. Set the initial value in the Redis database. On the function details page, click the Code tab, click Test Function, and check the returned result after successful execution.

    image

More information

  • For more examples of accessing Tair (Redis OSS-compatible), see Function Compute Python accessing Tair (Redis OSS-compatible).

  • For more exception cases about accessing Tair (Redis OSS-compatible), see Common errors.

  • If the exception problem you encounter has not been resolved, you need to troubleshoot based on the problem symptoms. For more information, see Common causes of database access failures.

  • If you want to use the Serverless Devs command-line tool to create functions and access the Tair (Redis OSS-compatible) database, see the following steps.

    Click here to view the Serverless Devs operation steps

    1. Install Serverless Devs and Docker, and add key information. For more information, see Quick Start.

    2. Create the code directory mycode, and prepare the s.yaml file and the code file app.py. For the sample code of app.py, see the sample code provided in Step 2: Access Redis in a function. The following is a sample s.yaml file.

      The following s.yaml example applies to the scenario of accessing a Redis database within the same VPC. If you need to access a database across VPCs or regions, see Scenario 2: Access a Redis database across VPCs or regions.

      # ------------------------------------
      #   Official manual: https://manual.serverless-devs.com/user-guide/aliyun/#fc3
      #   Tips: https://manual.serverless-devs.com/user-guide/tips/
      #   If you have any questions, join the DingTalk group 33947367
      # ------------------------------------
      edition: 3.0.0
      name: hello-world-app
      access: "default"
      
      vars: # Global variables
        region: "cn-hangzhou"  # If you choose to access the RDS database within the same VPC, make sure that the function is deployed in the same region as the RDS database
      
      resources:
        hello_world:
          component: fc3 
          actions:       
            pre-${regex('deploy|local')}: 
              - component: fc3 build 
          props:
            region: ${vars.region}              
            functionName: "start-python-redis"
            runtime: custom.debian10
            description: 'hello world by serverless devs'
            timeout: 10
            memorySize: 512
            cpu: 0.5
            diskSize: 512
            code: ./code
            customRuntimeConfig:
              port: 9000
              command:
                - python3
                - app.py  
            internetAccess: true
            vpcConfig:
             vpcId: vpc-bp1dxqii29fpkc8pw**** # The VPC ID of the database instance
             securityGroupId: sg-bp12ly2ie92ixrfc**** # The security group ID
             vSwitchIds: 
              - vsw-bp1ty76ijntee9z83**** # Make sure that the CIDR block of this vSwitch is configured in the database instance access whitelist
            environmentVariables:
              PYTHONPATH: /code/python
              PATH: /code/python/bin:/var/fc/lang/python3.10/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin
              REDIS_HOST: r-bp*****.redis.rds.aliyuncs.com  # The database endpoint
              REDIS_PASSWORD: *****     # The database password
              REDIS_PORT: "6379"         # The database port
             

      The directory structure of the code is as follows.

      ├── code
      │ ├── app.py
      │ └── requirements.txt
      └── s.yaml

      The dependencies specified in the requirements.txt file are as follows.

      flask==2.2.5
    3. Run the following command to build the project.

      sudo s build --use-docker
    4. Run the following command to deploy the project.

      sudo s deploy -y
    5. Run the following command to invoke the function.

      Note

      Make sure that the CIDR block of the vSwitch configured for the function has been added to the database instance access whitelist. For more information, see Step 4.

      sudo s invoke -e "{}"