All Products
Search
Document Center

Function Compute:Access a Tair (Redis OSS-compatible) database example

Last Updated:Feb 27, 2026

Deploy a Function Compute function that connects to a Tair (Redis OSS-compatible) instance over a virtual private cloud (VPC). This guide uses Serverless Devs to deploy a Python 3 function that reads and increments a counter stored in Tair.

Prerequisites

Before you begin, make sure that you have:

Important

The Tair instance and the Function Compute function must be in the same region. Create the Tair instance in a zone that Function Compute supports. If the instance is in an unsupported zone, create a vSwitch in a supported zone within the same VPC. vSwitches in the same VPC can communicate over the private network, so Function Compute can still reach the instance. For details, see How can I resolve the "vSwitch is in unsupported zone" error?

Configure an IP address whitelist

Before you deploy the function, add the vSwitch CIDR block to the Tair instance whitelist so that Function Compute can access the instance.

Important

Use an IP address whitelist to authorize Function Compute to access the Tair instance. Do not use the security group mode. The security group mode may cause intermittent connection failures.

  1. Log on to the Tair console.

  2. In the top navigation bar, select the region where the instance is deployed.

  3. On the Instances page, find the instance and click its ID.

  4. In the left-side navigation pane, click Whitelist Settings. On the Whitelist Settings tab, find the whitelist to modify and click Modify in the Actions column.

  5. In the Modify Whitelist panel, enter the CIDR block of the vSwitch in the Whitelist field and click OK.

Procedure

Step 1: Initialize the project

Run the following command to initialize a project:

sudo s init

In the CLI prompts:

  1. Select Alibaba Cloud as the vendor.

  2. Choose the quick start mode.

  3. Select a built-in Python runtime.

  4. Specify the project name and region. This guide uses the start-fc-redis-python project in the China (Hangzhou) region.

Navigate to the project directory:

cd start-fc-redis-python

Step 2: Configure the project files

Edit s.yaml

Edit the s.yaml file with the following configuration. Update the placeholder values with your actual VPC, security group, vSwitch, and Tair instance details.

edition: 1.0.0
name: fcDeployApp
access: "default"

services:
 fc-db-redis-python:
  component: devsapp/fc
  props:
   region: cn-hangzhou
   service:
    name: fc-db-demo
    description: 'demo for fc visit db'
    internetAccess: true
    vpcConfig:
     vpcId: vpc-bp1oeg1fwxzuxcliq****       # VPC ID where the Tair instance resides
     securityGroupId: sg-bp164seaxj7wc4d0**** # Security group ID
     vswitchIds:
      - vsw-bp1192npo1ziqzw4****             # vSwitch ID (add its CIDR block to the Tair whitelist)
   function:
    name: redis
    description: visit redis
    runtime: python3
    codeUri: ./code
    handler: index.handler
    memorySize: 256
    timeout: 30
    initializationTimeout: 60
    initializer: index.initializer
    environmentVariables:
     REDIS_HOST: r-bp1h2g53l3thqg****.redis.rds.aliyuncs.com # Private endpoint of the Tair instance
     REDIS_PASSWORD: ****                                      # Tair instance password
     REDIS_PORT: 63**                                          # Private port of the Tair instance

Replace the following placeholders with your actual values:

PlaceholderDescriptionExample
vpc-bp1oeg1fwxzuxcliq****VPC ID where the Tair instance residesvpc-bp1oeg1fwxzuxcliq1234
sg-bp164seaxj7wc4d0****Security group IDsg-bp164seaxj7wc4d01234
vsw-bp1192npo1ziqzw4****vSwitch IDvsw-bp1192npo1ziqzw41234
r-bp1h2g53l3thqg****.redis.rds.aliyuncs.comPrivate endpoint of the Tair instancer-bp1h2g53l3thqg1234.redis.rds.aliyuncs.com
**** (REDIS_PASSWORD)Password for the Tair instanceYour password
63**Private port of the Tair instance6379

Edit the index.py code file

The function reads the counter key from the Tair instance, increments it by 1, writes the new value back, and returns the previous value.

# -*- coding: utf-8 -*-
import os
import redis

# Global connection pool, reused across function invocations to reduce latency
conn_pool = None


def initializer(context):
    """Initialize a Redis connection pool using environment variables."""
    global conn_pool
    conn_pool = redis.ConnectionPool(
        host=os.environ['REDIS_HOST'],
        password=os.environ['REDIS_PASSWORD'],
        port=os.environ['REDIS_PORT'],
        db=1,
        decode_responses=True
    )


def handler(event, context):
    """Read, increment, and write back a counter value in Tair."""
    global conn_pool
    r = redis.Redis(connection_pool=conn_pool)

    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 counter
Note

The redis Python library is a third-party dependency. Build the project with Docker in the next step to bundle it automatically. For other dependency management options, see Install a third-party dependency for a function.

Step 3: Build and deploy

Build the project:

sudo s build --use-docker

Deploy the project:

sudo s deploy -y

Step 4: Invoke and verify the function

sudo s invoke -e "{}"

Expected output:

[2021-09-14T17:08:50.875] [INFO ] [S-CLI] - Start ...
========= FC invoke Logs begin =========
FC Initialize Start RequestId: ccd73383-048d-4c8d-834e-93da59b86a21
FC Initialize End RequestId: ccd73383-048d-4c8d-834e-93da59b86a21
FC Invoke Start RequestId: eccafc0a-493e-4f3e-9afa-45c0b84a2c0f
counter: 0
FC Invoke End RequestId: eccafc0a-493e-4f3e-9afa-45c0b84a2c0f

Duration: 27.51 ms, Billed Duration: 28 ms, Memory Size: 256 MB, Max Memory Used: 34.05 MB
========= FC invoke Logs end =========

FC Invoke Result:
0


End of method: invoke

The returned value starts at 0 and increments with each invocation, confirming that the function reads and writes the counter key in the Tair instance. Run the invoke command multiple times to verify that the counter increments correctly: 0, 1, 2, and so on.

Troubleshooting

Connection timeout

Symptom: The function times out without returning a result.

Causes and solutions:

  1. VPC misconfiguration: Verify that the vpcId, securityGroupId, and vswitchIds in s.yaml are correct and belong to the same VPC as the Tair instance.

  2. Whitelist not configured: Confirm that the vSwitch CIDR block is added to the Tair instance whitelist. See Configure an IP address whitelist.

  3. vSwitch in an unsupported zone: Create a vSwitch in a zone that Function Compute supports. See How can I resolve the "vSwitch is in unsupported zone" error?

Authentication failure

Symptom: The function returns a NOAUTH Authentication required, ERR invalid password, or WRONGPASS invalid username-password pair error.

Causes and solutions:

  1. Incorrect password: Check the REDIS_PASSWORD environment variable in s.yaml.

  2. Incorrect host or port: Verify that REDIS_HOST and REDIS_PORT match the private endpoint and port shown in the Tair console.

Dependency errors

Symptom: The function returns a ModuleNotFoundError: No module named 'redis' error.

Solution: Build the project with Docker before deploying:

sudo s build --use-docker
sudo s deploy -y

For more troubleshooting guidance, see Common errors and troubleshooting and How to troubleshoot database access failures?

Clean up resources

To avoid ongoing charges, delete the resources created in this guide:

  1. Remove the deployed function and service:

       sudo s remove -y
  2. If the Tair instance was created for this tutorial only, release it in the Tair console.

  3. If the VPC, vSwitch, or security group was created for this tutorial only, delete them in the VPC console.

References