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

推荐订阅源

WordPress大学
WordPress大学
L
LangChain Blog
D
Docker
G
Google Developers Blog
aimingoo的专栏
aimingoo的专栏
S
Secure Thoughts
AI
AI
T
The Blog of Author Tim Ferriss
月光博客
月光博客
U
Unit 42
M
MIT News - Artificial intelligence
P
Proofpoint News Feed
N
News and Events Feed by Topic
酷 壳 – CoolShell
酷 壳 – CoolShell
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
腾讯CDC
Last Week in AI
Last Week in AI
B
Blog
Stack Overflow Blog
Stack Overflow Blog
F
Full Disclosure
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
H
Hacker News: Front Page
博客园 - 叶小钗
S
SegmentFault 最新的问题
S
Security @ Cisco Blogs
H
Help Net Security
Recorded Future
Recorded Future
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
阮一峰的网络日志
阮一峰的网络日志
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
Tenable Blog
Jina AI
Jina AI
云风的 BLOG
云风的 BLOG
P
Privacy International News Feed
T
Threat Research - Cisco Blogs
Cloudbric
Cloudbric
爱范儿
爱范儿
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
O
OpenAI News
SecWiki News
SecWiki News
Latest news
Latest news
T
Tor Project blog
The Cloudflare Blog
C
Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
L
Lohrmann on Cybersecurity

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
The Jedi's Guide to Scaling Node.js APIs with Express: From Padawan to Master
Timevolt · 2026-06-19 · via DEV Community

Timevolt

The Quest Begins (The "Why")

Honestly, I still remember the first time I tried to ship a production‑ready Express API. It felt like I was Luke Skywalker staring at the Death Star plans—excited, a little terrified, and completely sure I’d missed a crucial piece of the puzzle. My endpoint worked fine on localhost:3000, but as soon as I spun up a second instance behind a load balancer, things started to glitch: sessions vanished, cache hits turned into misses, and my logs looked like a scene from Inception where everything kept folding onto itself.

The real dragon I was trying to slay? State. I’d been treating my Express app like a monolithic castle—everything lived in memory, and I assumed scaling was just “add more servers”. Spoiler: that’s not how the Force works. If you want your API to handle thousands of requests per second without turning into a chaotic lightsaber duel, you need to rethink where you keep data, how you structure middleware, and how you let each instance talk to the outside world.

That moment—when I realized my “quick fix” of shoving user sessions into an in‑memory Map was basically the same as trying to use a lightsaber to cut through a wall—was my “aha!” moment. I needed a solid foundation, and Express, despite its simplicity, can be that foundation if we wield it right.

The Revelation (The Insight)

Here’s the thing: Express itself is just a thin layer over Node’s HTTP server. Its power comes from middleware composition and router isolation. The secret to scaling isn’t cramming more logic into a single file; it’s about splitting concerns, making each piece stateless, and offloading shared state to external services (think Redis, PostgreSQL, or a managed cache).

When I started treating each route as a self‑contained mission—like a squad of Rebel pilots each with their own X‑wing—I could scale horizontally without worrying about one instance stepping on another’s toes. The revelation? Statelessness + shared external stores = linear scalability.

Think of it like The Matrix: once Neo sees the code, he can bend the rules. Once you see that your Express app shouldn’t hold onto session data or cached computations, you can let Kubernetes (or Docker Swarm, or even a simple PM2 cluster) spin up as many copies as you need, and they’ll all behave identically.

Wielding the Power (Code & Examples)

The Struggle – A Stateful Mess

Below is a snippet I actually shipped (and regretted) in my early days. It stores user sessions in an in‑memory Map and does heavy caching inside the route handler.

// server.js – THE “BEFORE” (don’t do this in prod!)
const express = require('express');
const app = express();

// 🚫 Bad: in‑memory session store – disappears on restart, not shared
const sessions = new Map();

app.use(express.json());

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  // fake DB check…
  if (username === 'admin' && password === 'secret') {
    const token = Math.random().toString(36).substr(2, 9);
    sessions.set(token, { username, expires: Date.now() + 3600000 });
    return res.json({ token });
  }
  res.status(401).json({ error: 'Invalid credentials' });
});

app.get('/profile', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  const session = sessions.get(token);
  if (!session || session.expires < Date.now()) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // 🚫 Heavy computation done on every request – not cached externally
  const userData = expensiveProfileLookup(session.username);
  res.json(userData);
});

function expensiveProfileLookup(username) {
  // Simulate a costly DB join or external API call
  return { username, role: 'admin', lastSeen: new Date() };
}

app.listen(3000, () => console.log('🚀 Server listening on 3000'));

Why this hurts scaling:

  • The sessions Map lives only in the process that created it. Add a second instance and users randomly get logged out.
  • expensiveProfileLookup runs on every request, burning CPU. If you have 10 instances, you’re doing the same work ten times.

