title: AWS Lambda Timeout when connecting to Redis Elasticache in same VPC
body: <p>Trying to publish from a Lambda function to a Redis Elasticache, but I just continue to get <code>502 Bad Gateway</code> responses with the Lambda function timing out.</p>
  <p>I have successfully connected to the Elasticache instance using an ECS in the same VPC which leads me to think that the VPC settings for my Lambda are not correct. I tried following this tutorial (<a href="https://docs.aws.amazon.com/lambda/latest/dg/services-elasticache-tutorial.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/lambda/latest/dg/services-elasticache-tutorial.html</a>) and have looked at several StackOverflow threads to no avail.</p>
  <p>The Lambda Function:</p>
  <pre class="lang-js prettyprint-override"><code>export const publisher = redis.createClient({
    url: XXXXXX, // env var containing the URL which is also used in the ECS server to successfully connect
  });
  
  export const handler = async (
    event: AWSLambda.APIGatewayProxyWithCognitoAuthorizerEvent
  ): Promise&lt;AWSLambda.APIGatewayProxyResult&gt; =&gt; {
    try {
      if (!event.body || !event.pathParameters || !event.pathParameters.channelId)
        return ApiResponse.error(400, {}, new InvalidRequestError());
  
      const { action, payload } = JSON.parse(event.body) as {
        action: string;
        payload?: { [key: string]: string };
      };
  
      const { channelId } = event.pathParameters;
  
      const publishAsync = promisify(publisher.publish).bind(publisher);
  
      await publishAsync(
        channelId,
        JSON.stringify({
          action,
          payload: payload || {},
        })
      );
  
      return ApiResponse.success(204);
    } catch (e) {
      Logger.error(e);
      return ApiResponse.error();
    }
  };
  </code></pre>
  <p>In my troubleshooting, I have verified the following in the Lambda functions console:</p>
  <ul>
  <li>The correct role is showing in <code>Configuration &gt; Permissions</code></li>
  <li>The lambda function has access to the VPC (<code>Configuration &gt; VPCs</code>), Subnets, and the same SG as the Elasticache instance.</li>
  <li>The SG is allowing all traffic from anywhere.</li>
  <li>It is indeed the Redis connection. Using <code>console.log</code> the code stops at this line: <code>await publishAsync()</code></li>
  </ul>
  <p>I am sure it is something small, but it is racking my brain!</p>
  <h2>Update 1:</h2>
  <p>Tried adding an error handler to log any issues with the publish in addition to the main <code>try/catch</code> block, but it's not logging a thing.</p>
  <pre><code>publisher.on('error', (e) =&gt; {
      Logger.error(e, 'evses-service', 'message-publisher');
    });
  </code></pre>
  <p>Also have copied my Elasticache setup:
  <a href="https://i.stack.imgur.com/WMK9b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WMK9b.png" alt="enter image description here" /></a></p>
  <p>And my Elasticache Subnet Group:
  <a href="https://i.stack.imgur.com/kkMed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kkMed.png" alt="enter image description here" /></a></p>
  <p>And my Lambda VPC settings:
  <a href="https://i.stack.imgur.com/nxpYw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nxpYw.png" alt="enter image description here" /></a></p>
  <p>And that my Lambda has the right access:
  <a href="https://i.stack.imgur.com/U974a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U974a.png" alt="enter image description here" /></a></p>
  <h2>Update 2:</h2>
  <p>Tried to follow the tutorial here (<a href="https://docs.aws.amazon.com/lambda/latest/dg/services-elasticache-tutorial.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/lambda/latest/dg/services-elasticache-tutorial.html</a>) word for word, but getting the same issue. No logs, just a timeout after 30 seconds. Here is the test code:</p>
  <pre><code>const crypto = require('crypto');
  const redis = require('redis');
  const util = require('util');
  
  const client = redis.createClient({
    url: 'rediss://clusterforlambdatest.9nxhfd.0001.use1.cache.amazonaws.com',
  });
  
  client.on('error', (e) =&gt; {
    console.log(e);
  });
  
  exports.handler = async (event) =&gt; {
    try {
      const len = 24;
  
      const randomString = crypto
        .randomBytes(Math.ceil(len / 2))
        .toString('hex') // convert to hexadecimal format
        .slice(0, len)
        .toUpperCase();
  
      const setAsync = util.promisify(client.set).bind(client);
      const getAsync = util.promisify(client.get).bind(client);
  
      await setAsync(randomString, 'We set this string bruh!');
      const doc = await getAsync(randomString);
  
      console.log(`Successfully receieved document ${randomString} with contents: ${doc}`);
  
      return;
    } catch (e) {
      console.log(e);
  
      return {
        statusCode: 500,
      };
    }
  };
  </code></pre>