π 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.
Leave a Reply