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

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 司徒正美
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
G
Google Developers Blog
T
Threat Research - Cisco Blogs
Cyberwarzone
Cyberwarzone
罗磊的独立博客
S
Security Affairs
D
Docker
Microsoft Azure Blog
Microsoft Azure Blog
G
GRAHAM CLULEY
W
WeLiveSecurity
博客园 - Franky
C
Check Point Blog
The Last Watchdog
The Last Watchdog
F
Full Disclosure
Security Latest
Security Latest
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Troy Hunt's Blog
S
Secure Thoughts
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Privacy & Cybersecurity Law Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Privacy International News Feed
S
Schneier on Security
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tenable Blog
aimingoo的专栏
aimingoo的专栏
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recent Announcements
Recent Announcements
IT之家
IT之家
D
DataBreaches.Net
U
Unit 42
博客园 - 聂微东
H
Hacker News: Front Page
GbyAI
GbyAI
T
The Exploit Database - CXSecurity.com
N
News and Events Feed by Topic
Simon Willison's Weblog
Simon Willison's Weblog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
TaoSecurity Blog
TaoSecurity Blog
Google Online Security Blog
Google Online Security Blog
T
Threatpost
博客园 - 叶小钗
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
K
Kaspersky official 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
From Cache Keys to Concurrency
Ali Agboola · 2026-06-13 · via DEV Community

The final stage of HNG is a writing task: pick two pieces of work from the internship, one solo and one team, and write about whichever ones stuck. Mine are Stage 4, an optimization pass on an API I'd already built, and Stage 6, the queue infrastructure behind a team product called Flowbrand. Neither is here because it went well. Each one cost me an assumption I didn't know I was carrying, which is a better reason to write than a clean scoreboard.

Stage 4: the difference between working and holding up

By Stage 4 I had a NestJS API sitting on db seeded with demographic profiles. Filtering, sorting, pagination, a natural-language search endpoint. All of it worked. Stage 4 then asked the question every stage before it had politely avoided: what happens when people actually use this?

Three deliverables: faster queries, consistent cache keys, and a CSV ingestion endpoint that could take files of up to 500,000 rows without flattening the server.

The slowness came first. A query like gender=male&country_id=NG&age_group=adult against a million-row Postgres table over a remote connection took about 1.6 seconds. All three columns had single-column indexes, so I assumed the database was covered. It wasn't. Postgres can't combine three separate indexes into a single lookup; it runs a bitmap scan on each one and intersects the results in memory, and at a million rows the intersection is where the time goes.

The caching problem was quieter. Redis was in place, but gender=male&country_id=NG and country_id=NG&gender=male serialized to different cache keys. Two requests asking the same question, two trips to the database.

The CSV problem was plain arithmetic. Inserting 500,000 rows one at a time is 500,000 network round trips; at 5ms each, that's about forty minutes. Buffer the whole file in memory instead and a 50MB upload becomes a 50MB heap spike, multiplied by every concurrent upload.

What I built

Composite indexes went in first because they required no application changes:

@@index([gender, country_id])
@@index([gender, age_group, country_id])

Order matters here. gender leads because it prunes the most rows at the first step, and a composite index lets Postgres walk one pre-grouped structure instead of doing three scans and stitching them together afterwards.

Then the cache keys, before touching any Redis logic. A cache that sometimes misses is a nuisance; a cache that returns results for the wrong query is a hazard, and inconsistent keys are exactly how you get there. So every filter object is normalized before anything else happens: strings lowercased, keys sorted alphabetically, numerics coerced to consistent precision, undefined fields stripped, then serialized.

function buildCacheKey(filters: ProfileQueryFilters): string {
  const normalized = normalizeFilters(filters);
  const sorted = Object.keys(normalized)
    .sort()
    .reduce((acc, key) => ({ ...acc, [key]: normalized[key] }), {});
  return `profiles:${JSON.stringify(sorted)}`;
}

The cache itself is plain cache-aside. Check Redis, return on a hit, query and store on a miss with a five-minute TTL, invalidate on writes. Five minutes because analysts repeat queries within a session, and slightly stale analytics is a trade nobody notices.

