Description
The function in index.js is not idempotent and may insert multiple duplicate records into database.
item[PRIMARY_KEY] = uuidv4();
const params = {
TableName: TABLE_NAME,
Item: item
}
try {
await dynamoDb.put(params).promise()
return processResponse(IS_CORS);
}
When the function fails after executing dynamoDb.put(params).promise()
because runtime error or other reasons, AWS Lambda will retry the function. Then uuidv4()
will return another different id and dynamoDb.put(params).promise()
will be executed again, which creates another new record in database.
This can be fixed by making the function idempotent. First, the primary key should be provided by users as a parameter. This can avoid generating a different new primary key on retry. Second, before executing dynamoDb.put(params).promise()
, the function should check whether the record with the same primary key have been in the database. If so, that means the current execution is a retry and the function should not write the database again.
Please let me know if I've missed something or if my understanding of the code is incorrect. Thanks!