Drupal site performance issues when integrating streaming platform API

I’m working on a Drupal project where I need 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 input their streaming platform username.

Here’s my template code:

<?php
$start_time = microtime(true);
$username = strip_tags($fields['field_username']->content);
$api_response = json_decode(file_get_contents('https://api.twitch.tv/helix/streams?user_login='.strtolower($username)), true);
$status_text = " is currently offline";
$viewer_count = "Not streaming";
$user_game = strip_tags($fields['field_game']->content);
if (!empty($api_response['data'])) {
    $stream_data = $api_response['data'][0];
    $broadcaster_name = $stream_data['user_name'];
    $stream_description = $stream_data['title'];
    $current_category = $stream_data['game_name'];
    $viewer_count = $stream_data['viewer_count']." watching";
    $status_text = " is live now";
}
$end_time = microtime(true);
$response_time = $end_time - $start_time;
$milliseconds = $response_time * 1000;
?>
<div class=<?php echo "\"$user_game streamStatus\"" ?> title=<?php echo "\"$viewer_count\"" ?>>
<?php
    print $milliseconds;
    print $fields['username']->content;
    echo "$status_text";
?>
</div>

The functionality works correctly, but my website becomes extremely slow when this block loads. Is this a problem with my implementation or is the external API naturally slow? Should I look into caching solutions or alternative approaches?

Blocking I/O is definitely your bottleneck. I hit the same issue building a guild status display for a gaming site. What saved me was switching to a queue-based setup - API calls run in the background via cron jobs instead of during page requests. Store the streaming status in a custom table and update it every minute or two. Your pages load instantly while showing fresh data. Also, Twitch needs proper headers including Client-ID for their API calls, so make sure you’re handling authentication correctly. Moving those external calls out of the request cycle makes a huge difference.

dude ur using file_get_contents() which blocks everything - that’s why it’s slow as hell. switch to guzzle or curl with proper timeouts. also cache those api calls for at least 30 seconds because hammering twitch’s api on every page load will destroy ur performance