Bird
Raised Fist0
NestJSframework~8 mins

Why providers encapsulate business logic in NestJS - Performance Evidence

Choose your learning style10 modes available
Performance: Why providers encapsulate business logic
MEDIUM IMPACT
This affects the rendering speed and responsiveness by organizing code to minimize unnecessary computations and side effects during request handling.
Organizing business logic in a NestJS application
NestJS
import { Injectable, Controller, Get } from '@nestjs/common';

@Injectable()
export class UserService {
  getActiveUsers() {
    const users = this.fetchUsersFromDb();
    return users.filter(u => u.isActive);
  }

  private fetchUsersFromDb() {
    return [{ id: 1, isActive: true }, { id: 2, isActive: false }];
  }
}

@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get()
  getUsers() {
    return this.userService.getActiveUsers();
  }
}
Separating business logic into a provider (UserService) allows reuse, easier testing, and avoids redundant logic in controllers, improving response time and maintainability.
📈 Performance GainReduces redundant logic execution and improves code reuse, lowering CPU load and improving input responsiveness.
Organizing business logic in a NestJS application
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UserController {
  @Get()
  getUsers() {
    // Business logic directly in controller
    const users = fetchUsersFromDb();
    const filtered = users.filter(u => u.isActive);
    return filtered;
  }
}

function fetchUsersFromDb() {
  // Simulate DB fetch
  return [{ id: 1, isActive: true }, { id: 2, isActive: false }];
}
Placing business logic directly in controllers causes tight coupling and repeated logic execution on each request, increasing processing time and reducing maintainability.
📉 Performance CostTriggers repeated computations on every request, increasing CPU usage and response time.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Business logic in controllerN/AN/AN/A[X] Bad
Business logic in providerN/AN/AN/A[OK] Good
Rendering Pipeline
Encapsulating business logic in providers separates concerns, so controllers handle routing and providers handle data processing. This reduces unnecessary computations during request handling, improving responsiveness.
→JavaScript Execution
→Event Handling
⚠️ BottleneckExcessive logic in controllers causing repeated computations
Core Web Vital Affected
INP
This affects the rendering speed and responsiveness by organizing code to minimize unnecessary computations and side effects during request handling.
Optimization Tips
1Keep business logic in providers, not controllers, to avoid repeated computations.
2Use providers to organize code for reuse and easier testing.
3Reducing logic in controllers improves input responsiveness and lowers CPU load.
Performance Quiz - 3 Questions
Test your performance knowledge
Why does placing business logic directly in controllers reduce performance?
AIt reduces the number of HTTP requests
BIt improves caching automatically
CIt causes repeated logic execution on every request increasing CPU load
DIt decreases bundle size
DevTools: Performance
How to check: Record a performance profile while making requests to the API endpoints. Look for long scripting times or repeated function calls in the call tree.
What to look for: High CPU usage or repeated execution of business logic functions in controllers indicates poor separation.

Practice

(1/5)
1. Why do NestJS providers encapsulate business logic instead of placing it directly in controllers?
easy
A. To make the app run faster
B. Because controllers cannot contain any code
C. To keep the code organized and separate concerns
D. Because providers handle user interface rendering

Solution

  1. Step 1: Understand roles of controllers and providers

    Controllers handle requests and responses, while providers hold the main business rules and logic.
  2. Step 2: Recognize separation of concerns

    Separating logic into providers keeps code organized, easier to test, and reusable.
  3. Final Answer:

    To keep the code organized and separate concerns -> Option C
  4. Quick Check:

    Separation of concerns = A [OK]
Hint: Remember: providers = logic, controllers = routes [OK]
Common Mistakes:
  • Thinking controllers should hold business logic
  • Believing providers speed up app performance
  • Confusing providers with UI rendering
2. Which of the following is the correct way to define a provider class in NestJS that encapsulates business logic?
easy
A. @Injectable() export class MyService { doTask() { return 'done'; } }
B. export class MyService { constructor() {} }
C. function MyService() { return 'done'; }
D. const MyService = () => 'done';

Solution

  1. Step 1: Identify NestJS provider syntax

    Providers must be decorated with @Injectable() to be recognized by NestJS.
  2. Step 2: Check class structure

    @Injectable() export class MyService { doTask() { return 'done'; } } shows a class with @Injectable() and a method, which is correct for a provider.
  3. Final Answer:

    @Injectable() export class MyService { doTask() { return 'done'; } } -> Option A
  4. Quick Check:

    @Injectable() + class = B [OK]
Hint: Look for @Injectable() decorator on classes [OK]
Common Mistakes:
  • Omitting @Injectable() decorator
  • Using plain functions instead of classes
  • Not exporting the provider class
3. Given this provider code, what will be the output when appService.getGreeting() is called?
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getGreeting() {
    return 'Hello from provider!';
  }
}
medium
A. 'Hello from provider!'
B. undefined
C. Error: Method not found
D. 'Hello from controller!'

Solution

  1. Step 1: Analyze the getGreeting method

    The method returns the string 'Hello from provider!'.
  2. Step 2: Understand method call result

    Calling appService.getGreeting() returns the exact string defined.
  3. Final Answer:

    'Hello from provider!' -> Option A
  4. Quick Check:

    Method returns string = A [OK]
Hint: Method returns string literal, expect exact output [OK]
Common Mistakes:
  • Confusing provider output with controller output
  • Expecting undefined if method is not async
  • Assuming error without checking method existence
4. Identify the error in this provider code snippet:
@Injectable()
export class UserService {
  getUser() {
    return this.user;
  }
}
medium
A. getUser method should be async
B. Missing declaration of 'user' property
C. Missing @Controller decorator
D. UserService should not be injectable

Solution

  1. Step 1: Check class properties

    The method getUser returns this.user, but 'user' is not declared anywhere in the class.
  2. Step 2: Understand consequences

    Accessing an undeclared property will cause runtime errors or undefined returns.
  3. Final Answer:

    Missing declaration of 'user' property -> Option B
  4. Quick Check:

    Undeclared property access = C [OK]
Hint: Check if all used properties are declared in the class [OK]
Common Mistakes:
  • Thinking @Controller is needed on providers
  • Assuming async needed without async code
  • Believing providers can't be injectable
5. You want to reuse business logic for calculating discounts in multiple controllers. What is the best way to organize this in NestJS?
hard
A. Put the discount calculation code inside each controller separately
B. Use a global variable to store discount values accessible by all controllers
C. Write the discount logic directly in the main.ts bootstrap file
D. Create a provider service with discount logic and inject it where needed

Solution

  1. Step 1: Identify code reuse best practice

    Duplicating logic in controllers causes maintenance issues and breaks separation of concerns.
  2. Step 2: Use providers for shared logic

    Creating a provider service encapsulates the discount logic and allows injection into any controller.
  3. Final Answer:

    Create a provider service with discount logic and inject it where needed -> Option D
  4. Quick Check:

    Shared logic in providers = D [OK]
Hint: Use providers to share logic across controllers [OK]
Common Mistakes:
  • Duplicating logic in controllers
  • Using global variables instead of providers
  • Placing logic in bootstrap file
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard