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

推荐订阅源

宝玉的分享
宝玉的分享
L
LINUX DO - 最新话题
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
雷峰网
雷峰网
Apple Machine Learning Research
Apple Machine Learning Research
V
Visual Studio Blog
Attack and Defense Labs
Attack and Defense Labs
O
OpenAI News
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
B
Blog RSS Feed
H
Help Net Security
量子位
小众软件
小众软件
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
TaoSecurity Blog
TaoSecurity Blog
美团技术团队
博客园 - 司徒正美
Hacker News - Newest:
Hacker News - Newest: "LLM"
Recent Commits to openclaw:main
Recent Commits to openclaw:main
The Cloudflare Blog
N
News and Events Feed by Topic
C
Cybersecurity and Infrastructure Security Agency CISA
The Last Watchdog
The Last Watchdog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Scott Helme
Scott Helme
T
The Exploit Database - CXSecurity.com
K
Kaspersky official blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
Application and Cybersecurity Blog
Application and Cybersecurity Blog
U
Unit 42
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
Schneier on Security
Schneier on Security
G
Google Developers Blog
Forbes - Security
Forbes - Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Y
Y Combinator Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Palo Alto Networks Blog
A
Arctic Wolf
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
The Hacker News
The Hacker News
B
Blog
D
DataBreaches.Net
Simon Willison's Weblog
Simon Willison's Weblog

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
Custom behavior without custom code
Ian Johnson · 2026-05-19 · via DEV Community

Every successful SaaS product eventually meets the same question: a customer asks for something specific to them, you build it, and now you have a feature in your codebase that's only meant to run for one tenant. A year later, you have a dozen of these. The codebase has if-statements checking tenant IDs, the test suite mocks out customer-specific paths, and the senior engineer who knows which branch belongs to which customer is the only person who can refactor anything.

There's a better shape, and it doesn't require giving up the per-customer customization. It does require separating, cleanly and firmly, the code that defines what behaviors are possible from the data that selects and parameterizes them. This article is about how to do that, where to store the data, and the security cliff you'll fall off if you let the data become code.

What not to do

A handful of approaches show up over and over, and each has a fatal flaw:

  • Separate deployed instances per customer. This solves customization by forking the operational surface. Now you have N versions of the database, N sets of background jobs, N deploy pipelines, N versions of every bug fix to roll out. It works for two or three customers and collapses by ten.
  • Conditional code in the backendif tenant_id == "acme": .... Cheap on day one, untenable by month six. Every developer has to know the customer landscape to make changes safely. Every refactor is risky in proportion to how many tenants have branches. Customer-specific logic spreads across the codebase by capillary action.
  • Code injected at build time. A configuration that produces a different binary per tenant. Has the same operational cost as separate instances, plus the added joy of debugging behavior that depends on what compile-time flag was set. Don't.

The pattern that scales is to keep one codebase, one running cluster, one deploy pipeline — and to let per-tenant behavior live in data that the code consults. Basically, I am describing multi-tenancy.

Code defines the possibilities; data selects among them

Identify the points in your system where behavior can vary per tenant. These are extension points: the discount engine, the approval workflow, the export format, the notification rules. At each one, your code defines a small set of behaviors it knows how to perform. Per-tenant data picks which behaviors to use and supplies the parameters.

Concretely: a class hierarchy. A common shape is a CustomRule base class with a contract — say, applies?(context) and apply(context) — and a set of concrete implementations:

class CustomRule:
    def applies(self, context) -> bool: ...
    def apply(self, context) -> None: ...

class PercentageDiscountRule(CustomRule):
    def __init__(self, percent, min_order):
        self.percent = percent
        self.min_order = min_order

    def applies(self, context):
        return context.order_total >= self.min_order

    def apply(self, context):
        context.discount += context.order_total * (self.percent / 100)

class FirstPurchaseDiscountRule(CustomRule):
    def __init__(self, amount):
        self.amount = amount

    def applies(self, context):
        return context.customer.order_count == 0

    def apply(self, context):
        context.discount += self.amount

Enter fullscreen mode Exit fullscreen mode

A tenant's configuration is then a small declarative description — which rules they have, with what parameters:

{
  "discount_rules": [
    {"type": "percentage", "percent": 10, "min_order": 100},
    {"type": "first_purchase", "amount": 5}
  ]
}

Enter fullscreen mode Exit fullscreen mode

At runtime, you load the tenant's config, hydrate it into instances of the right rule classes, and run them. The code knows how to perform every behavior; the data says which behaviors to apply, in what order, with what parameters. To add a new kind of rule, you add a new class. To add a new tenant configuration, you change data — no deploy, no migration, no engineering.

