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

推荐订阅源

L
LINUX DO - 最新话题
C
Cyber Attacks, Cyber Crime and Cyber Security
G
GRAHAM CLULEY
T
Tenable Blog
T
Threatpost
C
CXSECURITY Database RSS Feed - CXSecurity.com
I
Intezer
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
D
Darknet – Hacking Tools, Hacker News & Cyber Security
K
Kaspersky official blog
Security Latest
Security Latest
P
Privacy & Cybersecurity Law Blog
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
P
Palo Alto Networks Blog
TaoSecurity Blog
TaoSecurity Blog
Webroot Blog
Webroot Blog
Spread Privacy
Spread Privacy
O
OpenAI News
The Last Watchdog
The Last Watchdog
P
Proofpoint News Feed
C
Check Point Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
人人都是产品经理
人人都是产品经理
S
Security @ Cisco Blogs
Scott Helme
Scott Helme
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
月光博客
月光博客
S
Securelist
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
T
Troy Hunt's Blog
W
WeLiveSecurity
GbyAI
GbyAI
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
Cisco Blogs
H
Help Net Security
The GitHub Blog
The GitHub Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 【当耐特】
Jina AI
Jina AI
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
小众软件
小众软件
N
News and Events Feed by Topic

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
Redis缓存三连击:击穿、雪崩、穿透全解析!
port smith · 2026-04-27 · via DEV Community

port smith

Redis缓存三连击:击穿、雪崩、穿透,一次讲透!

双十一大促零点,你手速拉满抢限量神券——结果页面卡死、刷新失败、“系统繁忙”弹窗反复刷屏。后台可能正被三股力量轮番暴击:有人用脚本狂刷根本不存在的用户ID(穿透);爆款商品详情页在缓存过期那一毫秒,被上万请求同时“凿穿”(击穿);而整个商品库的缓存Key又恰巧在整点集体失效(雪崩)。这三者不是玄学黑话,而是真实可复现、可定位、可防御的典型故障链。


一、缓存穿透:查不到,还拼命查

定义:查询压根不存在的数据(比如user:999999999),缓存无记录,请求直冲数据库,高频无效查询拖垮DB。

▶️ 极简复现:

EXISTS user:999999999  # 返回0,但每秒1万次?DB瞬间变筛子。

Enter fullscreen mode Exit fullscreen mode

✅ 防御双保险(Python示例):

import redis, hashlib
from bloom_filter import BloomFilter

r = redis.Redis()
bf = BloomFilter(capacity=1000000, error_rate=0.001)

def get_user(user_id):
    key = f"user:{user_id}"
    # 1. 布隆过滤器快速拦截绝对不存在的key
    if not bf.contains(key):
        return None

    # 2. 查缓存
    data = r.get(key)
    if data:
        return data

    # 3. 缓存未命中,查DB(此处省略具体实现)
    db_data = query_db_user(user_id)

    if db_data:
        r.setex(key, 3600, db_data)  # 正常数据缓存1小时
    else:
        r.setex(key, 300, "NULL")  # 空值缓存5分钟,防反复穿透

    return db_data

Enter fullscreen mode Exit fullscreen mode

核心就两点:存在性前置校验 + 空值短期缓存,把无效流量挡在数据库门外。


二、缓存击穿:热点Key过期的“生死1毫秒”

定义:某个超高频Key(如首页推荐位hot_item)恰好过期,瞬间大量并发请求穿透缓存,争抢重建,数据库CPU飙升。

▶️ 复现场景:

GET hot_item 返回 nil 的刹那,1000个线程同时执行SET——谁先写?谁来查库?没协调就是灾难。

✅ 加锁重建(Python + Redis SETNX):

def get_hot_item():
    key = "hot_item"
    data = r.get(key)
    if data:
        return data

    lock_key = f"lock:{key}"
    # 尝试加分布式锁(带自动过期,防死锁)
    if r.set(lock_key, "1", nx=True, ex=5):
        try:
            # 二次检查:防止重复重建
            data = r.get(key)
            if not data:
                data = build_hot_item_from_db()
                r.setex(key, 3600, data)
            return data
        finally:
            r.delete(lock_key)  # 必须释放锁
    else:
        # 未抢到锁,短暂等待后重试(或返回旧缓存/降级数据)
        time.sleep(0.01)
        return get_hot_item()

Enter fullscreen mode Exit fullscreen mode

关键点:锁粒度最小化、自动过期、二次检查、异常必释放


三、缓存雪崩:大批Key集体“下班”

定义:大量Key设置相同过期时间(如凌晨2点统一TTL=3600),到期后集中失效,流量洪峰同步涌向数据库。

▶️ 探测风险(仅限开发环境!):

KEYS item:*  # ⚠️ 生产禁用!更安全方式:SCAN + TTL采样

Enter fullscreen mode Exit fullscreen mode

✅ 根治方案(Python):

import random

def set_item_with_jitter(key, value, base_ttl=3600):
    jitter = random.randint(-int(base_ttl*0.1), int(base_ttl*0.1))
    final_ttl = max(600, base_ttl + jitter)  # 不低于10分钟
    r.setex(key, final_ttl, value)

# 核心数据兜底:逻辑永不过期 + 异步刷新
def set_essential_item(key, value):
    r.set(key, value)
    # 后台任务每30分钟主动更新一次

Enter fullscreen mode Exit fullscreen mode

口诀记牢:不设固定过期时间,只设“基础TTL+随机抖动”;核心数据宁可冗余更新,也不集体断供。


四、真实踩坑与监控预警实战

我们曾在线上活动遭遇穿透事故:未对注册手机号做空值缓存,黑产脚本遍历user:138****0001138****9999,DB连接数10秒飙至2000+,服务全面超时。

如何提前发现?两个低成本监控项:

  • Redis慢日志:执行 SLOWLOG GET 5,若频繁出现GET命令+大量nil响应,大概率有穿透苗头;
  • 客户端错误率:用Prometheus监控redis_connection_errors_total,配置告警规则: rate(redis_connection_errors_total[5m]) > 0.1 → 立即排查是否雪崩前兆。

监控不是锦上添花,而是故障前的最后一道哨兵。


结语:稳如磐石的缓存铁三角

穿透、击穿、雪崩,本质是缓存与数据一致性之间的三道裂缝。守住它们,只需三招:

🔹 存在性校验——布隆过滤器+空值缓存,让“不存在”止步于缓存层;

🔹 热点保护——原子锁+双重检查,把重建动作串行化;

🔹 过期分散——随机TTL+异步刷新,避免缓存集体休眠。

缓存不是银弹,而是需要精心设计的防护体系。你在项目中用过哪种防护组合?欢迎在评论区晒出你的redis.conf关键配置或自研工具片段——Dev.to的极客们,正等着抄作业呢!