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

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recent Announcements
Recent Announcements
博客园 - 聂微东
B
Blog RSS Feed
人人都是产品经理
人人都是产品经理
U
Unit 42
博客园 - 三生石上(FineUI控件)
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Microsoft Azure Blog
Microsoft Azure Blog
T
Troy Hunt's Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Schneier on Security
Schneier on Security
AI
AI
T
Tailwind CSS Blog
A
About on SuperTechFans
小众软件
小众软件
云风的 BLOG
云风的 BLOG
Google Online Security Blog
Google Online Security Blog
Forbes - Security
Forbes - Security
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
Cisco Talos Blog
Cisco Talos Blog
有赞技术团队
有赞技术团队
Recorded Future
Recorded Future
MongoDB | Blog
MongoDB | Blog
B
Blog
The GitHub Blog
The GitHub Blog
IT之家
IT之家
SecWiki News
SecWiki News
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CERT Recently Published Vulnerability Notes
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Know Your Adversary
Know Your Adversary
大猫的无限游戏
大猫的无限游戏
D
Docker
I
Intezer
K
Kaspersky official blog
T
Threat Research - Cisco Blogs
PCI Perspectives
PCI Perspectives
Y
Y Combinator Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
V
Vulnerabilities – Threatpost
C
Check Point Blog
The Register - Security
The Register - Security
Scott Helme
Scott Helme
G
GRAHAM CLULEY
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org

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
CDN Cache Invalidation: Why Deleted URLs Still Redirect (And How We Fixed It)
Anand Rathna · 2026-05-20 · via DEV Community

Anand Rathnas

This article was originally published on Jo4 Blog.

You deleted the URL. Redis says it's gone. The database confirms it. But users click the link and still get redirected to the destination. cf-cache-status: HIT. Cloudflare is happily serving a cached copy that nobody told it to forget.

The Problem

We run a URL shortener behind Cloudflare CDN. For performance, we cache redirect responses at the edge with a 2-hour TTL. This means popular short URLs resolve in under 50ms globally without touching our origin.

The issue surfaced when a customer deleted a short URL and then clicked it to verify. Still working. They tried again 30 minutes later. Still working. They opened a support ticket.

Same story with URL updates. A user changed the destination from https://old-site.com to https://new-site.com. The short URL kept redirecting to the old destination. OG metadata updates had the same problem — social cards showed stale titles and images because the HTML page was cached at the edge.

Three distinct mutations, all broken:

  1. Delete URL — link stays alive via CDN cache
  2. Update URL — old destination served from CDN, old metadata in Redis
  3. Admin force-expire — neither Redis nor CDN gets invalidated

The Root Cause: Layered Caching, Partial Invalidation

Our caching architecture has two layers:

User Request → Cloudflare CDN (edge cache) → Spring Boot API → Redis (app cache) → PostgreSQL

Enter fullscreen mode Exit fullscreen mode

When a URL is deleted, the service correctly invalidated the Redis cache. But it never told Cloudflare. The CDN layer continued serving stale responses until the TTL expired naturally.

The update path was worse. UrlService.updateUrl() wrote the new destination to the database but invalidated neither Redis nor Cloudflare. Reads hit Redis first, got the old cached value, and never saw the database update.

Admin operations were the worst. AdminService.forceExpireUrl() and AdminService.deleteUrl() updated the database directly and skipped both cache layers entirely. Admin code had been written as direct repository calls, bypassing the service-layer cache invalidation that regular user operations went through.

The Fix: Purge Both Layers on Every Mutation

Step 1: Add purgeUrls() to CloudflareService

Cloudflare exposes POST /zones/{zone_id}/purge_cache with a {"files": [...]} body. We wrapped it in a service method:

@Async
public void purgeUrls(List<String> urls) {
    if (!isEnabled() || urls == null || urls.isEmpty()) {
        return;
    }

    // Cloudflare API allows max 30 URLs per purge request
    List<List<String>> batches = partition(urls, 30);
    for (List<String> batch : batches) {
        purgeUrlBatch(batch);
    }
}

private void purgeUrlBatch(List<String> urls) {
    String endpoint = CLOUDFLARE_API_BASE + "/zones/" + zoneId + "/purge_cache";
    try {
        HttpHeaders headers = createHeaders();
        Map<String, Object> body = Map.of("files", urls);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);

        ResponseEntity<CloudflareResponse> response = restTemplate.exchange(
            endpoint, HttpMethod.POST, request, CloudflareResponse.class
        );

        if (response.getBody() != null && response.getBody().isSuccess()) {
            log.info("Purged {} URL(s) from Cloudflare cache", urls.size());
        } else {
            log.warn("Cloudflare cache purge returned non-success for URLs: {}", urls);
        }
    } catch (Exception e) {
        log.warn("Failed to purge Cloudflare cache: {}", e.getMessage());
    }
}

Enter fullscreen mode Exit fullscreen mode

Two design decisions here:

