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

推荐订阅源

T
Troy Hunt's Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Schneier on Security
Schneier on Security
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
Help Net Security
Help Net Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Palo Alto Networks Blog
P
Privacy International News Feed
AWS News Blog
AWS News Blog
Forbes - Security
Forbes - Security
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
A
Arctic Wolf
Hacker News: Ask HN
Hacker News: Ask HN
P
Proofpoint News Feed
N
News and Events Feed by Topic
S
Security @ Cisco Blogs
Cyberwarzone
Cyberwarzone
Google Online Security Blog
Google Online Security Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
PCI Perspectives
PCI Perspectives
Know Your Adversary
Know Your Adversary
The Hacker News
The Hacker News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Tenable Blog
S
Security Affairs
P
Privacy & Cybersecurity Law Blog
W
WeLiveSecurity
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
S
Securelist
AI
AI
Latest news
Latest news
T
The Blog of Author Tim Ferriss
Application and Cybersecurity Blog
Application and Cybersecurity Blog
C
Cybersecurity and Infrastructure Security Agency CISA
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
C
CXSECURITY Database RSS Feed - CXSecurity.com
美团技术团队
G
GRAHAM CLULEY
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
Cisco Blogs
V
Visual Studio Blog
L
LangChain 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
Feature Based Clean Architecture. Part 1: How a NestJS Application Evolves Into an Unmaintainable State
Victor Shkir · 2026-05-11 · via DEV Community

An architectural doctrine for NestJS projects: a breakdown of typical codebase degradation scenarios and the structural constraints that keep them from emerging as the feature set grows.

This article is a breakdown of how a typical NestJS backend degrades as the feature set grows, and how the ideas of Clean Architecture make it possible to avoid that. I'll walk through the full cycle: show on a "before and after" example how the feature-based structure that today is pushed as the standard loses control with scale; dissect the typical degradation scenarios; estimate in money and engineer-hours what they cost the business; explain why this kind of codebase forces teams to break monoliths into microservices long before it's justified. After that, I'll propose an approach designed against degradation — and back it with a formal mathematical argument. By the end of the article, you'll have both the reasoning and the tools to apply this approach to your own systems.

As a running example, we'll take the task that comes up on System Design interviews time and time again: a backend for a Twitter-class service. The minimal toolkit is obvious — a database and an application. Questions of peak performance, sharding, and horizontal scaling we'll deliberately set aside: this article is about code structure, not throughput. Let's fix the stack right away — Node.js and the NestJS framework. Let's start by writing out the functional requirements for the system.

  1. Sign-up and sign-in
  2. Tweet creation
  3. Feed
  4. Follows (follow / unfollow)
  5. User profile
  6. Likes
  7. Retweets
  8. Comments (replies)
  9. Search (users, tweets, hashtags)
  10. Notifications (likes, follows, replies)
  11. Media (images / videos)

Obviously the real Twitter is built an order of magnitude more complicated and was assembled over years by a team of hundreds of engineers — but the article's goal isn't to reproduce the product, it's to examine architectural evolution on a familiar problem domain. The list of features is fixed, the schema and the set of endpoints at this stage practically draw themselves, the stack is chosen. We open the NestJS documentation — and from the very first page the documentation suggests a baseline project structure.

src/
├── main.ts
├── app.module.ts
│
├── modules/
│   ├── auth/
│   ├── users/
│   ├── tweets/
│   ├── feed/
│   ├── likes/
│   ├── comments/
│   ├── retweets/
│   ├── follows/
│   ├── notifications/
│   ├── search/
│   └── media/
│
├── common/
│   ├── guards/
│   ├── interceptors/
│   ├── filters/
│   ├── decorators/
│   └── utils/
│
├── database/
│   ├── prisma/ or typeorm/
│   └── migrations/
│
├── config/
│   └── configuration.ts

Enter fullscreen mode Exit fullscreen mode

Beyond the top-level structure, the documentation also describes a recommended composition for a single module — which files and in what order it makes sense to create. This recommendation is the same for modules of different nature: auth, tweets, and search are all assembled to the same template. I'll show it on the tweets module:

src/modules/tweets/
├── tweets.module.ts
├── tweets.controller.ts
├── tweets.service.ts
├── dto/
│   └── create-tweet.dto.ts
├── entities/
│   └── tweet.entity.ts

Enter fullscreen mode Exit fullscreen mode

