Recently, I was trying to get into Python programming by developing a Telegram bot using a Telegram API wrapper based on Python. During the development phase everything was working fine. The bot responded quickly even after a few minutes of delay between each command.
However, after deploying the bot into a Ubuntu 16.04 server on Azure. The bot would not response after a few minutes (4 minutes to be exact). This would happen for both Polling (Update) or Webhook methods.
After many hours of troubleshooting. I finally found the problem it was an Azure IP Address interface configuration. By default Azure closes all idle TCP or HTTP connection after 4 minutes. The connection can only be kept open if clients send a keep-alive message.
However, this does not resolve my problem with the telegram bots as by default in Ubuntu servers a keep-alive message is only sent after 7200 seconds (2 Hours). That’s too long even for the longest Idle timeout setting you can set in Azure which is 30 minutes.
After finding out what the issue was. Finding a solution was relatively easy and quick. From a quick Google search I found a documentation on TCP Settings for Azure VMs on Github.
The document states that “Azure VMs communicate with the public Internet by using NAT (Network Address Translation). NAT devices assign a public IP address and port to an Azure VM, allowing that VM to establish a socket for communication with other devices. If packets stop flowing through that socket after a specific time, the NAT device kills the mapping, and the socket is free to be used by other VMs.”
TL;DR: The solution is to configure you server operating system to keep the connections alive.
sudo nano /etc/sysctl.conf
net.ipv4.tcp_keepalive_time = 120
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 8
sudo sysctl -p
And you’re done! I hope that this have solved your Azure VMs and TCP/HTTP timeout issue.