When we first launched our application, everything seemed to be working fine. However, we soon realized that the app was slower than expected, especially when it came to loading pages. The users started complaining about slow page load times, and it became clear that we had a performance issue. Some pages were taking as long as 5-10 seconds to load.
As developers, we understood that load time optimization and app performance improvement were critical, not just for user experience but also for SEO. That’s when we decided to implement Laravel caching to reduce the load time. The results were astonishing—we were able to reduce our app’s load time by 90%.
In this blog, I’ll walk you through how we used Laravel caching to make our app faster, optimize database queries, and improve page load speeds.
1. Identifying the Core Problem
Before we could implement caching in Laravel, we had to figure out what was slowing down our app. Here’s how we approached the problem:
Step 1: Analyze Slow Database Queries
We started by checking database performance. Using tools like Laravel Telescope and DB::listen(), we monitored the queries being executed. We discovered that complex SQL joins and inefficient queries were causing major delays. Some database queries took as long as 2-3 seconds, and with repeated requests, this was adding significant overhead.
Step 2: Investigate External API Calls
Our app was also making API calls to external services (for weather data, stock prices, etc.). These calls were taking anywhere from 500ms to 2 seconds per request. Although not huge on their own, they were adding up over multiple requests.
Step 3: Profiling with Laravel Debugbar
To dig deeper into the problem, we used Laravel Debugbar to see exactly where time was being spent during the page load. This helped us realize that the app was spending a lot of time waiting for database queries and external API responses.
2. Why Laravel Caching Was the Solution
Laravel provides a very flexible and easy-to-use caching system. We decided to leverage Laravel’s built-in caching features to store the results of expensive queries and API responses that didn’t change frequently. This would reduce repeated processing time and drastically speed up our app.
Here’s how we implemented caching in Laravel:
Caching Strategy Overview:
- Cache expensive database queries that are not frequently updated.
- Cache API responses from third-party services that don’t change every second.
- Use Redis cache for faster and more efficient storage.
3. Implementing Laravel Caching
Step 1: Set Up Redis for Caching
We chose Redis as our cache driver for its speed and efficiency. Setting it up in Laravel was simple:
- Install Redis on the server if not already installed.
- Configure Redis in the
.env
file:
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=null
REDIS_DB=0
3. After updating the .env
file, we cleared and cached the configuration:
php artisan cache:clear
php artisan config:cache
Now, Redis was ready to be used as our cache driver.
Step 2: Caching Database Queries
Next, we focused on caching database queries. Since some of our queries were quite heavy, we decided to cache the results and avoid running the same query multiple times.
Here’s how we implemented query caching using the Cache::remember
method:
use Illuminate\Support\Facades\Cache;
public function getPopularPosts()
{
// Check if the cached version exists; otherwise, run the query
$posts = Cache::remember('popular_posts', now()->addMinutes(10), function () {
return Post::with('comments')->orderBy('views', 'desc')->take(10)->get();
});
return view('posts.popular', compact('posts'));
}
What this does:
Cache::remember()
: Checks if thepopular_posts
cache exists in Redis. If it does, we fetch it from the cache. If it doesn’t, we run the query and store the result in the cache for 10 minutes.- By caching the result for 10 minutes, we significantly reduced the load on our database and improved the response time for users accessing the same data.
Step 3: Caching API Responses
For external API calls, we implemented caching to avoid making repetitive requests. For example, in our weather app, we only needed to fetch the weather data once every 5 minutes, not on every request.
Here’s how we cached the API response using Laravel’s cache system:
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
public function getWeatherData()
{
$weatherData = Cache::remember('weather_data', now()->addMinutes(5), function () {
return Http::get('https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London')->json();
});
return view('weather.index', compact('weatherData'));
}
What this does:
Cache::remember()
stores the weather data in Redis for 5 minutes.- If the cache is available, the weather data is fetched from Redis instead of calling the external API again.
- This improves page load speed and reduces unnecessary external requests.
Step 4: Caching Blade Views (Optional)
For pages that don’t change often, we also used Blade view caching. This is especially useful for static pages like the homepage or category pages.
public function showHomePage()
{
$view = Cache::remember('home_page', now()->addMinutes(30), function () {
return view('home')->render();
});
return response($view);
}
This approach caches the rendered Blade view and serves it directly from the cache for 30 minutes.
4. Performance Results
After implementing Laravel caching, we saw immediate improvements:
- Load times dropped by 90% on high-traffic pages.
- Complex database queries, which previously took 2-3 seconds, now completed in less than 100ms.
- External API calls, which used to take 1-2 seconds, now returned almost instantly because they were cached.
- Pages that previously took 10-15 seconds to load now loaded in under 2 seconds.
5. Conclusion: Why Caching Is a Game-Changer
By using Laravel caching, we were able to optimize our app’s performance and achieve lightning-fast load times. Caching database queries, API responses, and Blade views made a huge difference, and the app is now running much more efficiently.
If you are looking to improve app performance, reduce load time, and enhance the user experience, caching is one of the best techniques you can use. Laravel’s caching system is not only easy to implement but also highly scalable.
Here are a few key takeaways:
- Always cache expensive database queries to reduce redundant processing.
- Use Redis for faster caching, especially for high-traffic apps.
- Cache external API calls to minimize latency.
- Implement Blade view caching for static pages that don’t change frequently.
If you haven’t already, I highly recommend integrating Laravel caching into your app. Not only will it improve performance, but it will also make your application more scalable and responsive.
Comments