Performance issues when integrating streaming API with Drupal

I’m working on a Drupal site and trying to create a custom block that displays user streaming status, similar to what you see on gaming websites. I’ve set up a user field where people can enter their streaming username.

Here’s my current implementation in the template file:

<?php
$start_time = microtime(true);
$username = strip_tags($fields['field_username']->content);
$api_data = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($username)), true);
$status_message = " is Currently Offline";
$viewer_count = "Not Live";
$category = strip_tags($fields['field_category']->content);
if ($api_data['stream'] != NULL) {
    $display_name = $api_data['stream']['channel']['display_name'];
    $stream_status = $api_data['stream']['channel']['status'];
    $current_category = $api_data['stream']['channel']['game'];
    $viewer_count = $api_data['stream']['viewers']." watching";
    $status_message = " is Currently Live";
}
$end_time = microtime(true);
$total_time = $end_time - $start_time;
$milliseconds = $total_time * 1000;
?>
<div class=<?php echo "\"$category streamBox\"" ?> title=<?php echo "\"$viewer_count\"" ?>>
<?php
    print $milliseconds;
    print $fields['name']->content;
    echo "$status_message";
?>
</div>

The functionality works correctly, but my website becomes extremely slow when this block loads. I’m wondering if this is caused by my code implementation or if the Twitch API itself has latency issues that require a different approach?

The performance issues you’re experiencing are likely due to the synchronous nature of your API calls. When using file_get_contents() in the template, the page waits for a response from Twitch, which can lead to slow loading times. I faced similar challenges when creating a streaming display. To enhance performance, consider implementing caching for API responses using Drupal’s cache API. A TTL of 2-3 minutes can minimize requests to Twitch. Alternatively, you could utilize AJAX to load the streaming status asynchronously, allowing users to see the page immediately while the data fetches in the background.