@Async (fire-and-forget). CDN purge should never block the user operation. If Cloudflare is slow or down, the delete/update still completes instantly. The cache will expire naturally via TTL as a fallback.

Batched in groups of 30. Cloudflare's API limits purge requests to 30 URLs per call. A single short URL can produce up to 3 cacheable URLs (UI page, API endpoint, custom domain), so this limit matters for bulk operations.

Step 2: Build the List of Cacheable URLs

Each short URL can be cached under multiple paths. We need to purge all of them:

private void addCacheableUrls(List<String> urls, String shortUrl, String customDomain) {
    // UI page (HTML with OG tags, served via Cloudflare CDN)
    urls.add(uiHost + "/a/" + shortUrl);
    // API endpoint (JSON, also cached by Cloudflare)
    urls.add(apiHost + "/api/v1/public/a/" + shortUrl);
    // Custom domain URL (if configured)
    if (StringUtils.isNotBlank(customDomain)) {
        urls.add("https://" + customDomain + "/a/" + shortUrl);
    }
}

Enter fullscreen mode Exit fullscreen mode

For updates where the short URL or custom domain itself changed, we purge both old and new URLs:

private void purgeCloudflareCache(String shortUrl, String customDomain,
                                   String oldShortUrl, String oldCustomDomain) {
    List<String> urlsToPurge = new ArrayList<>();
    addCacheableUrls(urlsToPurge, shortUrl, customDomain);

    if (oldShortUrl != null && !oldShortUrl.equals(shortUrl)) {
        addCacheableUrls(urlsToPurge, oldShortUrl, oldCustomDomain);
    } else if (oldCustomDomain != null && !oldCustomDomain.equals(customDomain)) {
        urlsToPurge.add("https://" + oldCustomDomain + "/a/" + shortUrl);
    }

    if (!urlsToPurge.isEmpty()) {
        cloudflareService.purgeUrls(urlsToPurge);
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Wire Into Every Mutation Path

This is where the original bug lived. We had to audit every code path that mutates URL state:

UrlService (user-facing operations):

  • updateUrl() — added Redis invalidation + Cloudflare purge
  • deleteUrl() — already had Redis invalidation, added Cloudflare purge

AdminService (admin operations):

  • forceExpireUrl() — added both Redis + Cloudflare invalidation
  • deleteUrl() — added both Redis + Cloudflare invalidation
  • refreshMetadata() — added Cloudflare purge (OG tags changed)

The admin fix required a dedicated helper since admin code was calling repositories directly:

private void invalidateUrlCaches(UrlEntity url) {
    urlCacheService.invalidateCache(url.getShortUrl());

    List<String> urlsToPurge = new ArrayList<>();
    urlsToPurge.add(uiHost + "/a/" + url.getShortUrl());
    urlsToPurge.add(apiHost + "/api/v1/public/a/" + url.getShortUrl());
    if (StringUtils.isNotBlank(url.getCustomDomain())) {
        urlsToPurge.add("https://" + url.getCustomDomain() + "/a/" + url.getShortUrl());
    }
    cloudflareService.purgeUrls(urlsToPurge);
}

Enter fullscreen mode Exit fullscreen mode

One method. Both cache layers. Called from every admin mutation.

Why @Async Is the Right Call

CDN purge is a network call to Cloudflare's API. It adds 100-300ms of latency. If we made it synchronous:

  • User deletes a URL — waits an extra 200ms for Cloudflare confirmation
  • Cloudflare API is down — user's delete fails or hangs
  • Bulk operations — each URL adds another round-trip

With @Async, the user operation completes immediately. The purge runs in the background thread pool. If it fails, the cache expires naturally via TTL (2 hours max). The user never notices.

The tradeoff: there's a brief window (milliseconds to seconds) where the CDN might still serve stale content after an update. For a URL shortener, this is acceptable. For something like financial data, you'd want synchronous purge with error handling.

Lessons Learned

1. Cache invalidation has layers. If your architecture has CDN → Redis → Database, you need to invalidate from the outside in. Clearing Redis doesn't help if Cloudflare is still serving cached responses. Most requests never reach your app server when the CDN has a hit.

2. Admin code is a blind spot. Admin operations often bypass service-layer abstractions. They call repositories directly for flexibility, but that means they skip whatever cache invalidation the service layer provides. Audit every mutation path, not just the user-facing ones.

3. Fire-and-forget is correct for CDN purge. Don't block user operations on external API calls. Use @Async, log failures, and rely on TTL expiration as your safety net. The worst case is stale content for a bounded time window.

4. Enumerate all cacheable URLs. A single logical resource can exist at multiple CDN URLs. Miss one and you have a partial purge. Our short URLs have three: the UI page, the API endpoint, and the custom domain variant. All three need purging.


Ever been bitten by a stale CDN cache hiding a "deleted" resource? What's your cache invalidation strategy?

Building jo4.io - URL shortener with analytics, custom domains, and team workspaces.