At first glance the layout looks tidy: clean separation, obvious rules for where things go, a low entry barrier for a new developer. In practice, though — without additional architectural discipline — within six months it turns into hard-to-maintain code. Further on we'll see exactly how: step by step, through a sequence of locally reasonable decisions. Let's start with the module that exists in nearly any product — users and authentication.

The minimal required functionality: two endpoints — sign-up and sign-in.

@Controller("auth")
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post("sign-up")
  async signUp(@Body() dto: SignUpDto): Promise<SignUpResponse> {
    return this.authService.signUp(dto.email, dto.password);
  }

  @Post("sign-in")
  async signIn(@Body() dto: SignInDto): Promise<SignInResponse> {
    return this.authService.signIn(dto.email, dto.password);
  }
}

Enter fullscreen mode Exit fullscreen mode

As the ORM throughout the article we'll use TypeORM — the choice isn't critical for the architecture conversation, and everything below transfers easily to Prisma, MikroORM, or Drizzle. We just need a tool that's convenient for showing queries. First, let's describe the user entity.

@Entity("users")
export class User {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({ unique: true })
  email: string;

  @Column()
  password: string;

  @CreateDateColumn()
  createdAt: Date;
}

Enter fullscreen mode Exit fullscreen mode

By the accepted structure, code related to working with users should live in src/modules/users. Which means the logic for creating a user record in the database formally belongs to that module too. That's already decent discipline — better than putting SQL queries directly into AuthService. But at this point the developer really has two options: hit the user repository directly from AuthService, or go through UsersService. At a small scale both options work and both pass review — so let's first look at them side by side.

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>,
  ) {}

  async signUp(email: string, password: string) {
    const existing = await this.usersRepository.findOne({
      where: { email },
    });

    if (existing) {
      throw new Error("User already exists");
    }

    const user = this.usersRepository.create({
      email,
      password,
    });

    await this.usersRepository.save(user);

    return {
      id: user.id,
      email: user.email,
    };
  }

  async signIn(email: string, password: string) {
    const user = await this.usersRepository.findOne({
      where: { email },
    });

    if (!user) {
      throw new UnauthorizedException("Invalid credentials");
    }

    if (user.password !== password) {
      throw new UnauthorizedException("Invalid credentials");
    }

    return {
      id: user.id,
      email: user.email,
    };
  }
}

Enter fullscreen mode Exit fullscreen mode

Going through the service

import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UsersService } from "../users/users.service";

@Injectable()
export class AuthService {
  constructor(private readonly usersService: UsersService) {}

  async signUp(email: string, password: string) {
    const existing = await this.usersService.findByEmail(email);

    if (existing) {
      throw new Error("User already exists");
    }

    const user = await this.usersService.create({
      email,
      password,
    });

    return {
      id: user.id,
      email: user.email,
    };
  }

  async signIn(email: string, password: string) {
    const user = await this.usersService.findByEmail(email);

    if (!user) {
      throw new UnauthorizedException("Invalid credentials");
    }

    if (user.password !== password) {
      throw new UnauthorizedException("Invalid credentials");
    }

    return {
      id: user.id,
      email: user.email,
    };
  }
}

Enter fullscreen mode Exit fullscreen mode

At the current scale both approaches look equivalent, and that is the main trap: the right choice now is determined not by how the code looks at the moment of writing, but by what will happen to it in a year. So let's fast-forward right away — imagine about a year of active development has passed. The product found its audience, the user base grew, and along with them came the people who try to abuse registration. Marketing demands tracking traffic sources and running A/B tests on users. A multi-level referral system with bonuses and limits has appeared. The users module has grown its own endpoints and new fields — in short, everything that happens in any product right when it starts bringing in money.

Let's fix exactly what list of requirements AuthService now needs to adapt to:

  1. A referral system with checks and limits: invitation caps, protection against self-referral, protection against repeated invitations of the same email
  2. A more complex sign-up with anti-abuse checks — by IP, by deviceId, by the fact of repeated registration from the same device
  3. An expanded users module — new fields (traffic source, deviceId, verification flags), separate endpoints, its own scenarios
  4. Marketing requirements — sign-up analytics, A/B tests, traffic source attribution, event export to external systems

A note on transactions. In production, sign-up requires idempotency, race protection, and careful transactional boundaries. In the article's examples, all of this is deliberately omitted — the topic is decomposition, not transactionality. And to head off the question right away: "wrap everything in one big transaction" is not the right default either. A long transactional block with calls into external analytics, bonuses, and counter recalculations would hold rows locked for seconds and crash the database under load. Correct transactional boundaries are a separate task, beyond the scope of the article.

