I was pulling the data this way, but when I query with Postman, it takes too long to get the response.
public function getAllItems(Request $request)
{
$type = $request->input('type');
$query = Item::query();
if ($type === 'series') {
$query->where('is_series', true);
} elseif ($type === 'movies') {
$query->where('is_series', false);
}
$items = $query->get();
return response()->json($items, 200, [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
I tried using caching to shorten the response time. I also added the start and end times of the query to the response.
public function getAllItems(Request $request)
{
$type = $request->input('type');
$cacheKey = 'all_items_' . $type;
$startTime = microtime(true);
if (Cache::has($cacheKey)) {
$items = Cache::get($cacheKey);
$endTime = microtime(true);
$executionTime = ($endTime - $startTime);
return response()->json([
'isCache' => true,
'time' => $executionTime . ' seconds',
'data' => $items,
], 200, [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
$query = Item::query();
if ($type === 'series') {
$query->where('is_series', true);
} elseif ($type === 'movies') {
$query->where('is_series', false);
}
$items = $query->get();
Cache::put($cacheKey, $items, now()->addMinutes(60));
$endTime = microtime(true);
$executionTime = ($endTime - $startTime);
return response()->json([
'isCache' => false,
'time' => $executionTime . ' seconds',
'data' => $items,
], 200, [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
However, as you can see in the screenshot, there is a big difference between the time I added to the response and the time it took for Postman to return the response.
How can I get the response faster?
3
Answers
In my case I implemented the following solution to the problem:
I added the array to the cache using the "toArray()" method. Thus, when it fetches the data in the cache, it will not waste time parsing it again.
I save the data in the cache indefinitely and update this cache when necessary with another function.
Here's what the final version looks like:
To solve this issue, there are several ways: firstly, ignore extra columns in the query by using the
select
method, secondly, use pagination.There are several ways to reduce API response.
Example:
Use indexing for your ‘is_series’ column because you are using condition on this column.
Your Cache key may overlap. Make sure your Cache key is unique.
Consider pagination for large datasets
Example
These above points will short your response time.