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

推荐订阅源

Google DeepMind News
Google DeepMind News
S
Security Affairs
阮一峰的网络日志
阮一峰的网络日志
L
LangChain Blog
Microsoft Azure Blog
Microsoft Azure Blog
雷峰网
雷峰网
Recent Announcements
Recent Announcements
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
博客园_首页
The Cloudflare Blog
M
MIT News - Artificial intelligence
博客园 - 【当耐特】
MyScale Blog
MyScale Blog
S
SegmentFault 最新的问题
P
Proofpoint News Feed
Y
Y Combinator Blog
Jina AI
Jina AI
博客园 - 聂微东
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
F
Full Disclosure
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Microsoft Security Blog
Microsoft Security Blog
爱范儿
爱范儿
T
Tailwind CSS Blog
J
Java Code Geeks
Vercel News
Vercel News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Stack Overflow Blog
Stack Overflow Blog
罗磊的独立博客
小众软件
小众软件
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Blog of Author Tim Ferriss
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 三生石上(FineUI控件)
W
WeLiveSecurity
PCI Perspectives
PCI Perspectives
Attack and Defense Labs
Attack and Defense Labs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
宝玉的分享
宝玉的分享
IT之家
IT之家
Hacker News: Ask HN
Hacker News: Ask HN
The Register - Security
The Register - Security
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs

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
Pricing logic feels boring until it's wrong.
NorfolkD · 2026-05-21 · via DEV Community

Build it like infrastructure from day one.
Most pricing engines are built wrong. Here's what I'd do instead.
If you're building a CPQ product — or any SaaS tool where users configure and price deals — your pricing logic is probably living in the wrong place.
It's in a component. Or a utility function called from three different places. Or worse, duplicated between your frontend table renderer and your backend invoice service, silently drifting apart until a customer notices the numbers don't match.
I've thought a lot about how to architect this properly. Here's what I'd do.

First: treat pricing as infrastructure, not a feature
The moment you have billing frequency, line-item discounts, currency formatting, and tax rules composing together, you don't have a utility anymore. You have a domain. It deserves its own package, its own test suite, and its own ownership.
A shared @your-org/pricing-engine package — published internally, consumed by your frontend, your backend, and your export pipeline — means one place where

unitPrice × quantity × frequency = subtotal

Enter fullscreen mode Exit fullscreen mode

is defined. Not three.
Why does this matter in practice? Consider this scenario:
A sales rep quotes a client €90/month per seat for a SaaS tool, after a 10% discount, converted from USD. That number needs to be:

  • Identical in the live proposal table the rep is editing
  • Identical in the PDF the client downloads and signs
  • Identical in the invoice the billing system generates on day one
  • Identical in the revenue report the finance team pulls at month end

If your frontend, your PDF export service, and your billing backend each have their own implementation of applyDiscount() and convertCurrency(), you will eventually have a discrepancy. Not maybe. Eventually.

Never use floating-point arithmetic for money. Ever.

0.1 + 0.2 === 0.30000000000000004

Enter fullscreen mode Exit fullscreen mode

This isn't a JavaScript quirk. It's IEEE 754 — the way binary floating-point works at a hardware level. And it will silently corrupt your customer invoices.
A real example of how this surfaces: a pricing table with 7 line items, each with a percentage discount and a currency conversion applied. By the time you sum those rows, the float drift compounds. Your table shows $1,200.00. Your invoice says $1,199.99. Your customer notices. Your support team gets a ticket. Your engineers spend a day debugging something that was never going to work correctly.
Use decimal.js or equivalent to it. Treat it as a hard rule, not a code style preference. Decimal arithmetic is slower — negligibly so at any realistic pricing table scale. There is no valid argument for floating-point in customer-facing money calculations.

Keep your engine pure
A pricing engine should be a pure function:

inputs → outputs

Enter fullscreen mode Exit fullscreen mode

No Redux. No React. No HTTP calls. No side effects. Just data in, calculated data out.
What the engine looks like from the outside

const result = computeTablePricing({
  rows: [
    {
      id: "row-1",
      unitPrice: new Decimal("100.00"),
      quantity: new Decimal("5"),
      billingFrequency: "monthly",
      discount: { type: "percentage", value: new Decimal("10") }
    }
  ],
  currency: { code: "EUR", symbol: "", symbolPosition: "front", decimalPlaces: 2 },
  settings: { taxRate: new Decimal("0") }
});

// result.rows["row-1"].subtotal === Decimal("450.00")
// result.frequencyTotals.monthly === Decimal("450.00")
// result.grandTotal === Decimal("450.00")

Enter fullscreen mode Exit fullscreen mode

This matters more than it sounds. A pure engine:

Runs identically on web, server, React Native, and in a unit test
Can be validated against your old implementation in shadow mode before touching production
Can be reasoned about without understanding your component tree
Can be tested with plain input/output assertions — no mocking, no rendering, no Redux store setup

The billing frequency problem — a concrete example of why this matters
Let's say you want to add billing frequency to your pricing table. Line items can be one-time, monthly, or annual. The footer should show a subtotal per frequency group.
In a component-centric architecture, you add grouping logic to your table renderer. Then you realize your PDF export also needs frequency subtotals, so you add it there too. Then billing needs it. Three implementations. Three places to get out of sync.
With an engine, billing frequency is just a first-class input field on each row:

