惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
量子位
aimingoo的专栏
aimingoo的专栏
V
Visual Studio Blog
Y
Y Combinator Blog
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
宝玉的分享
宝玉的分享
Engineering at Meta
Engineering at Meta
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
Stack Overflow Blog
Stack Overflow Blog
大猫的无限游戏
大猫的无限游戏
Microsoft Security Blog
Microsoft Security Blog
B
Blog
Last Week in AI
Last Week in AI
有赞技术团队
有赞技术团队
博客园 - 聂微东
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop Wasting Bandwidth: Master API Caching with ETags ⚡
Prajapati Paresh · 2026-06-25 · via DEV Community
Cover image for Stop Wasting Bandwidth: Master API Caching with ETags ⚡

Prajapati Paresh

The Redundant Data Tax

In data-dense B2B SaaS platforms at Smart Tech Devs, clients constantly poll your API for updates. Imagine a dashboard making a GET /api/system-config request every 60 seconds. The payload is 200KB of JSON. If the configuration hasn't changed in three days, your server is spending CPU cycles serializing data, and you are paying AWS egress fees to transmit the exact same 200KB file 1,440 times a day per user.

Basic Redis caching speeds up the database query, but it doesn't stop the payload from traveling over the network. To eliminate network bloat entirely, your API must leverage the browser's native HTTP cache using ETags and the Stale-While-Revalidate directive.

The Solution: 304 Not Modified

An ETag (Entity Tag) is a cryptographic hash (like an MD5 checksum) of the response body. When the server sends the JSON, it includes the ETag in the header.

The next time the browser requests that endpoint, it sends an If-None-Match: {ETag} header. The server quickly calculates the hash of the current data. If the hashes match, the data hasn't changed! Instead of sending the 200KB JSON body, the server instantly drops the payload and replies with a tiny, empty 304 Not Modified status code. The browser knows it is safe to use its local cache, dropping network transfer times to 1 millisecond.

Architecting an ETag Middleware in Laravel

We can implement this globally across our read-only API routes using a custom Laravel Middleware layer.


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ETagCacheMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        // 1. Only cache safe, read-only methods
        if (! $request->isMethod('GET') && ! $request->isMethod('HEAD')) {
            return $next($request);
        }

        $response = $next($request);

        // 2. Generate a unique MD5 hash of the final JSON content
        $etag = md5($response->getContent());
        $requestEtag = str_replace('"', '', $request->header('If-None-Match', ''));

        // 3. If the browser's hash matches the server's hash, drop the payload!
        if ($requestEtag === $etag) {
            $response->setNotModified(); // Automatically converts to 304 and strips the body
        }

        // 4. Attach the ETag and the ultimate performance directive: stale-while-revalidate.
        // This tells the browser: "Show the cached version instantly, but check the server in the background for updates."
        $response->withHeaders([
            'ETag' => '"' . $etag . '"',
            'Cache-Control' => 'public, max-age=60, stale-while-revalidate=300'
        ]);

        return $response;
    }
}

The Engineering ROI

By implementing ETags and stale-while-revalidate, you shift the burden of data storage from your cloud servers to your user's local device. Your server response times become functionally instantaneous, network bandwidth costs plummet, and your Next.js frontend feels locally native because it never waits for unchanged data to cross the physical wire.