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

推荐订阅源

S
Securelist
博客园 - Franky
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
量子位
Hugging Face - Blog
Hugging Face - Blog
有赞技术团队
有赞技术团队
V
V2EX
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Full Disclosure
L
LangChain Blog
大猫的无限游戏
大猫的无限游戏
雷峰网
雷峰网
G
Google Developers Blog
B
Blog
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
小众软件
小众软件
博客园 - 【当耐特】
H
Help Net Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
博客园 - 叶小钗
Jina AI
Jina AI
Cloudbric
Cloudbric
N
Netflix TechBlog - Medium
Hacker News - Newest:
Hacker News - Newest: "LLM"
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
I
Intezer
IT之家
IT之家
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
W
WeLiveSecurity
G
GRAHAM CLULEY
J
Java Code Geeks
H
Heimdal Security Blog
Cyberwarzone
Cyberwarzone
MyScale Blog
MyScale Blog
Latest news
Latest news
Schneier on Security
Schneier on Security
H
Hacker News: Front Page
Martin Fowler
Martin Fowler
V
Visual Studio Blog
Webroot Blog
Webroot Blog
P
Palo Alto Networks Blog
T
Tor Project blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Beyond the Cache Miss: Designing Resilient Caching Layers with Redis Degradation Strategies
Shubham Bhati · 2026-06-22 · via DEV Community

Shubham Bhati

1. The Anatomy of a Cache Disaster

To design a solution, we must first analyze how cache failures manifest as systemic outages. Consider a standard read-through caching pattern:

[Client] ---> [API Gateway] ---> [Product Service] 
                                    |         |
                              (1) Read    (2) Miss? Read DB
                                    v         v
                                 [Redis]   [PostgreSQL]

The Failure Cascade

If Redis latency increases from 2ms to 2000ms (due to network congestion or CPU saturation), the following cascade occurs:

  1. Thread Pool Exhaustion: The API container's HTTP worker threads (e.g., Tomcat, Netty) wait on Redis read timeouts. New incoming requests queue up, quickly exhausting the container's thread pool.
  2. The Cache Stampede (Thundering Herd): If the Redis connection drops entirely, all concurrent requests for a popular resource miss simultaneously. They bypass the cache and hit the downstream database together.
  3. Database Demolition: The database, designed for a fraction of the cache's read volume, experiences immediate connection pool saturation, CPU spikes to 100%, and starts dropping requests. The entire platform goes offline.

Root Cause Analysis (RCA)

The root cause is tight coupling and synchronous blocking on the caching layer. The application treats Redis as a hard dependency rather than an opportunistic optimization.


2. The Resilient Architecture: Multi-Tier Caching & Circuit Breaking

To build a resilient caching layer, we must implement three core design patterns:

  1. Dual-Layer Caching (L1/L2):
    • L1 (Local Memory): A small, fast, in-memory cache (e.g., Caffeine) residing within the application process JVM.
    • L2 (Distributed Cache): Redis.
  2. Circuit Breaking & Fallbacks: Wrapping Redis interactions inside a circuit breaker. If Redis error rates or response times cross a threshold, the breaker trips, bypassing Redis entirely and falling back to L1 or a safe database read-through.
  3. Asynchronous Non-Blocking Refresh (Stale-While-Revalidate): Serving slightly stale data from L1/L2 while asynchronously updating the cache in the background.
                  +---------------------------------------+
                  |           Product Service             |
                  +---------------------------------------+
                                      |
                           [Check L1 Cache (Local)]
                                      | (Miss)
                                      v
                        +----------------------------+
                        |   Resilience4j Breaker     |
                        +----------------------------+
                          /                        \
                 (Closed)/                          \(Open / Half-Open)
                        v                            v
               [Check L2 (Redis)]             [Fallback Path]
                 /            \                      |
         (Hit)  /      (Miss)  \ (Error)             |
               v                v                    v
         [Return Data]   [Query DB & Populate]  [Query DB (Rate Limited) / Stale Data]


3. Implementation: Building a Resilient Cache Manager in Spring Boot

Let's implement this architecture using Java 17, Spring Boot 3, Caffeine (L1), Redis (L2), and Resilience4j.

Dependency Configuration (pom.xml)

<dependencies>
    <!-- Spring Boot Starter Cache -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- Caffeine (L1 Cache) -->
    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>
    <!-- Resilience4j Circuit Breaker -->
    <dependency>
        <groupId>io.github.resilience4j</groupId>
        <artifactId>resilience4j-spring-boot3</artifactId>
        <version>2.1.0</version>
    </dependency>