AuthService.signUp V2

async signUp(
  email: string,
  password: string,
  referralCode?: string,
  adSourceCode?: string,
  ip?: string,
  deviceId?: string,
): Promise<SignUpResponse> {
  const existingUserByEmail = await this.usersRepository.findOne({
    where: { email },
  });
  if (existingUserByEmail) {
    throw new BadRequestException("User already exists");
  }

  const registrationsFromIp = await this.usersRepository.count({
    where: { registrationIp: ip },
  });
  if (registrationsFromIp > 5) {
    throw new BadRequestException("Too many registrations from this IP");
  }

  const existingUserByDevice = await this.usersRepository.findOne({
    where: { deviceId },
  });
  if (existingUserByDevice) {
    throw new BadRequestException("Device already used");
  }

  const adSource = adSourceCode
    ? await this.adSourceRepository.findOne({ where: { code: adSourceCode } })
    : null;
  if (adSourceCode && !adSource) {
    throw new BadRequestException("Invalid ad source");
  }

  if (adSource) {
    const experimentGroup = Math.random() > 0.5 ? "A" : "B";

    await this.adSourceRepository.increment(
      { id: adSource.id },
      "registrationsCount",
      1,
    );

    await this.analyticsRepository.save({
      type: "experiment_assignment",
      group: experimentGroup,
      source: adSource.code,
    });
  }

  const referral = referralCode
    ? await this.referralsRepository.findOne({
        where: { code: referralCode },
        relations: ["owner"],
      })
    : null;
  if (referralCode && !referral) {
    throw new BadRequestException("Invalid referral code");
  }

  const referredByUser = referral?.owner ?? null;

  if (referredByUser) {
    const referralsByOwnerCount = await this.referralsRepository.count({
      where: { owner: { id: referredByUser.id } },
    });
    if (referralsByOwnerCount > 10) {
      throw new BadRequestException("Referral limit exceeded");
    }

    const existingReferralForEmail = await this.referralsRepository.findOne({
      where: {
        owner: { id: referredByUser.id },
        invitedUser: { email },
      },
      relations: ["invitedUser"],
    });
    if (existingReferralForEmail) {
      throw new BadRequestException("Referral abuse detected");
    }

    if (referredByUser.email === email) {
      throw new BadRequestException("Self-referral not allowed");
    }
  }

  const newUser = this.usersRepository.create({
    email,
    password,
    adSource,
    registrationIp: ip,
    deviceId,
    isVerified: false,
  });
  await this.usersRepository.save(newUser);

  if (referredByUser) {
    await this.bonusRepository.save({
      userId: referredByUser.id,
      amount: 100,
      type: "referral_reward",
    });

    const parentReferral = await this.referralsRepository.findOne({
      where: { invitedUser: { id: referredByUser.id } },
      relations: ["owner"],
    });
    if (parentReferral) {
      await this.bonusRepository.save({
        userId: parentReferral.owner.id,
        amount: 50,
        type: "second_level_referral",
      });
    }

    await this.referralsRepository.save({
      owner: referredByUser,
      invitedUser: newUser,
    });
  }

  await this.analyticsRepository.save({
    type: "user_registered",
    userId: newUser.id,
    source: adSource?.code,
    ip,
  });

  return {
    id: newUser.id,
    email: newUser.email,
  };
}

Enter fullscreen mode Exit fullscreen mode

At this point a defender of code like this will say: "So what? It works, the business scenario is covered end to end, one method honestly carries the registration from start to finish." And formally that's true. But if you look at what actually lives inside signUp, the picture is different: one function now simultaneously handles authentication, anti-fraud logic, marketing experiments, the referral mechanic, and analytics. It depends on five different repositories and four independent business domains. And that — not the line count — is the real problem. One more product quarter from now, any new feature — anti-bot, geo-targeting, email verification — will be stitched into the same spot, because "all the registration requirements live in signUp."

V2 went to prod and did what V1 couldn't. The referral program started bringing in traffic cheaper than paid ads, influencers noticed and started reaching out themselves. In the product and finance dashboards, the numbers came up green in the same quarter for the first time in a long while. The project is alive, the project is growing, the project is making money.

Product catches the wave and starts pushing: "guys, the market just opened, let's go faster, the competitors aren't sleeping." At this exact moment, someone on the team catches that wave personally too. He's putting it together in his head: the feature is big, visible, right before performance review; if he ships first and bug-free — he can walk into his manager and ask for the tech-lead grade, he can start going to business meetings, become that engineer the PM goes to first to ask, and only then writes the user story. The motivation is understandable, human — not bad, not good, just real.

