Check Cache Before Making Expensive External API Calls

πŸ“– 2 minutes read

When integrating external APIs, check your cache before making expensive API calls. Don’t fetch all data upfront only to discover you had it cached.

❌ Before: Wasteful API Calls

public function handle(): int
{
    $username = $this->argument('username');

    // Fetch all data first, then check cache
    $profile = $this->fetchUserProfile($username);
    $comments = $this->fetchComments($username);
    $posts = $this->fetchPosts($username);

    // Now check if we had cached results
    $cached = $this->checkCache($username);
    
    if ($cached) {
        return $cached; // Oops, already fetched unnecessary data!
    }

    // Process the data we fetched
    return $this->processData($profile, $comments, $posts);
}

βœ… After: Cache-First Approach

public function handle(): int
{
    $username = $this->argument('username');

    // Fetch lightweight data first
    $profile = $this->fetchUserProfile($username);

    // Check cache BEFORE expensive calls
    $cached = $this->checkCache($username);
    
    if ($cached) {
        $this->line('βœ“ Using cached data');
        return $cached;
    }

    // Only fetch expensive data if cache miss
    $this->line('βœ— Cache miss - fetching data...');
    $comments = $this->fetchComments($username);
    $posts = $this->fetchPosts($username);

    return $this->processData($profile, $comments, $posts);
}

Why This Matters

This pattern reduces unnecessary API requests, saves rate limits, and improves performance. In the example above, we fetch comments and posts only when there’s a cache miss.

The key insight: lightweight checks first, expensive operations last. Your future self (and your API quota) will thank you.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *