
Lambda 执行模型
容器被创建(冷启动约 300ms),然后被重用(热启动约 0ms)。在处理器外部初始化客户端。

冷启动优化
// 在处理器外部初始化——在热调用中重用
const db = DynamoDBDocumentClient.from(new DynamoDBClient({ maxAttempts: 3 }))
const pgPool = new Pool({ connectionString: process.env.DATABASE_URL, max: 1 })
export const handler = async (event: APIGatewayEvent) => {
// db 和 pgPool 已经初始化——没有冷启动开销
}

SQS 部分批量失败
export const handler = async (event: SQSEvent) => {
const failures: SQSBatchItemFailure[] = []
await Promise.allSettled(event.Records.map(async (record) => {
try {
await processMessage(JSON.parse(record.body))
} catch (err) {
failures.push({ itemIdentifier: record.messageId })
}
}))
return { batchItemFailures: failures }
}

缓存的 SSM 密钥
const secretCache = new Map<string, string>()
async function getSecret(name: string) {
if (secretCache.has(name)) return secretCache.get(name)!
const { Parameter } = await ssm.send(new GetParameterCommand({ Name: name, WithDecryption: true }))
secretCache.set(name, Parameter!.Value!)
return Parameter!.Value!
}
成本优化
| 变更 | 节省 |
|---|---|
| 128MB → 512MB 内存 | 通常总成本降低 60% |
| ARM64 架构 | 成本降低 20% |
| 预留并发 | 防止失控扩展 |
-> 使用 Base64 转换器 对 Lambda 变量进行编码。