The next batch of "we've been meaning to" lands on the table. A partner program with bloggers and streamers. Different monetization models — revenue share, bonuses, tiers. A more serious anti-fraud, with multiple scenarios and a scoring model. Extended analytics for marketing, product, and finance. Plus additional checks and limits for the referrals. Each point on its own is normal — the same logic, just a few more scenarios.

Our hero opens auth.service.ts and figures out the fastest path — everything in one service, no unnecessary refactoring, no review arguments, ship by Friday. And it's exactly this combination — product success, PM pressure, one engineer's personal motivation, and a Friday deadline — that, time after time, produces the same class of code. If you've worked in a product that went from MVP into growth, you've seen this scene at least once. Now you'll see it again — in detail.

Before looking at what eventually ends up in auth.service.ts, let's fix what's formally on the spec at this stage:

  1. A partner program with bloggers and streamers — separate partner categories, verification, separate statuses and transitions between them
  2. An expanded monetization model — revenue share, multi-level bonuses, partnership tiers, different accrual rules for different categories
  3. A more complex anti-fraud — multiple scenarios (new user, referral, partner click), a scoring model, manual blocks
  4. Extended analytics — separate data layers for marketing, product, and finance; event export to external systems
  5. Additional checks and limits for referrals — limits by time, by user segment, by traffic source

Each item is an ordinary product request: nothing exotic, nothing architecturally provocative. And they're implemented like ordinary product requests.

AuthService.signUp V3

