heroku

2 min read

As you may know, free dynos on Heroku sleeps after 30 mins of inactivity. You can count about 5 or 6 seconds to wake it up. But if you're a student or you want to save money, I have a nice trick for you.
The goal here is to maintain the dyno awake. So, as the specification on the site says:

Sleeps after 30 mins of inactivity, otherwise always on depending on your remaining monthly free dyno hours

If the dyno receives a request, every time before the 30 minutes elapse, it will stay online.
There are many ways to do so, but i prefer these 2.

  1. Programmatically
  2. A website monitoring tool

Let's do this.

via GIPHY

1. Node.js - Programmatically, the old fashion way

n this case, we need a function that sends a request to the website every 10 or 20 minutes ( 600 or 1200 seconds ). Let's make it in javascript so you can try it right now by hitting Ctrl + C or Cmd + C.
There is the code.

const wakeUpDude = (url, interval, cors) => {
    if ( cors === true ){
        url = "https://cors-anywhere.herokuapp.com/" + url;
    }
    setInterval(() => { 
            fetch(url)
            .then(response => console.log("Request successfully sent, status: ", response.status))
            .catch((error) => console.log("Can't access webstie, error =>",error))
        }, interval );
}

wakeUpDude('https://www.hermann.codes', 600, true)

The function wakeUpDude receives 3 params:

  • URL - The URL of the dyno to prevent from sleeping
  • interval - The time interval between 2 requests in seconds
  • cors - True, to prevent CORS issues.

Why CORS?

If the request is sent from another website, the request may be blocked by the CORS policy. So I've added and proxy that can partially solve this issue.

Using the setInterval function makes the things lot easier. Once the request is completed, it logs the response code and a little text.

2. A website monitoring tool

How can this help? The principle behind website monitoring tools is the same as the previous function. It sends a request and if the response code is not 200, you get an email. We will exploit the fact that it sends requests frequently. I think you can use anyone.

I use DownNotifier, it's free and easy to setup. It sends a request to the dyno every 10 minutes.

Conclusion
That's all. Now you can have your dyno awake all time.

via GIPHY

Enjoying our content? share with a friend, on Twitter.
Any question? Any suggestion? Tell me down here 👇

Hermann

Hermann

A geek and a big dreamer.

https://itishermann.me Limoges, France