Search code examples
amazon-web-servicesaws-lambdaaws-serverlessamazon-cognito-triggers

How to execute more than one lambda in different microservices listening for the cognito PreSignUp event?


Until recently I had a lambda in a microservice that triggered with the cognito PreSignUp event. Now I need to run another one in another microservice, but since I put it in, only one really runs. What do I have to do to be able to execute both, even more lambdas, with the same trigger event?


Solution

  • For anything below, make sure not to take longer than 5 seconds or Cognito will timeout and try the call again up to 3 times.

    1. Have a Cognito trigger lambda calling multiple other child lambdas, using invoke()
    const lambda = new AWS.Lambda({region: 'us-east-1', apiVersion: '2015-03-31'})
    
    await Promise.all([
      lambda.invoke({
          FunctionName: 'ChildLambda1',
          InvocationType: 'Event',
          LogType: 'None',
          Payload: Buffer.from(JSON.stringify(<DATA HERE>))
        }).promise(),
      lambda.invoke({
          FunctionName: 'ChildLambda2',
          InvocationType: 'Event',
          LogType: 'None',
          Payload: Buffer.from(JSON.stringify(<DATA HERE>))
        }).promise()
    ])
    
    1. Set a trigger lambda that simply makes API calls to each of the micro-service endpoints that need to be triggered

    2. Have each child lambda subscribe to an SNS topic and have the Cognito trigger lambda send a message to said topic (AWS docs)

    // SNS subscriptions to "Cognito_PreSignUp" topic are configured in AWS console
    
    // Send message from Cognito trigger lambda
    const sns = new AWS.SNS({apiVersion: '2010-03-31'})
    
    await sns.publish({
      Message: JSON.stringify(<DATA HERE>),
      TopicArn: 'Cognito_PreSignUp'
    }).promise()