如何在AWS Lambda(Python3.8)中并行执行多个PostgreSQL SQL查询
在采用Python 3.8运行时的AWS Lambda函数中,我创建了2个进程,每个进程尝试并行执行2个完全独立的函数,各运行一条SQL查询,所有查询均访问使用psycopg2驱动的PostgreSQL数据库的不同表。
我在AWS Lambda函数启动阶段就创建了单个connection对象,所有运行的进程都复用该连接对象,每个进程使用独立的游标,进程执行结束后关闭对应游标。
同时我启用了全局的connection.autocommit = True配置,AWS Lambda函数的MemorySize设置为10240。
执行代码时,两个进程均抛出以下错误:
[ERROR] psycopg2.OperationalError: SSL error: decryption failed or bad record mac
根据psycopg2官方文档说明:
在使用multiprocessing这类模块,或FastCGI这类采用fork机制的Web部署方式时,请确保在fork操作完成后再创建数据库连接。
我担心在每个进程中单独创建数据库连接对象会大幅拖慢AWS Lambda的执行速度,因此目前使用全局变量POSTGRESQL_CONNECTION来复用预先创建好的数据库连接。请问这种场景下我该如何处理?我的核心需求是在AWS Lambda中并行执行多条SQL查询。
代码片段
import logging import os from multiprocessing import Process, Pipe from psycopg2.extras import RealDictCursor from functools import wraps from typing import * import databases # AWS Lambda Layer logger = logging.getLogger(__name__) logger.setLevel(logging.ERROR) # The connection to the database will be created the first time the AWS Lambda function is called. # Any subsequent call to the function will use the same database connection until the container stops. POSTGRESQL_CONNECTION = None # Initialize global variables with parameters for settings. POSTGRESQL_USERNAME = os.environ["POSTGRESQL_USERNAME"] POSTGRESQL_PASSWORD = os.environ["POSTGRESQL_PASSWORD"] POSTGRESQL_HOST = os.environ["POSTGRESQL_HOST"] POSTGRESQL_PORT = os.environ["POSTGRESQL_PORT"] POSTGRESQL_DB_NAME = os.environ["POSTGRESQL_DB_NAME"] def reuse_or_recreate_postgresql_connection(): global POSTGRESQL_CONNECTION if not POSTGRESQL_CONNECTION: try: POSTGRESQL_CONNECTION = databases.create_postgresql_connection( POSTGRESQL_USERNAME, POSTGRESQL_PASSWORD, POSTGRESQL_HOST, POSTGRESQL_PORT, POSTGRESQL_DB_NAME ) except Exception as error: logger.error(error) raise Exception("Unable to connect to the PostgreSQL database.") return POSTGRESQL_CONNECTION def execute_parallel_processes(functions: List[Dict[AnyStr, Union[Callable, Dict[AnyStr, Any]]]]) -> Dict[AnyStr, Any]: # Create an empty list to keep all parallel processes. processes = [] # Create an empty list of pipes to keep all connections. pipes = [] # Create a process per function. for index, function in enumerate(functions): # Check whether the input arguments have keys in their dictionaries. try: target = function["function_object"] except KeyError as error: logger.error(error) raise Exception(error) try: kwargs = function["function_arguments"] except KeyError as error: logger.error(error) raise Exception(error) # Create a pipe for communication. parent_pipe, child_pipe = Pipe() pipes.append(parent_pipe) kwargs["pipe"] = child_pipe # Create a process. process = Process(target=target, kwargs=kwargs) processes.append(process) # Start all parallel processes. for process in processes: process.start() # Wait until all parallel processes are finished. for process in processes: process.join() # Get the results of all processes. results = {} for pipe in pipes: results = {**results, **pipe.recv()} # Return the results of all processes. return results def psycopg2_cursor(function): @wraps(function) def wrapper(**kwargs): try: postgresql_connection = kwargs["postgresql_connection"] except KeyError as error: logger.error(error) raise Exception(error) cursor = postgresql_connection.cursor(cursor_factory=RealDictCursor) result = function(cursor=cursor, **kwargs) cursor.close() return result return wrapper @psycopg2_cursor def get_product_data(**kwargs) -> None: # Check whether the input arguments have keys in their dictionaries. try: cursor = kwargs["cursor"] except KeyError as error: logger.error(error) raise Exception(error) try: arguments = kwargs["sql_arguments"] except KeyError as error: logger.error(error) raise Exception(error) try: pipe = kwargs["pipe"] except KeyError as error: logger.error(error) raise Exception(error) # Prepare the SQL query. statement = "select * from products where product_id = %(product_id)s limit 1;" # Execute the SQL query dynamically, in a convenient and safe way. try: cursor.execute(statement, arguments) except Exception as error: logger.error(error) raise Exception(error) # Send data to the pipe and then close it. pipe.send({ "product_data": cursor.fetchone() }) pipe.close() @psycopg2_cursor def get_user_data(**kwargs) -> None: # Check whether the input arguments have keys in their dictionaries. try: cursor = kwargs["cursor"] except KeyError as error: logger.error(error) raise Exception(error) try: arguments = kwargs["sql_arguments"] except KeyError as error: logger.error(error) raise Exception(error) try: pipe = kwargs["pipe"] except KeyError as error: logger.error(error) raise Exception(error) # Prepare the SQL query. statement = "select * from users where user_id = %(user_id)s limit 1;" # Execute the SQL query dynamically, in a convenient and safe way. try: cursor.execute(statement, arguments) except Exception as error: logger.error(error) raise Exception(error) # Send data to the pipe and then close it. pipe.send({ "user_data": cursor.fetchone() }) pipe.close() def lambda_handler(event, context): postgresql_connection = reuse_or_recreate_postgresql_connection() # Run several functions in parallel to get all necessary data from different databases tables. results_of_processes = execute_parallel_processes([ { "function_object": get_product_data, "function_arguments": { "postgresql_connection": postgresql_connection, "sql_arguments": { "product_id": event["product_id"] } } }, { "function_object": get_user_data, "function_arguments": { "postgresql_connection": postgresql_connection, "sql_arguments": { "user_id": event["user_id"] } } } ]) product_data = results_of_processes["product_data"] user_data = results_of_processes["user_data"] return { 'statusCode': 200, 'body': json.dumps(results_of_processes) }
名为databases的AWS Lambda Layer代码如下:
def create_postgresql_connection(db_username, db_password, db_host, db_port, db_name): connection = psycopg2.connect(user=db_username, password=db_password, host=db_host, port=db_port, database=db_name) connection.autocommit = True return connection
报错根源完全匹配psycopg2官方文档提到的场景:psycopg2的连接对象包含进程非安全的内部状态,尤其是SSL连接的加解密上下文在fork后会被多个子进程共享,同时读写就会触发MAC校验失败。
针对你担心的新建连接拖慢性能的问题,结合Lambda运行特性,可按优先级选择以下方案:
方案1:改用线程并行替代多进程(优先推荐)
psycopg2的连接线程安全等级为2,支持多线程同时在同一个连接上创建独立游标执行查询,完全不需要单独建连,性能开销远低于多进程模式。
修改要点:
- 替换
multiprocessing.Process为concurrent.futures.ThreadPoolExecutor - 移除原有的Pipe通信逻辑,线程执行完直接返回结果即可
修改后的并行执行逻辑示例:
from concurrent.futures import ThreadPoolExecutor def execute_parallel_threads(functions: List[Dict]) -> Dict: with ThreadPoolExecutor(max_workers=len(functions)) as executor: futures = [executor.submit(func["function_object"], **func["function_arguments"]) for func in functions] # 汇总所有线程的返回结果 results = {} for future in futures: results.update(future.result()) return results
对应业务函数不需要额外处理连接,直接复用父进程已经初始化好的全局连接拿游标即可,不会触发SSL报错。
方案2:必须用多进程时按进程隔离创建连接
PostgreSQL普通TCP连接的建立耗时通常在10~50ms级别,两个进程各建一个连接的额外开销仅几十毫秒,远低于多进程本身的fork开销,也远低于SQL查询的执行耗时,性能影响可以忽略。
修改要点:
- 父进程不要预先创建PostgreSQL连接,仅传递连接参数给子进程
- 每个子进程启动后再创建专属连接,使用完后关闭
调整后的lambda_handler示例:
def lambda_handler(event, context): # 不再预先创建全局连接,直接传数据库参数 results_of_processes = execute_parallel_processes([ { "function_object": get_product_data, "function_arguments": { "db_params": { "db_username": POSTGRESQL_USERNAME, "db_password": POSTGRESQL_PASSWORD, "db_host": POSTGRESQL_HOST, "db_port": POSTGRESQL_PORT, "db_name": POSTGRESQL_DB_NAME }, "sql_arguments": { "product_id": event["product_id"] } } }, # 用户数据查询逻辑同理传递db_params即可 ])
业务函数内部修改为先创建连接再拿游标:
def get_product_data(**kwargs): db_params = kwargs["db_params"] conn = databases.create_postgresql_connection(**db_params) cursor = conn.cursor(cursor_factory=RealDictCursor) # 原有SQL执行逻辑不变... # 执行完后关闭游标和连接 cursor.close() conn.close() return {"product_data": result}
如果同一次Lambda调用内有多个相同进程的任务,可以在子进程内维护进程级全局连接,避免重复建连。
额外优化提示
你当前配置的10GB内存Lambda实例,完全可以承载4~8个并行线程,对于短查询场景,线程并行的吞吐量远高于多进程模式,同时还能复用父进程已经建立的连接,没有额外开销。
内容的提问来源于stack exchange,提问作者Nurzhan Nogerbek