For the CSV endpoint, the file never sits in the Node heap. Multer's diskStorage writes the upload to /tmp, the service opens a readline interface over a read stream, and valid rows collect in a 1,000-row buffer that flushes through createMany with skipDuplicates: true. Each chunk commits on its own, and there is deliberately no transaction around the import. If the process dies at row 400,000, those rows stay committed, and because duplicates are skipped, re-running the same file is safe. Rolling back 400,000 good inserts because row 400,001 crashed helps nobody.

What broke

The bug that taught me the most was in my own normalization. I had put it inside buildCacheKey, which meant the cache saw normalized filters while the database received the raw ones. Same request, two different shapes. It mostly worked anyway, because Postgres happened to be case-insensitive on that column, which is the worst kind of bug: one that passes by accident. The fix was boring and correct. Normalization became the first thing findAllProfiles() does, before the cache check and before the query, so both sides see the same object.

The other adjustment was chunk size. I started flushing every 100 rows, which on a 500k file means 5,000 round trips. Too many. Moving to 1,000-row chunks cut it to 500 and kept memory per chunk reasonable.

The before and after:

Query Before After (cache miss) After (cache hit)
gender=male 820ms 310ms 12ms
gender=male&country_id=NG 1,240ms 390ms 14ms
gender=male&country_id=NG&age_group=adult 1,680ms 420ms 11ms

What stayed with me, in order of how often I've repeated it to myself since: EXPLAIN ANALYZE beats assumptions. I was sure my single-column indexes were earning their keep until the plan showed three bitmap scans and a hash join over 70,000 rows. Cache key normalization is a correctness requirement, not a performance tweak, and before this stage I had never once thought about it. And partial-failure behaviour in a bulk operation is a decision to make deliberately at design time, not something to discover during an incident.

I picked this stage because it was the first one that asked "does it hold up?" rather than "does it work?". Every earlier stage had a happy path. This one had a number: 1.6 seconds before, 11 milliseconds after. Watching that number move was the first time the work felt like engineering instead of assembly.


Stage 6: Flowbrand, queues, and the merge I'd take back

Stage 6 was the team stage. We built the backend for Flowbrand, a platform that takes an uploaded document and generates a branded marketing funnel from it. My slice was the queue infrastructure, the document upload pipeline, and the worker that actually produces the funnels. And then, late in the stage, a security audit that sent me somewhere I hadn't expected to go.

The product is asynchronous whether you like it or not. A user uploads a PDF. An LLM call extracts structured content from it. A second LLM call turns that content into a funnel schema. The assembled result lands in Postgres. Thirty seconds on a good day, with a failure possible at every step, and none of it belongs inside an HTTP request. Without a queue, Flowbrand is a timeout with a logo.

The boilerplate we inherited had no queue at all, and features were already being built against synchronous service calls the real flow would never survive. So before anything else, the team needed something to plug into.

Five PRs and an audit

PR #12 laid the foundation: Bull wired into NestJS with Redis behind it, a QueueService any module could inject to enqueue work, a base processor pattern, and a QueueModule for the rest of the team to import. The decision I'd defend hardest from that PR is typing jobs as a discriminated union — one payload shape per job type — so a processor always knows exactly what it's holding.

PR #30 came from watching the foundation misbehave under real conditions. Redis briefly unreachable during startup? Module threw. Job died with an unhandled exception? Vanished, silently. I added connection retries with graceful degradation, structured error logging at the processor level, and an event listener that records failures to the database where someone can actually see them. The question underneath all of it: who owns this failure, and what are they supposed to do with it?

PR #35 was the funnel worker: two processors, 889 lines, fifteen files. ExtractionProcessor reads the document from S3, calls the LLM, stores the structured content. FunnelGenerationProcessor takes that content, calls the LLM again with a funnel-specific prompt, and writes the assembled result inside a single QueryRunner transaction. Keep the 889 in mind. It comes back.

PR #62 was the upload pipeline — and where the real edge-case work happened. Flowbrand accepts PDFs, Word files, PowerPoints. Each one needs to be validated, streamed to MinIO, queued for text extraction, and tracked via a polling endpoint so the frontend knows what's happening. The uploaded_documents table, a status enum (UPLOADING, PARSING, COMPLETED, FAILED), and a failure_reason column all went in first. Then the storage service, then the extraction processor.

The happy path worked within a day. Two things then broke it.

