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

推荐订阅源

T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Register - Security
The Register - Security
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
N
Netflix TechBlog - Medium
量子位
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
H
Help Net Security
D
Docker
D
DataBreaches.Net
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
B
Blog
博客园 - 聂微东
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
The Cloudflare Blog
F
Full Disclosure
GbyAI
GbyAI
F
Fortinet All Blogs
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
小众软件
小众软件
V
Visual Studio Blog
月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
Recorded Future
Recorded Future
J
Java Code Geeks
雷峰网
雷峰网
P
Privacy & Cybersecurity Law Blog
C
Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
Webroot Blog
Webroot Blog
美团技术团队
N
News | PayPal Newsroom
G
Google Developers Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园_首页
V
Vulnerabilities – Threatpost

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
Smart Query-Aware Cache Invalidation: Solving Mongoose Performance at Scale
Victor Ajadi · 2026-06-14 · via DEV Community

The Mongoose Caching Problem (And How We Solved It)

From 300 RPS to 700+ RPS: A 2.2x Performance Breakthrough

When you're building a Node.js application with MongoDB, you quickly hit a wall: your database can't handle the query volume. You add caching. But caching is fraught with pitfalls-cache stampedes, stale data, invalidation nightmares.

We built @mongoose-performance-cache to solve this once and for all. Here's what we learned.

The Problem: Why Your Mongoose App Feels Slow

Let me paint a scenario. You have a typical SaaS API:

// User authentication - runs thousands of times
app.get('/api/user/:id', async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user);
});

// Popular reports - same query, different users
app.get('/api/reports/active', async (req, res) => {
  const reports = await Report.find({ status: 'active' });
  res.json(reports);
});

Each request hits MongoDB. At 100 concurrent users:

  • 500+ database queries per second
  • MongoDB CPU at 85%+
  • P99 latency: 500ms+
  • Users complaining: "Why is this so slow?"

You need caching. But here's where it gets tricky.

Caching is Hard (For Good Reason)

Traditional caching with Redis is deceptively simple:

// Naive caching approach
async function getActiveReports(req, res) {
  const cached = await redis.get('active_reports');
  if (cached) return res.json(JSON.parse(cached));

  const reports = await Report.find({ status: 'active' });
  await redis.set('active_reports', JSON.stringify(reports), 'EX', 300);
  res.json(reports);
}

Looks clean. But in production, it breaks in three catastrophic ways:

Problem 1: The Cache Stampede

It's 2:59:55 PM. Your cache expires in 5 seconds.

2:59:55 - 100 concurrent requests arrive
2:59:59 - Cache expires
3:00:00 - All 100 requests query MongoDB
         (not 100 queries in sequence, but 100 in parallel)
         ↓
         MongoDB CPU: 95%+, P99 Latency: 2000ms+

This is called a cache stampede or thundering herd. Your database crashes right when it matters most.

Problem 2: Invalidation Hell

You need to update a report:

// Update the report
await Report.findByIdAndUpdate(reportId, { status: 'completed' });

// Now what? The cache says it's still 'active'
// Do you clear the entire 'active_reports' cache?
// Do you clear all report caches?
// Do you manually track which queries are affected?

Most teams pick option 2: clear everything. Your hit rate plummets.

Problem 3: Concurrent Writes

Multiple requests update the same document:

Request A: Update report status → Queue update → Cache in 50ms
Request B: Update report name  → Queue update → Cache in 100ms

What gets cached? The result of B (name change), but A's status change is lost.

The Solution: Intelligent Caching

We built @mongoose-performance-cache to solve all three problems automatically.

1. Cache Stampede Protection

When multiple concurrent requests hit the same uncached query, only one database query executes. The rest share the result.

import { initCache } from '@mongoose-performance-cache';

const cache = initCache({ ttl: 600 });
cache.applyCacheToQueries(ReportSchema);

// 100 concurrent requests
const reports = await Report.find({ status: 'active' });

// Result: 1 MongoDB query, 100 shared responses
// Not 100 queries. Not throttled. Just smart.

