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

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿
H
Help Net Security
Last Week in AI
Last Week in AI
The Cloudflare Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
B
Blog
C
Check Point Blog
T
Tailwind CSS Blog
云风的 BLOG
云风的 BLOG
D
Docker
Recent Announcements
Recent Announcements
Vercel News
Vercel News
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale Blog
The GitHub Blog
The GitHub Blog
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
月光博客
月光博客
F
Fortinet All Blogs
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
The Register - Security
The Register - Security
V
Visual Studio Blog
F
Full Disclosure
Hugging Face - Blog
Hugging Face - Blog
T
Threat Research - Cisco Blogs
Latest news
Latest news
PCI Perspectives
PCI Perspectives
Cisco Talos Blog
Cisco Talos Blog
博客园 - Franky
D
DataBreaches.Net
A
Arctic Wolf
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
Google Developers Blog
P
Palo Alto Networks Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
T
Tenable Blog
L
LINUX DO - 热门话题
Spread Privacy
Spread Privacy

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
CQRS Is Almost Always Wrong. Here Are the 4 Cases Where It's Actually Right.
Gabriel Anha · 2026-04-26 · via DEV Community

You opened a pull request that splits your Order entity into OrderWriteModel and OrderReadModel. The reviewer asks why. You answer: "CQRS." The reviewer asks why again, and this time the answer takes 40 minutes, three Miro diagrams, and an apology to the standup that started without you.

You have probably seen the version that goes wrong. A team ships CQRS into a 12-table CRUD app because someone read about it. Eighteen months later they have two databases that disagree, a projection rebuild script nobody trusts, and a "consistency dashboard" with three orange tiles that have been orange since launch. The system works. It works the same way the pre-CQRS version worked, except now there are two of everything.

Greg Young (who coined the term in 2010) was clear from the start: CQRS is a pattern, not an architecture. Martin Fowler puts it more bluntly on his bliki: "for most systems CQRS adds risky complexity." Chris Richardson lists CQRS under the data-management patterns on microservices.io precisely because the problem it solves only appears once you have multiple services and multiple databases.

Most apps are not those apps. Read and write in the same model. Use a normal repository. Ship.

Here are the four cases where CQRS actually earns the cost.

Case 1: read scale dwarfs write scale by 2+ orders of magnitude

The textbook scenario. Picture a pricing service that writes 50 updates per minute and serves 800,000 reads per minute, or a product catalog that edits 200 items a day and is queried 10 million times. Those are illustrative thresholds, not measured benchmarks. The shape is asymmetric, and you cannot index your way out of it because the indexes themselves contend with writes.

CQRS lets you scale the read side independently. The write model lives behind your normal transactional database, sized for writes. The read model is a denormalized projection: Redis, Elasticsearch, or a separate Postgres replica with materialized views. Size it for reads, and replicate it wherever your traffic lives.

# Write side — small, normalized, transactional.
class PricingCommandHandler:
    def __init__(self, db, events):
        self.db = db
        self.events = events

    def update_price(self, sku: str, price: Decimal) -> None:
        with self.db.transaction() as tx:
            tx.execute(
                "UPDATE prices SET amount = %s WHERE sku = %s",
                (price, sku),
            )
            self.events.publish(
                PriceUpdated(sku=sku, amount=price, ts=now()),
            )

Enter fullscreen mode Exit fullscreen mode

# Read side — denormalized projection, eventually consistent.
class PriceProjection:
    def __init__(self, redis):
        self.redis = redis

    def on_price_updated(self, e: PriceUpdated) -> None:
        self.redis.set(
            f"price:{e.sku}",
            json.dumps({"amount": str(e.amount), "ts": e.ts}),
        )

    def get(self, sku: str) -> dict | None:
        raw = self.redis.get(f"price:{sku}")
        return json.loads(raw) if raw else None

Enter fullscreen mode Exit fullscreen mode

The write side stays small and correct. The read side stays fast and disposable. If your read traffic is 10× write traffic, do not do this. Add a replica and an index. My rule of thumb is two orders of magnitude. Treat that as an illustrative threshold, not a benchmark, and only at that point does the projection earn its operational tax.

Case 2: reads have different consistency requirements

A trading platform shows you your portfolio balance on the dashboard and the same balance on the trade-confirmation screen. The dashboard can be 200ms stale. The confirmation screen cannot — it has to reflect the order you just placed.

A single model forces you to pick one consistency level for both. Either the dashboard reads through the slow path that confirmation needs, or the confirmation screen reads through the fast path that the dashboard tolerates and gets a stale balance at the worst possible moment.

CQRS lets you serve each read with its own model. Strong-consistency reads hit the write store directly (read-your-writes within the aggregate). Eventually-consistent reads hit a projection optimized for the query — pre-joined, pre-aggregated, pre-paginated.

class PortfolioReads:
    def __init__(self, write_db, read_store):
        self.write_db = write_db   # source of truth
        self.read_store = read_store  # projection

    def balance_for_confirmation(self, account_id: str) -> Decimal:
        # Strong: read through the write model.
        row = self.write_db.fetchone(
            "SELECT balance FROM accounts WHERE id = %s",
            (account_id,),
        )
        return row["balance"]

    def balance_for_dashboard(self, account_id: str) -> Decimal:
        # Eventual: pre-aggregated projection, fast.
        return self.read_store.get_balance(account_id)

