I am running an application that sends multiple requests per second to fetch data from API and return responses to clients. The process flow is as follows:
- Ajax sends a request
- View sends a request
- API returns response for view
- View returns response for client
However, I have noticed that this process consumes a lot of CPU.
What could be causing the high CPU usage?
How can I optimize this process? It's important to note that I need to download currency data every second.
Should I consider using WebSocket for this?
Below is the Ajax code:
var ajaxFn = function () {
$.ajax({
url: '{% url "coinbase_currency_ajax" %}',
success: function (response) {
if(response) {
for(var elem in response) {
$("#"+elem).text(response[elem]+"$");
}
setTimeout(ajaxFn, 1000);
}
}
});
};
ajaxFn();
And here is the View code:
def currency_price_list(request):
client=CoinbaseService().client
btc = client.get_buy_price(currency_pair='BTC-USD') #API COINBASE
ltc = client.get_buy_price(currency_pair='LTC-USD')
eth = client.get_buy_price(currency_pair='ETH-USD')
bch = client.get_buy_price(currency_pair='BCH-USD')
return JsonResponse({
"btc": btc['amount'],
"ltc": ltc['amount'],
"eth": eth['amount'],
"bch": bch['amount']
}, safe=False)