The Victory – Stateless Routing + External Stores

Now look at the refactored version. We’ve pulled session storage out into Redis, moved heavy computation into a cached layer, and kept the Express router razor‑thin.

// server.js – THE “AFTER” (ready for horizontal scaling)
const express = require('express');
const redis   = require('redis');
const { promisify } = require('util');

const app = express();
app.use(express.json());

// 🚀 Redis client – shared across all instances
const redisClient = redis.createClient({
  host: process.env.REDIS_HOST || '127.0.0.1',
  port: process.env.REDIS_PORT || 6379,
});
redisClient.connect().catch(console.error);

// Helper to promisify Redis commands
const getAsync = promisify(redisClient.get).bind(redisClient);
const setAsync = promisify(redisClient.set).bind(redisClient);
const expireAsync = promisify(redisClient.expire).bind(redisClient);

// Middleware: validate token against Redis (stateless!)
app.use(async (req, res, next) => {
  const auth = req.headers.authorization;
  if (!auth) return res.status(401).json({ error: 'Missing token' });
  const token = auth.split(' ')[1];
  const sessionJSON = await getAsync(`sess:${token}`);
  if (!sessionJSON) return res.status(401).json({ error: 'Invalid or expired token' });

  // Attach decoded session to request for downstream handlers
  req.session = JSON.parse(sessionJSON);
  next();
});

// Login endpoint – creates a Redis‑backed session
app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  // Replace with real DB verification (bcrypt, etc.)
  if (username !== 'admin' || password !== 'secret') {
    return res.status(401).json({ error: 'Bad credentials' });
  }

  const token = Math.random().toString(36).substr(2, 9);
  const session = { username, expires: Date.now() + 3600000 };
  await setAsync(`sess:${token}`, JSON.stringify(session));
  await expireAsync(`sess:${token}`, 3600); // 1 hour TTL
  res.json({ token });
});

// Profile endpoint – fetches cached data from Redis
app.get('/profile', async (req, res) => {
  const cacheKey = `profile:${req.session.username}`;
  const cached = await getAsync(cacheKey);
  if (cached) {
    return res.json(JSON.parse(cached));
  }

  // Simulate expensive lookup – run once, then cache
  const userData = await expensiveProfileLookup(req.session.username);
  await setAsync(cacheKey, JSON.stringify(userData));
  await expireAsync(cacheKey, 300); // cache for 5 minutes
  res.json(userData);
});

async function expensiveProfileLookup(username) {
  // In a real app this could be a DB query or external API call
  // We’ll just fake a delay to show the benefit of caching
  await new Promise(r => setTimeout(r, 200));
  return { username, role: 'admin', lastSeen: new Date() };
}

// Cluster mode – let Node spawn workers equal to CPU cores
if (require('cluster').isMaster) {
  const cpuCount = require('os').cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    require('cluster').fork();
  }
  require('cluster').on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died. Forking a new one...`);
    require('cluster').fork();
  });
} else {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => console.log(`⚡ Worker ${process.pid} listening on ${PORT}`));
}

What changed and why it scales:

  1. Session store moved to Redis – every instance reads/writes the same key‑value store, so a login on one node is instantly visible to all others.
  2. Middleware validates the token – keeps route handlers clean and ensures each request is authorized without hitting a DB.
  3. Response caching in Redis – the expensive profile lookup runs only once per cache TTL, regardless of how many workers are serving traffic.
  4. Cluster mode – Node now forks a worker per CPU core, letting the OS distribute incoming connections evenly.

The best part? You can drop this code into a Docker container, push it to Kubernetes, and watch the replica set grow or shrink based on traffic—no code changes needed.

Why This New Power Matters

Armed with this pattern, you’ve turned your Express API from a fragile hut into a fortress that can weather any siege. You can now:

  • Handle traffic spikes – add more pods, and the load balancer spreads the work.
  • Deploy zero‑downtime updates – roll out a new version, kill old pods, and the external stores keep sessions and caches alive.
  • Focus on business logic – because the plumbing (session handling, caching, clustering) is encapsulated and reusable.

It’s like upgrading from a lightsaber to a blaster rifle with auto‑aim: you still need skill, but the tool does the heavy lifting for you.

And the best part? You didn’t have to abandon Express. You just gave it a proper utility belt.

Your Turn – A Mini Quest

Here’s a challenge for you: take the /profile endpoint above and add a rate‑limiting layer using Redis (think INCR with expiration). Try to block a client after 10 requests per minute, then return a 429 Too Many Requests.

When you get it working, drop a comment with your snippet or a link to a repo. I’d love to see how you’ve adapted the pattern—maybe you’ll add a feature I haven’t even thought of!

May the Force be with your APIs. Happy coding! 🚀