首页 > 解决方案 > 为什么一个简单的 SQL 查询会导致我的 Lambda 函数显着变慢?

问题描述

我构建了一个托管在 AWS Lambda 上并通过 AWS API Gateway 提供服务的基本 node.js API。这是代码:

'use strict';

// Require and initialize outside of your main handler
const mysql = require('serverless-mysql')({
    config: {
      host     : process.env.ENDPOINT,
      database : process.env.DATABASE,
      user     : process.env.USERNAME,
      password : process.env.PASSWORD
    }
  });

// Import the Dialogflow module from the Actions on Google client library.
const {dialogflow} = require('actions-on-google');

// Instantiate the Dialogflow client.
const app = dialogflow({debug: true});

// Handle the Dialogflow intent named 'trip name'.
// The intent collects a parameter named 'tripName'.
app.intent('trip name', async (conv, {tripName}) => {

    // Run your query
    let results = await mysql.query('SELECT * FROM tablename where field = ? limit 1', tripName)

    // Respond with the user's lucky number and end the conversation.
    conv.close('Your lucky number is ' + results[0].id);

    // Run clean up function
    await mysql.end()
});

// Set the DialogflowApp object to handle the HTTPS POST request.
exports.fulfillment = app;

它接收一个参数(行程名称),在 MySQL 中查找并返回结果。

我的问题是 API 响应时间超过 5 秒,速度很慢。

我不知道为什么它很慢?MySQL 是一个强大的Amazon Aurora,并且 node.js 应该很快。

我从与 MySQL(孟买)相同的 AWS 区域测试了该功能,但它仍然超时,所以我认为它与不同区域之间的距离无关。

缓慢的原因是执行任何 SQL 查询(甚至是非常简单的SELECT)。它确实带回了正确的结果,但速度很慢。

当我删除 SQL 部分时,它变得非常快。我将 Lambda 的内存增加到最大,并将 Aurora 重新部署到更强大的内存。

标签: node.jsaws-lambdaaws-api-gatewayactions-on-googlegoogle-assist-api

解决方案


如果您配置更多内存,Lambda 函数将运行得更快。配置的内存越少,性能越差。

这意味着如果您已将函数配置为使用 128MB,它将在非常低配置的硬件中运行。

另一方面,如果您将其配置为使用 3GB,它将在一台非常不错的机器上运行。

在 1792MB 时,您的函数将在具有专用内核的硬件中运行,考虑到您正在使用 IO 调用(例如网络请求),这将显着加快您的代码速度。您可以在此处查看此信息

虽然没有神奇的公式。您必须运行一些测试并查看最适合您的应用程序的内存配置。我会从 3GB 开始,最终减少 128MB 的块,直到找到正确的配置。


推荐阅读