</dependencies>

The Resilient Cache Layer Implementation

We will write a custom ResilientProductService that coordinates the L1 cache, the L2 Redis cache protected by a circuit breaker, and the database fallback.

package com.example.cache.service;

import com.example.cache.model.Product;
import com.example.cache.repository.ProductRepository;
import com.github.benmanes.caffeine.cache.Cache;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class ResilientProductService {

    private final ProductRepository productRepository;
    private final RedisTemplate<String, Product> redisTemplate;
    private final Cache<String, Product> l1CaffeineCache; // Local JVM cache

    private static final String REDIS_KEY_PREFIX = "product:";
    private static final String REDIS_CIRCUIT_BREAKER = "redisService";

    /**
     * Fetch Product with a resilient multi-tier fallback architecture.
     * 1. Try L1 Cache (Caffeine)
     * 2. Try L2 Cache (Redis) - Wrapped in Circuit Breaker
     * 3. Database Fallback (with automatic L1/L2 repopulation)
     */
    public Product getProduct(String productId) {
        // Step 1: Query L1 (In-Memory JVM Cache) - Instant, cannot fail due to network
        Product product = l1CaffeineCache.getIfPresent(productId);
        if (product != null) {
            log.debug("L1 Cache Hit for product: {}", productId);
            return product;
        }

        // Step 2: Query L2 (Redis) via Circuit Breaker
        return getProductFromL2WithCircuitBreaker(productId);
    }

    /**
     * Redis lookup protected by Resilience4j.
     * If Redis is slow or down, the fallbackMethod is executed.
     */
    @CircuitBreaker(name = REDIS_CIRCUIT_BREAKER, fallbackMethod = "fallbackGetProductFromDb")
    private Product getProductFromL2WithCircuitBreaker(String productId) {
        log.debug("L1 Cache Miss. Querying L2 (Redis) for product: {}", productId);
        String key = REDIS_KEY_PREFIX + productId;

        // This operation will throw an exception if Redis is unreachable, 
        // triggering the circuit breaker and fallback.
        Product product = redisTemplate.opsForValue().get(key);

        if (product != null) {
            log.debug("L2 Cache Hit for product: {}", productId);
            // Populate L1 cache so subsequent reads avoid L2/Network completely
            l1CaffeineCache.put(productId, product);
            return product;
        }

        // Step 3: L2 Miss -> Query Database
        log.warn("L2 Cache Miss for product: {}. Fetching from Database.", productId);
        Product dbProduct = productRepository.findById(productId)
                .orElseThrow(() -> new ResourceNotFoundException("Product not found: " + productId));

        // Asynchronously or synchronously populate caches
        populateCaches(productId, dbProduct);
        return dbProduct;
    }

    /**
     * Fallback Method executed when the Redis Circuit Breaker is OPEN or Redis throws an Exception.
     * This bypasses Redis to protect database connection pools from starvation.
     */
    private Product fallbackGetProductFromDb(String productId, Throwable throwable) {
        log.error("Redis Cache Unavailable (Circuit Breaker status/error: {}). Falling back directly to DB.", 
                  throwable.getMessage());

        // Under degradation, we fetch from the database. 
        // Optional: Implement a rate-limiter or semaphore here to prevent database overload!
        Product dbProduct = productRepository.findById(productId)
                .orElseThrow(() -> new ResourceNotFoundException("Product not found: " + productId));

        // Populate L1 (Local Memory) only. Do NOT touch Redis while it is struggling.
        l1CaffeineCache.put(productId, dbProduct);

        return dbProduct;
    }

    private void populateCaches(String productId, Product product) {
        // Populate L1
        l1CaffeineCache.put(productId, product);

        // Populate L2 (Redis) with write-timeout protection
        try {
            redisTemplate.opsForValue().set(
                REDIS_KEY_PREFIX + productId, 
                product, 
                Duration.ofMinutes(10)
            );
        } catch (Exception e) {
            log.error("Failed to populate L2 Redis Cache. Suppressing exception to avoid client disruption.", e);
        }
    }
}

Application Configuration (application.yml)

The circuit breaker config is critical. We must set low timeouts for Redis connections and configure the circuit breaker sensitivity to trip quickly.