billingFrequency: 'one-time' | 'weekly' | 'monthly' | 'quarterly' | 'annual'

Enter fullscreen mode Exit fullscreen mode

The engine computes frequency subtotals as outputs. The table reads them. The PDF reads them. The billing service reads them. Same numbers everywhere, because it's the same function.

The discount composition problem — where things really break
Discounts are where scattered pricing logic becomes a genuine product risk.
Consider what a real CPQ discount model looks like:

A rep can apply up to 10% at line-item level without approval
Anything above 10% needs manager sign-off
There's a volume discount: 5+ seats get an additional 5% off
There's a seasonal promotion: 15% off annual plans in Q4
These can stack — but only in specific combinations

Enter fullscreen mode Exit fullscreen mode

If discount logic lives in your table component, how does your catalog apply the same rules? How does your billing service validate that the agreed discount is still applied at invoice time? How do you write a unit test for the approval threshold without rendering a table?
The answer is: you can't, cleanly. You end up with discount logic scattered across five files, each with slightly different behavior.
In an engine architecture, discount application is a shared rule:

// shared/discount-application.ts
export function applyDiscount(
  baseAmount: Decimal,
  discount: { type: 'percentage' | 'fixed'; value: Decimal }
): { discountedAmount: Decimal; discountAmount: Decimal } {
  const discountAmount =
    discount.type === 'percentage'
      ? baseAmount.mul(discount.value).div(100)
      : discount.value;

  return {
    discountedAmount: baseAmount.minus(discountAmount),
    discountAmount
  };
}

Enter fullscreen mode Exit fullscreen mode

One function. Tested once. Used by the table calculator, the catalog calculator, the billing service, and the approval workflow validator. Identical behavior everywhere by definition.

The feature composition problem — this is the real ceiling
Individual features are manageable. The problem is when they compose.
A line item that has:

Billing frequency: monthly
Discount: 10% off
Currency: EUR, converted from USD at current rate
Tax: 20% VAT applied after discount

Enter fullscreen mode Exit fullscreen mode

...needs to produce exactly the same number in your live editor, your PDF, your invoice, and your analytics pipeline. Every combination of features multiplies the number of cases where scattered logic can diverge.
This is what actually blocks CPQ roadmaps. Not any individual feature — the combinatorial explosion of feature interactions when your calculation logic is spread across the codebase.

Let your state layer stay clean
In a Redux architecture, the pattern that actually works:

Redux stores confirmed inputs only (what the user committed — prices, quantities, discounts, frequencies)
Selectors derive all calculated values by passing those inputs through the engine
Components never calculate — they only display

// selector reads inputs from Redux, derives outputs via engine
const selectTablePricingResult = createSelector(
  [selectTablePricingInputs],
  (inputs) => computeTablePricing(inputs) // pure function, memoized automatically
);

Enter fullscreen mode Exit fullscreen mode

This eliminates an entire class of bugs where your displayed subtotal disagrees with what gets saved, invoiced, or exported. The Redux store is always clean data. Derived values are never persisted. There is no ambiguity about whether a stored subtotal field is a user input or a computed value — a distinction that causes real bugs in collaborative editing and undo/redo flows.

The migration play — how to get there without breaking production
If you're refactoring an existing system rather than greenfielding, shadow mode is your best friend.
Run the new engine in parallel with your old implementation. For every calculation your old code produces, the engine produces the same calculation independently. Log any divergence. Ship zero user-facing changes until the outputs match exactly — across every row type, every discount combination, every currency, every edge case you can throw at it.
Silent arithmetic regressions on customer invoices are not a recoverable situation. Shadow mode gives you mathematical certainty before you flip the switch.
The sequencing I'd recommend:

Engine package first — pure functions, no UI changes, full test coverage
New features through the engine — billing frequency, discounts, anything net-new goes through the engine from day one, minimizing regression risk on existing behavior
Shadow mode on existing features — validate the engine matches current behavior exactly
Migrate existing consumers — replace old calculations one surface at a time, behind a feature flag
Remove the old code — only after full coverage and monitoring confirms correctness

What this unlocks long-term
Once you have a pure, shared pricing engine, a lot of things that were hard become straightforward:

Backend adoption: Your invoice service imports the same npm package your frontend uses. Calculation discrepancies between frontend and backend become structurally impossible
Mobile: React Native consumes the same engine. No separate mobile pricing logic
Analytics: Revenue reports use the same calculation rules as the proposals that generated the revenue
Formula engine: User-programmable pricing formulas

(=quantity * unitPrice * (1 - discount))

Enter fullscreen mode Exit fullscreen mode

become an extension of the engine, not a rewrite of it.

The point
Pricing logic feels boring until it's wrong. Build it like infrastructure from day one — pure, shared, tested, and decoupled from your UI layer. The payoff isn't visible immediately. It's visible when your fifth pricing feature composes correctly with your first four without a single edge case meeting.
Have you tackled pricing complexity at scale? Curious what patterns have worked — especially around currency and tax.