Laravel Development
Your Laravel API Sends the Same Data Again and Again. Fix It With HTTP Caching
Is your Laravel API repeatedly sending the same JSON data to clients? Learn how to use Cache-Control, ETag, conditional requests, and HTTP 304 responses to reduce unnecessary data transfer and improve API performance.
Laravel Development
Your Laravel API Sends the Same Data Again and Again. Fix It With HTTP CachingIf your API keeps returning data that has not changed, you may be wasting bandwidth, server resources, and response time. Learn how HTTP caching, ETags, and conditional requests can make Laravel APIs more efficient.
The problem: the same response is sent repeatedly
Imagine your Laravel application exposes an endpoint that returns a list of categories. A frontend requests the endpoint every time a user opens a page.
The category list changes only occasionally, but the server sends the full JSON response every time. If the response is large and many users request it, unnecessary data transfer and repeated work can add up.
HTTP caching gives clients and intermediary caches a way to reuse a response when it is still valid. You can also let the client ask whether its cached copy has changed before sending the full response again.
1. Understand Cache-Control
The Cache-Control response header tells browsers and shared caches how a response may be stored and reused.
For data that can safely be cached by a browser for a short period, a response might include:
Cache-Control: private, max-age=60
This tells a private cache, such as the user's browser, that it may reuse the response for up to 60 seconds without
revalidating it. The private directive prevents shared caches from storing it.
For public data that is identical for all users, a different policy may be appropriate:
Cache-Control: public, max-age=300
Use public caching only when the response is genuinely safe to share across users. Never apply it blindly to authenticated or user-specific API responses.
2. Add Cache-Control headers in Laravel
You can attach cache headers directly to a JSON response. Here is a simple example for a public categories endpoint:
use App\Models\Category;
public function index()
{
$categories = Category::query()
->select(['id', 'name', 'slug'])
->orderBy('name')
->get();
return response()
->json($categories)
->header('Cache-Control', 'public, max-age=300');
}
The browser can reuse the response for five minutes. This is a simple time-based policy. It does not automatically invalidate a cached response the moment a category changes.
3. Use ETags for conditional requests
An ETag is a validator for a particular representation of a resource. The server sends an ETag with the response.
On a later request, the client can send that value in the If-None-Match request header.
If the representation has not changed, the server can respond with 304 Not Modified and no response body. The client can then reuse its cached copy.
A simplified Laravel example:
use App\Models\Category;
use Illuminate\Http\Request;
public function index(Request $request)
{
$categories = Category::query()
->select(['id', 'name', 'slug'])
->orderBy('name')
->get();
$payload = $categories->toJson();
$etag = '"' . hash('sha256', $payload) . '"';
if ($request->header('If-None-Match') === $etag) {
return response('', 304)
->header('ETag', $etag)
->header('Cache-Control', 'public, max-age=0, must-revalidate');
}
return response($payload, 200)
->header('Content-Type', 'application/json')
->header('ETag', $etag)
->header('Cache-Control', 'public, max-age=0, must-revalidate');
}
This example calculates a validator from the response payload. For production use, ensure the ETag changes whenever any part of the representation changes, including relevant related data, permissions, locale, or other request-dependent variations. Also account for weak validators and multiple ETag values if your application needs full HTTP conditional request semantics.
4. What happens during a 304 response?
The flow looks like this:
- The client requests the API endpoint for the first time.
- The server returns the JSON response together with an ETag.
- The client stores the response and its validator in its HTTP cache.
- On a later request, the client sends the saved ETag using
If-None-Match. - If the resource has not changed, the server responds with
304 Not Modified. - The client reuses its stored response instead of downloading the full JSON body again.
A 304 response reduces response-body transfer, but the server may still need to perform work to determine whether the resource has changed. If computing the response is expensive, consider efficient validators, timestamps, version columns, or caching the underlying data as well.
5. Use Laravel's cache for expensive data
HTTP caching helps clients avoid downloading unchanged data. Laravel's application cache can also reduce repeated database work on the server.
use Illuminate\Support\Facades\Cache;
use App\Models\Category;
public function index()
{
$categories = Cache::remember(
'public_categories',
now()->addMinutes(5),
fn () => Category::query()
->select(['id', 'name', 'slug'])
->orderBy('name')
->get()
);
return response()
->json($categories)
->header('Cache-Control', 'public, max-age=300');
}
The first request loads the data from the database and stores it in the configured cache store. Subsequent requests can reuse the cached value until it expires.
When categories change, invalidate the application cache:
Cache::forget('public_categories');
You can place invalidation logic in the relevant service or model event workflow. Make sure every write path that changes the cached data also invalidates or refreshes the cache.
6. Do not cache private API responses publicly
This is one of the most important caching rules. A response containing a user's profile, account details, private dashboard data, or permission-dependent content must not be treated like a public category list.
For sensitive or user-specific responses, you may want a policy such as:
Cache-Control: no-store
no-store tells caches not to store the response. If private browser caching is appropriate for a particular
authenticated endpoint, define that policy deliberately and ensure the cache varies correctly by identity and
authorization context. Never rely on a URL alone to distinguish private data between users.
7. When should you use HTTP caching?
HTTP caching is particularly useful for data that changes infrequently, such as:
- Public categories and tags.
- Public product or article listings.
- Reference data and configuration.
- Public documentation and metadata.
- Static or versioned API resources.
It is less suitable for rapidly changing data or personalized responses unless you have designed the cache policy and validation strategy specifically for those cases.
Final thoughts
Returning the same API data repeatedly can waste bandwidth and server resources. HTTP caching gives clients a way to reuse valid responses, while ETags let them check whether a representation has changed before downloading it again.
Combine appropriate Cache-Control policies, conditional requests, and Laravel's application cache
where they make sense. Keep private data private, invalidate cached data when it changes, and ensure validators
represent the complete response.
A fast API does not always need to send less useful data. It needs to stop sending unchanged data unnecessarily.