spring:
  data:
    redis:
      host: localhost
      port: 6379
      connect-timeout: 200ms # Short connect timeout
      timeout: 100ms         # Very aggressive read timeout for microsecond cache lookups

resilience4j:
  circuitbreaker:
    instances:
      redisService:
        slidingWindowType: COUNT_BASED
        slidingWindowSize: 20           # Track last 20 requests
        minimumNumberOfCalls: 10         # Min calls before calculating error rate
        failureRateThreshold: 50         # Trip if 50% of last 20 calls failed
        slowCallRateThreshold: 75        # Trip if 75% of calls are slower than limit
        slowCallDurationThreshold: 50ms  # Call is "slow" if it takes > 50ms
        waitDurationInOpenState: 15s     # Keep breaker open for 15s before retrying
        permittedNumberOfCallsInHalfOpenState: 5
        automaticTransitionFromOpenToHalfOpenEnabled: true


4. Mitigating Cache Stampede: Mutex Locking

If a highly popular cache key expires (e.g., home page configuration), the fallback database lookup can still trigger a spike. To solve this, we implement Single-Flight Lock (using a Mutex lock / local synchronization) to ensure only one thread fetches the missing data from the database, while other concurrent requests wait or yield stale data.

Below is an implementation of a thread-safe local lock bypass for database reads:

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class StampedeProofProductService {

    private final ProductRepository productRepository;
    private final Cache<String, Product> l1Cache;
    private final ConcurrentHashMap<String, ReentrantLock> keyLocks = new ConcurrentHashMap<>();

    public Product getProductWithStampedeProtection(String productId) {
        Product product = l1Cache.getIfPresent(productId);
        if (product != null) {
            return product;
        }

        // Get or create a lock specific to this productId
        ReentrantLock lock = keyLocks.computeIfAbsent(productId, k -> new ReentrantLock());

        if (lock.tryLock()) {
            try {
                // Double-checked locking pattern
                Product doubleCheck = l1Cache.getIfPresent(productId);
                if (doubleCheck != null) {
                    return doubleCheck;
                }

                // Fetch from Database
                Product dbProduct = productRepository.findById(productId).orElseThrow();
                l1Cache.put(productId, dbProduct);
                return dbProduct;
            } finally {
                lock.unlock();
                keyLocks.remove(productId); // Clean up map
            }
        } else {
            // If lock cannot be acquired, a concurrent thread is already pulling from the DB.
            // Option A: Sleep briefly and retry local cache lookup.
            // Option B: Serve a stale/cached default payload.
            return handleContentionFallback(productId);
        }
    }

    private Product handleContentionFallback(String productId) {
        try {
            Thread.sleep(50); // Small backoff
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        // Retry once from L1
        Product fallback = l1Cache.getIfPresent(productId);
        if (fallback != null) {
            return fallback;
        }
        // Last-resort mock / read-through fallback logic
        return Product.builder().id(productId).name("Fallback Limited Details").build();
    }
}


5. Operational Verification: Testing Caching Failure Modes

To verify your degradation layer is functioning, run architectural chaos testing:

Test Case Simulation Action Expected System Behavior Verified?
Normal Path Warm cache read L1 Hit (0ms overhead) / L2 Hit (1-3ms latency). [ ]
L2 Connection Drop Block port 6379 using iptables First few requests trigger timeouts. Circuit breaker trips to OPEN. Subsequent requests go directly to DB / L1 without querying Redis. [ ]
Redis CPU Spike (100%) Execute complex script in Redis Reads exceed 50ms timeout threshold. Circuit Breaker transitions to OPEN due to slowCallRateThreshold. DB protected. [ ]
Self-Healing Unblock port 6379 Circuit Breaker goes to HALF-OPEN after 15s. Sends 5 test requests. Passes. Breaker goes CLOSED. System restored automatically. [ ]

Summary: Caching Best Practices for Architects

  1. Establish Aggressive Timeouts: Never use default timeouts for cache connections. For Redis, connection timeouts should be <200ms, and command execution timeouts <100ms.
  2. Never Let Redis Failure Crash the App: Wrap distributed cache calls in a fallback or a circuit breaker.
  3. Keep L1 Lean: Use L1 (Caffeine/Ehcache) to cache high-frequency read keys with extremely short TTLs (e.g., 30-60 seconds) to guard against sudden hot-key spikes.
  4. Log & Monitor Cache State Transitions: Create alerts for Circuit Breaker status changes (CLOSED to OPEN) to detect issues before they affect end-users.