Search code examples
amazon-web-servicesaws-lambdaaws-api-gatewayuuid

Aws lambda and uuid, it always return same value


mycode:

const axios = require('axios')
const uuid = require('uuid').v1();
const rand = Math.random();

exports.lambdaHandler = async (event) => {
    //const uuix = uuid.v1();
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: uuid,
            rand: rand,
        })
    }

};

every time it run, it should return different rand and uuid but it always return same value. When I test it locally using sam local start-api it work perfectly.


Solution

  • This is because lambda will re-use its execution environment which results in:

    Objects declared outside of the function's handler method remain initialized, providing additional optimization when the function is invoked again.

    Since your uuid and rand are created outside of the handler, lambda is simply re-using them - it does not generate them for as long as the execution environment is valid.

    To rectify the issue, you have to create the variables in your handler:

    const axios = require('axios')
    const uuid = require('uuid');
    
    exports.lambdaHandler = async (event) => {
    
        const uuix = uuid.v1(); 
        const rand = Math.random();
    
        return {
            statusCode: 200,
            body: JSON.stringify({
                message: uuix,
                rand: rand,
            })
        }
    };