async signUp(
  email: string,
  password: string,
  referralCode?: string,
  adSourceCode?: string,
  ip?: string,
  deviceId?: string,
): Promise<SignUpResponse> {
  const existingUserByEmail = await this.usersRepository.findOne({
    where: { email },
  });
  if (existingUserByEmail) {
    throw new BadRequestException("User already exists");
  }

  const registrationsFromIp = await this.usersRepository.count({
    where: { registrationIp: ip },
  });
  if (registrationsFromIp > 5) {
    throw new BadRequestException("Too many registrations from this IP");
  }

  const existingUserByDevice = await this.usersRepository.findOne({
    where: { deviceId },
  });
  if (existingUserByDevice) {
    throw new BadRequestException("Device already used");
  }

  const fraudScore =
    (registrationsFromIp ?? 0) * 10 +
    (existingUserByDevice ? 50 : 0) +
    (ip?.startsWith("192.") ? 20 : 0);
  if (fraudScore > 70) {
    throw new BadRequestException("Fraud detected");
  }

  const adSource = adSourceCode
    ? await this.adSourceRepository.findOne({ where: { code: adSourceCode } })
    : null;
  if (adSourceCode && !adSource) {
    throw new BadRequestException("Invalid ad source");
  }

  if (adSource) {
    const experimentGroup = Math.random() > 0.5 ? "A" : "B";

    await this.adSourceRepository.increment(
      { id: adSource.id },
      "registrationsCount",
      1,
    );

    await this.analyticsRepository.save({
      type: "experiment_assignment",
      group: experimentGroup,
      source: adSource.code,
    });
  }

  const referral = referralCode
    ? await this.referralsRepository.findOne({
        where: { code: referralCode },
        relations: ["owner", "influencerPartner"],
      })
    : null;
  if (referralCode && !referral) {
    throw new BadRequestException("Invalid referral code");
  }

  const influencerPartner = referral?.influencerPartner ?? null;
  const referredByUser =
    referral && !influencerPartner ? referral.owner : null;

  let calculatedReward = 0;
  if (influencerPartner) {
    await this.partnerRepository.increment(
      { id: influencerPartner.id },
      "registrationsCount",
      1,
    );

    if (influencerPartner.type === "blogger") {
      const audienceSize = influencerPartner.audienceSize ?? 1000;
      const ctr = influencerPartner.ctr ?? 0.02;
      const engagementScore = audienceSize * ctr;

      calculatedReward =
        20 + engagementScore * 0.01 + (engagementScore > 1000 ? 50 : 0);

      if (engagementScore > 5000) {
        calculatedReward *= 1.5;
      }
    } else if (influencerPartner.type === "streamer") {
      const avgViewers = influencerPartner.avgViewers ?? 100;
      const streamHours = influencerPartner.streamHours ?? 2;
      const retentionFactor = Math.min(streamHours / 4, 1);

      calculatedReward =
        avgViewers * 0.5 * retentionFactor + (avgViewers > 1000 ? 100 : 0);

      if (streamHours > 6) {
        calculatedReward *= 1.2;
      }
    } else if (influencerPartner.type === "partner") {
      const revenueShare = influencerPartner.revenueShare ?? 0.1;
      const baseValue = influencerPartner.baseValue ?? 200;
      const tierMultiplier =
        influencerPartner.tier === "gold"
          ? 2
          : influencerPartner.tier === "silver"
            ? 1.5
            : 1;

      calculatedReward = baseValue * revenueShare * tierMultiplier;

      if (influencerPartner.kpiAchieved) {
        calculatedReward += 300;
      }
    }

    await this.analyticsRepository.save({
      type: "marketing_conversion",
      source: influencerPartner.type,
      reward: calculatedReward,
    });

    await this.analyticsRepository.save({
      type: "revenue_projection",
      expectedRevenue: calculatedReward * 10,
    });

    await this.analyticsRepository.save({
      type: "user_segment",
      segment:
        influencerPartner.type === "streamer" ? "gamers" : "general",
    });
  }

  if (referredByUser) {
    const referralsByOwnerCount = await this.referralsRepository.count({
      where: { owner: { id: referredByUser.id } },
    });
    if (referralsByOwnerCount > 10) {
      throw new BadRequestException("Referral limit exceeded");
    }

    const existingReferralForEmail = await this.referralsRepository.findOne({
      where: {
        owner: { id: referredByUser.id },
        invitedUser: { email },
      },
      relations: ["invitedUser"],
    });
    if (existingReferralForEmail) {
      throw new BadRequestException("Referral abuse detected");
    }

    if (referredByUser.email === email) {
      throw new BadRequestException("Self-referral not allowed");
    }
  }

  const newUser = this.usersRepository.create({
    email,
    password,
    adSource,
    registrationIp: ip,
    deviceId,
    isVerified: false,
  });
  await this.usersRepository.save(newUser);

  if (referredByUser) {
    await this.bonusRepository.save({
      userId: referredByUser.id,
      amount: 100,
      type: "referral_reward",
    });

    const parentReferral = await this.referralsRepository.findOne({
      where: { invitedUser: { id: referredByUser.id } },
      relations: ["owner"],
    });
    if (parentReferral) {
      await this.bonusRepository.save({
        userId: parentReferral.owner.id,
        amount: 50,
        type: "second_level_referral",
      });
    }

    await this.referralsRepository.save({
      owner: referredByUser,
      invitedUser: newUser,
    });
  }

  if (influencerPartner) {
    const partnerOwner = await this.usersRepository.findOne({
      where: { id: influencerPartner.ownerUserId },
    });
    if (partnerOwner) {
      await this.bonusRepository.save({
        userId: partnerOwner.id,
        amount: calculatedReward,
        type: "influencer_reward",
      });

      await this.analyticsRepository.save({
        type: "influencer_reward_paid",
        partnerId: influencerPartner.id,
        amount: calculatedReward,
      });
    }
  }

  await this.analyticsRepository.save({
    type: "user_registered",
    userId: newUser.id,
    source: adSource?.code,
    ip,
  });

  return {
    id: newUser.id,
    email: newUser.email,
  };
}

Enter fullscreen mode Exit fullscreen mode

This is a case in which no separate argument is needed to recognize the code's quality as unsatisfactory — the structural problems are visible to the naked eye. Two hundred lines in one function, six parameters at the input, three branches of referral logic, three reward models for partners; behind each conditional line is a separate business scenario, and no developer apart from the author is capable of holding all of them in their head together. It's worth emphasizing that this code deliberately omits transactionality, idempotency, invariant validation, unified error handling, and consistent response codes: their addition would make the example unreadable, and the situation only more characteristic.

At this point the reader naturally thinks: "Fine, the cause is clear — AuthService is holding the logic of several independent domains in one method. So we need to set up UsersService, ReferralsService, MarketingService, FraudService, PartnerService, and split all the signUp logic across them by the principle one service — one domain; AuthService will remain only an orchestrator." This answer is the standard NestJS-community recommendation and literally the first piece of advice on any review of code like this. It sounds right, looks right, and in the moment really does deliver visible improvement.

Only it doesn't solve the problem. And in the next part we'll walk through this kind of refactoring step by step and see why "split into services properly" isn't simply moving calls from one place to another, and why any project that has no architectural rule behind "decomposition into services" will end up, a year later, in exactly the same place — only with a different set of file names.