api-lambda-save-dynamodb icon indicating copy to clipboard operation
api-lambda-save-dynamodb copied to clipboard

Idempotency bug in index.js

Open Nsupyq opened this issue 4 years ago • 1 comments

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!

Nsupyq avatar Oct 31 '21 13:10 Nsupyq

Sorry, I think it is unnecessary to check whether the record with the same primary key have been in the database. We just need to ensure there will be only one new record in database. I have modified my PR #8 and removed unnecessary check.

Nsupyq avatar Nov 03 '21 14:11 Nsupyq