How to keep your free hosted Heroku web app awake 24/7

Heroku is a very exciting free hosting service that allows us, developers to host free web apps or websites on the cloud in minutes. This service is especially famous among python developers, as it is probably the only free hosting service that supports python (If you know any other service, let me know in the comments). It is very convenient to deploy experimental code or small scale apps. For those of you who don't know, this format of cloud service is called PaaS, which stands for Platform as a Service.

The problem

The thing about all these free services online are, they all come with strings attached. Some of them are free only for a limited period of time, and some are free for a limited set of features. I personally prefer the later. An example of the first kind is Microsoft Azure. They have a 30 day trial period and they take your credit card information while registering. Whereas Heroku doesn't take your credit card information while registering. But it has limited features and resources.

One of the limitations is that, the free servers that they provide come in a container which they call a dyno. And each free app is assigned only one dyno. And these dynos act as the "platform" for your web app/ website. Also, another catch is that these dynos are not awake 24/7. When your web app is inactive for a certain amount of time, they reassign that particular dyno to some other web app that needs it. This way they reuse their resources for free accounts.

The consequence 

So, during the time it is inactive if somebody tries to access the web app, it will take a lot of time to load. Because in the background, it has to search for some other inactive web app and grab its dyno. This delay in time can sometimes cause a problem. For example, me and a friend are making a native android app which uses a REST API that we have deployed on Heroku. This delay in response sometimes caused a connection time-out exception in the app.

The solution

So the simple solution to this is, keep your server active. You can do this by simply pinging the server every 5-10 minutes. This will make Heroku think that your web app needs the dyno. There are many ways to implement this hack. One of the ways is by manually going to the web app on your browser via PC or phone which is stupid. The smarter way to deal with it is by writing a script that automates it. So, here is a sample code to implement it.

You can deploy this script on Heroku itself (I know right!). I have done something similar in this post do check it out.

So I hope this helps you deploy better app/API/website experiences and achieve your goals. If you have any alternate solutions to this problem, I'd love it if you shared it in the comments.