The first was the upload itself. The initial version used NestJS's default FileInterceptor, which buffers the whole file to disk before you touch it. Fine at 2MB. A 25MB PowerPoint stalled the server. The fix was switching to memoryStorage: false in Multer config and piping createReadStream(file.path) directly into the MinIO upload call — the file never fully lives in memory.

The second was a retry idempotency problem I hadn't thought through. Bull retries failed jobs automatically. If ExtractionProcessor crashed after writing 40% progress to the database but before marking the job complete, the retry would pick up the same job and try to reset progress to 0 — which made no sense, and in some cases hit a unique constraint violation. The fix was an orphan guard at the top of the processor: read the current DB record first. If status is COMPLETED, skip. If status is FAILED, re-run from the top. If percent_complete > 0 and status is PARSING, we're resuming — don't reset. A Bull job is not a function call. It can run more than once, on a different process, with the same inputs. If your processor has side effects — and writing to MinIO and updating a DB row definitely are — you need to be able to answer: what happens if this runs twice?

PR #102 wrapped every controller response in a consistent { status: "success", data: ... } envelope. Not glamorous. The frontend was blocked on it.

PR #166 came from a code audit, and it was the most uncomfortable work I did in Stage 6. Three concurrency bugs in the authentication service, all security-relevant, all in code that had passing tests.

The first: two simultaneous first-time logins from the same user both read auth_metadata = null, both tried to create the row, and one crashed on a unique constraint. Fix: catch Postgres error code 23505 and re-read the row the concurrent request already created. The second requester gets a valid result without knowing a race happened.

The second was worse. The account lockout counter used a JavaScript read-modify-write pattern: read failed_attempts, add 1, write it back. Under concurrent wrong-password attempts, two requests could read the same value, both add 1, both write the same number. The counter could only go up by 1 even if five requests hit simultaneously. A brute-force attack could exhaust attempts without ever triggering the lock. The fix was deleting the read-modify-write entirely and replacing it with a single repository.increment() call — one SQL statement, UPDATE auth_metadata SET failed_attempts = failed_attempts + 1 WHERE id = $1. The database handles the concurrency; there is no window between read and write for another request to interfere.

The third: the distributed lock on OTP verification had a 10-second TTL, chosen arbitrarily. A slow DB response under load could let the lock expire before the handler finished, allowing two concurrent OTP submissions to both succeed for the same token. Fix: raise the TTL to 30 seconds.

The increment() fix introduced a subtle problem I missed on first pass. The method had been returning the updated metadata object, which the caller used to decide whether to trigger lockout. increment() doesn't give you the row back. My first version re-fetched it — two DB round trips per failed login. I looked at what the caller actually needed: just the new count. So the method now returns the old value plus one, calculated locally, and only hits the database again when it needs to write locked_until. One write per failed attempt, no superfluous read.

These three bugs existed in code with passing tests. The tests ran one request at a time. That's the lesson from PR #166: concurrency bugs are invisible in unit tests unless you specifically design the test to expose them. And the fix for bug 2 is less about adding code than removing it — moving the operation to where it belongs, which is the database, not JavaScript.

What I keep

The queue left me with a clean model for failure ownership, because the two processors handle it opposite ways and both are right. ExtractionProcessor swallows exceptions and records them to the database: an extraction failure is specific to that document, and retrying the same broken content against the same call doesn't change anything. FunnelGenerationProcessor rethrows: its failures are usually transient, rate limits and timeouts, and Bull's retry machinery exists for exactly that case.

And then PR #35. 889 lines across fifteen files is at least three concerns in one diff, and I knew that when I opened it. The deadline was real. I merged. My lowest score in Stage 6 was Collaboration + Docs — 6 out of 10 — and it was earned. Reviewers can only review what they can read. The question I now ask before opening anything: what's the smallest piece of this that someone could review on its own?

I picked Stage 6 because it's where the internship stopped being coursework. In the solo stages, reviewability is theoretical; the reviewer is a grading script. In Stage 6, a real teammate is blocked until your work makes sense to them. PR #35 put the tradeoff in front of me plainly. I chose to ship the whole feature. The score put a number on what that cost. I don't plan to pay it twice.


Ali . HNG XIV Backend Track.
Portfolio: sage-ali.vercel.app · GitHub: github.com/sage-ali