Lambda连接us-east-1区域DynamoDB超时问题求助
Lambda函数读取DynamoDB超时问题排查与解决
问题描述
编写了如下Lambda函数用于读取us-east-1区域DynamoDB中名为Message的表数据:
// Loads in the AWS SDK const AWS = require('aws-sdk'); // Creates the document client specifing the region const ddb = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'}); exports.handler = async (event, context, callback) => { // Handle promise fulfilled/rejected states await readMessage().then(data => { data.Items.forEach(function(item) { console.log(item.message) }); callback(null, { // If success return 200, and items statusCode: 200, body: data.Items, headers: { 'Access-Control-Allow-Origin': '*', }, }) }).catch((err) => { // If an error occurs write to the console console.error(err); }) }; // Function readMessage // Reads 10 messages from the DynamoDb table Message // Returns promise function readMessage() { const params = { TableName: 'Message', Limit: 10 } return ddb.scan(params).promise(); }
函数执行时始终超时,无任何错误日志。已尝试延长超时至5分钟、开启/关闭配置6个子网的VPC,均无法解决;但简单的HelloWorld函数可正常运行。疑问:是否需要安装AWS SDK?
解答
关于AWS SDK的疑问
不需要手动安装AWS SDK。Lambda的Node.js运行时环境已经内置了AWS SDK,直接引用即可。
超时问题排查与解决
权限缺失(最可能原因)
Lambda执行角色没有DynamoDB的访问权限,会导致请求被静默拦截,最终超时。需要给Lambda的执行角色添加权限:- 可直接附加
AmazonDynamoDBReadOnlyAccess托管策略(适合测试场景); - 或创建自定义策略,仅允许对
Message表执行dynamodb:Scan操作(遵循最小权限原则)。
- 可直接附加
VPC配置问题(若Lambda在VPC内)
如果Lambda部署在VPC中,必须确保有访问DynamoDB的路径:- 配置DynamoDB VPC网关端点:这是访问DynamoDB的最优方式,无需公网;
- 或给子网配置NAT网关:让Lambda通过公网访问DynamoDB公网端点(需确保安全组出站规则允许访问DynamoDB端口)。
若关闭VPC后仍超时,可排除VPC网络问题,重点检查权限。
代码逻辑不规范
原代码混用了async/await与then/callback,可能导致Lambda进程无法正确终止,进而超时。同时响应body需为字符串类型,原代码直接返回对象会引发问题。修正后的代码如下:// Loads in the AWS SDK const AWS = require('aws-sdk'); // Creates the document client specifying the region const ddb = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'}); exports.handler = async (event) => { try { const data = await readMessage(); data.Items.forEach(item => { console.log(item.message); }); return { statusCode: 200, body: JSON.stringify(data.Items), headers: { 'Access-Control-Allow-Origin': '*', }, }; } catch (err) { console.error(err); return { statusCode: 500, body: JSON.stringify({error: err.message}), headers: { 'Access-Control-Allow-Origin': '*', }, }; } }; // Function readMessage // Reads 10 messages from the DynamoDb table Message // Returns promise function readMessage() { const params = { TableName: 'Message', Limit: 10 }; return ddb.scan(params).promise(); }
内容的提问来源于stack exchange,提问作者Gracie williams
相关产品推荐
相关产品推荐

