0
0
NestJSframework~8 mins

Why controllers handle incoming requests in NestJS - Performance Evidence

Choose your learning style9 modes available
Performance: Why controllers handle incoming requests
MEDIUM IMPACT
This affects how quickly the server processes and responds to user requests, impacting server response time and user experience.
Handling HTTP requests in a NestJS application
NestJS
import { Controller, Get } from '@nestjs/common';

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

  @Get()
  async getUsers() {
    // Use async non-blocking operations
    const users = await this.userService.findAll();
    return users;
  }
}
Non-blocking async code allows server to handle other requests concurrently, reducing response delays.
📈 Performance GainImproves responsiveness, reduces server blocking, better INP scores
Handling HTTP requests in a NestJS application
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  async getUsers() {
    // Heavy synchronous processing here
    for (let i = 0; i < 1e8; i++) {}
    return { message: 'Users list' };
  }
}
Blocking synchronous code in controller delays response, increasing server response time and hurting user experience.
📉 Performance CostBlocks event loop, increasing response time by hundreds of milliseconds or more
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Blocking synchronous controller codeN/A (server-side)N/AN/A[X] Bad
Asynchronous non-blocking controller codeN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Controllers receive incoming HTTP requests, process them (often asynchronously), and send responses. Efficient handling avoids blocking the event loop, allowing faster server responses.
Request Handling
Server Processing
Response Sending
⚠️ BottleneckSynchronous/blocking code in controllers delays response and blocks event loop
Core Web Vital Affected
INP
This affects how quickly the server processes and responds to user requests, impacting server response time and user experience.
Optimization Tips
1Avoid blocking synchronous code inside controllers to keep server responsive.
2Use async/await or promises for non-blocking request handling.
3Monitor server response times to detect controller bottlenecks.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of using synchronous code inside NestJS controllers?
AIt causes layout shifts in the browser
BIt blocks the event loop, delaying responses
CIt increases CSS paint time
DIt reduces bundle size
DevTools: Network panel in browser DevTools and server profiling tools
How to check: Open Network panel, observe server response times for requests handled by controllers; use server profiler to check event loop blocking
What to look for: Long server response times or blocked event loop indicate inefficient controller handling