Impact: Eliminated cache stampedes entirely. No more thundering herd.

2. Smart Query-Aware Invalidation

Here's where it gets clever:

// This query is cached
const activeReports = await Report.find({ status: 'active' });

// Update report - change the name
await Report.findByIdAndUpdate(reportId, { name: 'Q4 Report' });

// What happens to the cache?
// The system automatically determines:
// "Does 'name' appear in the query filter?"
// "No. So don't invalidate."
// ✅ Cache remains valid

// Now update the status
await Report.findByIdAndUpdate(reportId, { status: 'completed' });

// The system determines:
// "Does 'status' appear in the query filter?"
// "Yes. Invalidate this specific query."
// ✅ Only relevant queries cleared

This isn't guessing. It's pattern matching on your actual query filters.

Impact: 70% higher hit rates in write-heavy workloads. The cache stays valid longer.

3. Batch Write Optimization

Instead of flushing each cache write individually:

Traditional: 1000 writes → 1000 Redis operations → Network overhead
v1.2:        1000 writes → Batch queue → 40 Redis operations (deduped)

The library groups cache writes into 50ms batches, automatically deduplicating them. If the same key is written twice, only the latest write persists.

Impact: 60% fewer Redis operations. Smoother latency.

The Results: Benchmarks That Matter

We stress-tested this on real hardware (Lenovo 14 Ada: 2-core @ 1.2GHz, 5.88GB RAM) with a realistic workload:

v1.1 Performance (Before)
├─ Throughput: 300-350 RPS
├─ P50 Latency: ~120ms
├─ P95 Latency: ~250ms
└─ P99 Latency: ~500ms

v1.2 Performance (After)
├─ Throughput: 705-708 RPS ⬆️ 2.2x
├─ P50 Latency: ~70ms ⬆️ 42% faster
├─ P95 Latency: ~95ms ⬆️ 62% faster
└─ P99 Latency: ~150ms ⬆️ 70% faster

Test details: 50 concurrent clients, 60-second duration, 70% read / 15% write / 15% aggregate operations.

Production Grade: The Audit Story

Before shipping this, we ran a comprehensive audit across 45,534 real-world operations:

What we verified:

  • ✅ Zero data corruption (100% success rate)
  • ✅ Proper invalidation semantics (every edge case tested)
  • ✅ Memory safety under load (no OOM crashes)
  • ✅ Serialization accuracy (BSON types handled correctly)
  • ✅ Distributed cache consistency (Redis pub/sub working)

Data Integrity Score: 9.6/10

We found (and fixed) three minor issues:

  1. Size estimation was ±80% off (now ±20%)
  2. $pull operator missing type safety (now validated)
  3. Geospatial queries weren't cache-safe (now rejected)

All fixes were straightforward. No architectural flaws. No data corruption vectors.

How It Works: Just Three Lines

import { initCache } from '@mongoose-performance-cache';

// 1. Initialize once
const cache = initCache({ 
  ttl: 600,                    // 10 minutes
  enableSmartInvalidation: true // Smart invalidation
});

// 2. Apply to your schemas
cache.applyCacheToQueries(UserSchema);
cache.applyCacheToQueries(ReportSchema);
cache.applyCacheToQueries(ProjectSchema);

// 3. Use Mongoose normally
const users = await User.find({ status: 'active' });
const reports = await Report.find({ published: true });

// That's it. Caching works automatically.
// Invalidation happens automatically.
// No manual cache busting.

The Architecture: Why It's Different

Traditional caching treats the cache as a simple key-value store. We treat it as an extension of Mongoose itself.

Standard Caching:
User Logic → Cache Layer → Database
            (dumb, knows nothing about queries)

Our Approach:
User Logic → Mongoose Hooks → Smart Cache → Database
                              (knows query structure)
                              (understands invalidation)
                              (prevents stampedes)