Notice that the apply methods mutate the incoming value. If you prefer to not do so, just return that result and apply it when called. A reasonable name for this operation is result. This is really up to your preference in terms of using mutable vs immutable data. In the context of a web app, you usually do want mutability (for example, encoding and decoding a value from the database to a particular meaning for a tenant). If there is more complexity, you can put it behind a port to unit test it separately.

The shape generalizes: any extension point in your system can have its own base class, its own family of implementations, and its own data schema describing how it's configured per tenant.

Where the data lives

The configuration has to be persisted somewhere. The options aren't equivalent:

  • In-memory cache. Tempting because it's fast, but caches get invalidated, evicted, and reset on deploy. If the cache is the source of truth, you've lost the data the moment something restarts. Caches belong in front of the source of truth, not in place of it.
  • Files on disk. Workable for very small, very stable configurations, but file I/O is slow at scale, file deployment is operational overhead, and "edit a file and redeploy" doesn't fit the case where customer success needs to toggle something for a tenant at 4pm on a Friday.
  • Static configuration baked into the app. Fine for values that genuinely never change between deploys. But if the values are tenant-specific, you're back to the "code per customer" problem.
  • A database. If you're already running one — and you almost certainly are — this is the clear winner. Reads are fast (especially with a thin cache in front), updates are transactional, the data sits next to the tenant records it's associated with, and you get backups, replication, and access control for free.

Use the database you already have. Don't introduce a new piece of infrastructure for this.

A note on schema

Whichever shape you pick, the configuration has to be retrievable by tenant. That means a tenant_id foreign key, typically a dedicated tenant_configurations table with tenant_id referencing tenants, indexed for fast lookup. The runtime question is always the same: "given the tenant for this request, what's their configuration?" Get that relationship in place first; everything else flows from being able to find the right rules for the right tenant.

If you're using a relational database, the principled approach beyond that is to model the configuration with normalized tables — a tenant_discount_rules table with tenant_id, typed columns for rule type, percent, min_order, and so on, or a polymorphic schema with a separate table per rule type. This is fine, and you may end up there. But I'd push back on starting there.

For an initial proof of concept, a single table is enough:

CREATE TABLE tenant_configurations (
  tenant_id   BIGINT PRIMARY KEY REFERENCES tenants(id),
  config      JSONB  NOT NULL DEFAULT '{}'::jsonb,
  updated_at  TIMESTAMP NOT NULL DEFAULT NOW()
);

Enter fullscreen mode Exit fullscreen mode

One row per tenant, the primary key handles the lookup index, no migrations needed when you add a new kind of rule. You fetch the row by tenant_id, parse the config JSON, hydrate it into your rule classes, run them. When the configuration stabilizes, when querying into the configuration becomes important, or when validation needs to live at the database level, that's the moment to normalize. Until then, JSON in a column is the shortest path from idea to working code, and you can refactor toward structure once you know what the structure should be.

The security cliff

There is one thing you must not do, no matter how convenient it looks: do not store executable code in the configuration, and do not let configuration values be interpreted and run.

That means no eval, no exec, no embedded JavaScript or Python or Ruby expressions, no SQL fragments concatenated into queries, no template engines that allow arbitrary function calls. It is tempting (really tempting) to support a configuration that looks like:

{
  "discount_amount": "order.total * 0.1 if customer.tier == 'gold' else 0"
}

Enter fullscreen mode Exit fullscreen mode

…and eval that string at runtime. Do not. The moment you do, anyone who can write to that configuration row can execute arbitrary code on your servers, with the privileges of your application. That's not a feature; that's a remote code execution vulnerability you built on purpose. It doesn't matter that the configuration is "only" editable by admins, or "only" through your UI — the surface area expands the moment another bug exposes that table, the moment a credential leaks, the moment an internal account is phished. The configuration becomes the attacker's payload delivery mechanism, and you handed them the loaded gun.

The correct discipline is strict: configuration is data. It selects between behaviors the code already knows how to perform and supplies typed parameters to them. It never describes a new behavior. If a customer needs a behavior the code doesn't have, the answer is to add a new rule class, not to let them write logic into a JSON blob.

This is also what makes the system safe to expose to customer-success people, support engineers, and eventually self-service customers. The blast radius of a misconfigured rule is "the rule doesn't apply" or "the rule applies wrong". Never "the server runs whatever I told it to."

The shape, summarized

  • Identify per-tenant extension points and write a small base class for each.
  • Implement the concrete behaviors as subclasses of that base.
  • Store tenant configurations as data; start with a JSON column on the tenant record, normalize later if it earns it.
  • Hydrate the data into classes at runtime; let the classes do the work.
  • Never, ever let the data become code.

The principle underneath all of this is that code is the menu (the list of things your system is capable of doing) and data is the order. Customers can pick from the menu, in any combination, with any parameters. They cannot rewrite the menu. The chef writes the menu. That's how you keep the kitchen safe.