Enter fullscreen mode Exit fullscreen mode

The two methods are honest about what they offer. The dashboard does not pay for strong consistency it does not need. The confirmation screen does not get fooled by a stale projection.

Case 3: queries cross aggregate or service boundaries

Once you split a system into services with database-per-service, joining across services becomes a runtime problem instead of a JOIN. "Show me all orders by customers in the EU placed in the last hour" now spans three services, and there is no SQL planner to help you.

You can answer this with API composition (call all three services, join in the app) or with CQRS — a read-side projection that subscribes to the events from each service and maintains a denormalized view shaped exactly for the query.

# Subscribes to OrderPlaced, CustomerUpdated, RegionAssigned.
class EuOrdersProjection:
    def __init__(self, read_db):
        self.read_db = read_db

    def on_order_placed(self, e: OrderPlaced) -> None:
        cust = self.read_db.get_customer(e.customer_id)
        if not cust or cust["region"] != "EU":
            return
        self.read_db.insert_order_view({
            "order_id": e.order_id,
            "customer_id": e.customer_id,
            "region": cust["region"],
            "amount": e.amount,
            "placed_at": e.ts,
        })

    def on_customer_region_changed(self, e: RegionChanged) -> None:
        self.read_db.update_orders_for_customer(
            e.customer_id, region=e.region,
        )

Enter fullscreen mode Exit fullscreen mode

This is the case where CQRS pays for itself fastest in microservice systems. The projection is a small focused service. The query goes from "fan out three calls and merge in app code" to "one indexed read." API composition stops scaling somewhere around a handful of participating services and a few hundred queries per second. Take that as an illustrative ceiling, not a hard one; your mileage will depend on payload size and tail latency.

Case 4: audit and temporal queries demand event sourcing

If your business requires answers to "what did we know at 14:32 on Tuesday" (regulated finance, healthcare, anything where an auditor will ask later), you end up at event sourcing. The append-only log of events becomes the source of truth. The current state of any aggregate is a fold over its events.

Event sourcing without CQRS is technically possible and practically miserable. Querying "all orders over $1k from EU customers" by replaying every order event is not a query, it is a batch job. So you build a read model. At which point you are doing CQRS, whether you call it that or not.

class OrderEventStore:
    def append(self, stream_id: str, events: list[Event]) -> None:
        with self.db.transaction() as tx:
            for e in events:
                tx.execute(
                    "INSERT INTO events (stream, type, payload, ts)"
                    " VALUES (%s, %s, %s, %s)",
                    (stream_id, e.type, json.dumps(e.data), e.ts),
                )
                self.bus.publish(e)

    def load(self, stream_id: str) -> list[Event]:
        rows = self.db.fetchall(
            "SELECT type, payload, ts FROM events"
            " WHERE stream = %s ORDER BY ts",
            (stream_id,),
        )
        return [Event.from_row(r) for r in rows]

Enter fullscreen mode Exit fullscreen mode

class OrderSearchProjection:
    """Denormalized table for analyst queries."""
    def on_order_placed(self, e: OrderPlaced) -> None:
        self.db.execute(
            "INSERT INTO orders_search "
            "(order_id, customer_id, total, region, placed_at) "
            "VALUES (%s, %s, %s, %s, %s)",
            (e.order_id, e.customer_id, e.total,
             e.region, e.ts),
        )

Enter fullscreen mode Exit fullscreen mode

The event store answers "what happened, in order." The projection answers "what is the current shape." If you do not need temporal queries (most systems do not), do not start here.

The bill comes due

Pick CQRS for the right reason and you still pay. Two models means two schemas to evolve, two stores to back up, two failure modes during deploys. Eventual consistency means the user who just hit "save" can refresh and not see their change for an illustrative 80ms of replication lag. That sounds fine until your support inbox tells you it does not.

The big one is projection rebuilds. The first time you change the shape of a read model, you have to rebuild it from the source. If your write store is the source, that is a long-running migration. If your event store is the source, it is a long-running replay. Either way the rebuild script becomes a load-bearing piece of code that nobody wants to own. Plan for it on day one or it will plan for you on day three hundred.

Other costs that show up later: idempotent event handlers (the bus will redeliver), out-of-order events (timestamps lie), schema versioning on events (you will edit a payload and break a five-month-old projection). None of this is unsolvable. All of it is work you would not be doing if read and write shared a model.

The default position

A CRUD app is not a CQRS app. A small service with a normal request/response API is not a CQRS app. A microservice that owns its own data and serves a handful of queries is not a CQRS app. Most of what gets called "CQRS" in code reviews is just command-query separation (the much older idea that methods either change state or return data, never both), which costs nothing and is good practice everywhere.

CQRS, the architecture, is the version with two models, two stores, and an eventual-consistency window between them. Reach for it later than you think. The complexity is real. The cases above are when it pays back.

If you find yourself reaching for CQRS because the architecture diagram looks more impressive with two boxes, close the laptop. Go for a walk. Come back and add an index.


If this was useful

The Event-Driven Architecture Pocket Guide walks through CQRS, sagas, the outbox pattern, and the failure modes that show up six months in — projection rebuilds, out-of-order events, the consistency-window bugs that only the support team sees. If you are evaluating whether to split read and write, it is the chapter-by-chapter version of this post.

Event-Driven Architecture Pocket Guide