Key innovations:

  1. Query-aware invalidation: Matches update operations against cached query filters
  2. Inflight coalescing: Shares database results across concurrent requests
  3. Batch deduplication: Groups cache writes, eliminates duplicates
  4. Memory circuit breakers: Prevents OOM by monitoring heap pressure
  5. Event loop protection: Prevents background operations from starving requests

When to Use This

Perfect for:

  • High-traffic APIs (100+ req/s)
  • Read-heavy workloads (70%+ reads)
  • Applications with repeating queries
  • Teams that want caching without the complexity

Not needed for:

  • Strongly consistent requirements (financial transactions)
  • Very low traffic (<10 req/s)
  • Queries that are always unique (no repeating patterns)

The Numbers: What You Actually Save

On a typical SaaS backend (100 concurrent users, 70% cache hit rate):

Without caching:
├─ Database queries: 3000/sec
├─ MongoDB CPU: 85%+
├─ P99 latency: 500ms
└─ Database cost: $2000/month

With @mongoose-performance-cache:
├─ Database queries: 900/sec (-70%)
├─ MongoDB CPU: 25%
├─ P99 latency: 150ms (-70%)
└─ Database cost: $400/month (-80%)

That's $19,200/year in saved database costs. Plus your users get 70% faster responses.

Why We Open Sourced This

We built this for production use. It's battle-tested on real traffic. We open sourced it because:

  1. Caching shouldn't be hard. Teams shouldn't have to solve this themselves.
  2. The problem is universal. If you use Mongoose at scale, you need this.
  3. Collaboration improves everything. We want the community to find edge cases we missed.

Getting Started

Install:

npm install @mongoose-performance-cache

Or on Bun:

bun add @mongoose-performance-cache

Full documentation: https://github.com/VictorAjadi/mongoose-cache

The Questions We Know You Have

Q: What about cache invalidation consistency across multiple servers?
A: We use Redis pub/sub for distributed invalidation. All instances sync automatically.

Q: Can I use this with existing caching middleware?
A: Yes. Our cache layer is independent. Works alongside other caching strategies.

Q: What happens if Redis goes down?
A: Automatic fallback to in-memory cache. No errors. Service continues working.

Q: Will this work with my existing MongoDB queries?
A: Yes. Zero code changes needed. Just call applyCacheToQueries(schema) once.

Q: How do I monitor cache performance?
A: Built-in stats: cache.getStats() returns hits, misses, hit rate, memory usage, etc.


What's Next

We're planning:

  • Cache analytics: Deep insights into query patterns and hit rates
  • Custom invalidation strategies: Plugin system for complex invalidation logic
  • GraphQL support: Automatic caching for GraphQL queries
  • Geospatial query support: Currently geo queries ($near, $geoIntersects) are rejected because exact coordinates make caching hard. We're exploring geohash-based caching (round coordinates to varying precision levels) and TTL stratification (shorter TTLs for precise queries).
  • Multi-database adaptation: The same patterns (stampede protection, smart invalidation, batch optimization) work for any database. Coming next:
    1. PostgreSQL (Beta Q1 2025)
    2. MySQL (Q2 2025)
    3. DynamoDB, Cassandra, SQLite (Community-driven)

Join Us

This library is open source and actively maintained. Contributions welcome:

  • Report bugs or edge cases
  • Submit feature requests
  • Share your performance results
  • Help with documentation

The Takeaway

Caching is hard. But it doesn't have to be.

With @mongoose-performance-cache, you get:

  • 2.2x faster responses
  • 70% fewer database queries
  • Zero cache invalidation complexity
  • Production-grade reliability

All with three lines of code.

Try it on your next project. Or your existing one. Let us know what you think.


Ready to make your Mongoose app faster?

npm install @mongoose-performance-cache

Happy caching! 🚀

Questions? Found a bug? Have a feature idea?
Open an issue on GitHub or reach out to us on LinkedIn.

Performance numbers based on stress testing with 50 concurrent clients on Lenovo 14 Ada (2-core @ 1.2GHz, 5.88GB RAM). Results may vary based on hardware, query complexity, and data size.