Using Redis in a Lambda Function

I have a lambda function that fetches data from the YouTube V3 API and it gets called on page load. I’m using Redis to cache this result so that it doesn’t hit the YouTube API everytime the page is loaded and this works great locally.

However when I deployed it the first time, I got Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

Okay maybe I need to change the url to the Redis server. So I changed it to be redis://effpv.netlify.com:6379 thinking maybe that was it. Now I get no errors, that’s cool. But it doesn’t do anything at all now. That’s not so cool.

Any Ideas? Here’s my Lambda function in it’s entirety https://gist.github.com/TravisBallard/9505619548e8f56795b276877c467db7

Your error catch might not be in the correct place. I’m not sure without a test, try instead:

await axios.get(url)
  .then(response => {
    const {data} = response;
    const {items} = data;

    if (items === undefined || items.length === 0) {
      callback(null, {statusCode: 200, body: '{"status":"No Items."}'});
    }

    const {statistics} = items[0];
    client.setex(id, expirationTime, JSON.stringify(statistics));
    callback(null, {statusCode: 200, body: JSON.stringify(statistics)});
  })
  .catch(error => {
    console.log('error:', error.message)
    callback(error);
  })

Still giving me the same thing unfortunately.

9:12:34 AM: getVideoInfo invoked
9:13:22 AM: getVideoInfo invoked
9:15:47 AM: getVideoInfo invoked
9:46:43 AM: getVideoInfo invoked

The first 3 were from my first round of testing after changing the url, the last one at 9:46AM was with the console log in the catch statement

I’m not sure where you think redis is “running” - it’s not running on our service :slight_smile: While you could spin it up in a function, it would terminate immediately when the function exits, so you wouldn’t be able to connect to it except from the same function instance you are running from. This seems like a suboptimal use of functions to me - you really in tend to start redis, query it, and do something with the result in 10 seconds? You can’t save any data to it (there is no backing store for it that persists), so I’m struggling to understand the use case. You’d want to set up a redis elsewhere - like in AWS or Digital Ocean - where it will run persistently - and connect to it there, would be my suggestion.

1 Like

Makes sense. Im new to lambda functions in general and when I asked this, I didn’t realize that they were only temporary instances that get spun up when called upon. I’ve since started setting up a redis server on heroku to handle this. Thanks for your feedback

1 Like