Axios timeout for chunked responses
ALRIGHT, this was an interesting one. I use Axios in one of my pet projects . Basically, the project is a Telegram bot that transforms voice messages into text. I know that Telegram now has this feature for premium subscribers, but this is not something we are about to cover in this article. Here I want to talk about the tricky way the Axios timeout works. Let's start with the simple HTTP server…
Axios is a popular JavaScript library used for making HTTP requests. One interesting aspect of Axios is its timeout feature, which allows developers to set a limit on how long a request can take before it is cancelled. In a recent project involving a Telegram bot that converts voice messages into text, the author encountered an unexpected behavior when using Axios with chunked responses.
The author created a simple HTTP server using Express, with a single API endpoint that takes 10 seconds to resolve. They then used Axios to make a POST request to this endpoint, specifying a timeout of 5 seconds. Upon running the code, they observed that the request took exactly 5 seconds to complete, as expected.
However, when the author integrated Axios with a streaming API for their Telegram bot, they encountered a problem. The bot receives voice messages in chunks, which are processed and sent back to the user in real-time. By using Axios, the author found that the timeout was reset with each chunk received, effectively cancelling the overall request time.
To demonstrate this issue, the author created a new Express endpoint that sends one chunk of the response every second, for a total of 10 seconds. When they made a POST request to this endpoint using Axios with a timeout of 10 seconds, they saw that the request was resolved as soon as the first chunk was received, despite the remaining chunks taking a significant amount of time to be sent.
This unexpected behavior of Axios with chunked responses can lead to inaccurate timing and potentially affect the performance of applications that rely on real-time data, such as the Telegram bot in this case.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.