Bird
Raised Fist0
Expressframework~10 mins

Performance monitoring basics in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Performance monitoring basics
Start Application
↓
Collect Metrics
↓
Analyze Metrics
↓
Detect Performance Issues
↓
Alert or Log
↓
Optimize Application
↩Back to Collect Metrics
This flow shows how performance monitoring collects data, analyzes it, detects issues, alerts, and helps optimize the app continuously.
Execution Sample
Express
const express = require('express');
const app = express();
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    console.log(`Request took ${Date.now() - start} ms`);
  });
  next();
});
This code measures how long each HTTP request takes and logs the duration.
Execution Table
StepActionTimestamp Start (ms)Timestamp End (ms)Duration (ms)Output
1Request received1000
2Middleware start timer1000
3Request processing1000
4Response finish event triggered102525Request took 25 ms
5Log outputRequest took 25 ms
6Next middleware or route handler
💡 Request processing finished, duration logged, middleware passed control forward
Variable Tracker
VariableStartAfter Step 2After Step 4Final
startundefined100010001000
Durationundefinedundefined2525
Key Moments - 2 Insights
Why do we use 'res.on("finish")' instead of logging immediately after 'Date.now() - start'?
Because the response finishes asynchronously, logging inside 'res.on("finish")' ensures we measure the full request time, as shown in execution_table step 4.
What does 'next()' do in the middleware?
'next()' passes control to the next middleware or route handler, allowing the request to continue processing, as seen in execution_table step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the duration of the request at step 4?
A25 ms
B1000 ms
C1025 ms
D0 ms
💡 Hint
Check the 'Duration (ms)' column at step 4 in the execution_table.
At which step does the middleware start the timer?
AStep 1
BStep 4
CStep 2
DStep 6
💡 Hint
Look at the 'Action' column in execution_table for when the timer starts.
If we remove 'next()', what happens to the request flow?
ADuration logs twice
BRequest processing stops after middleware
CRequest continues normally
DResponse never finishes
💡 Hint
Refer to key_moments about the role of 'next()' and execution_table step 6.
Concept Snapshot
Performance monitoring basics in Express:
- Use middleware to measure request time
- Start timer at request start
- Use 'res.on("finish")' to detect response end
- Log or send metrics for analysis
- Use 'next()' to continue request flow
Full Transcript
Performance monitoring in Express involves adding middleware that records the time when a request starts and listens for the response to finish. When the response finishes, it calculates the total time taken and logs it. This helps detect slow requests. The middleware uses 'next()' to pass control to the next handler so the request can be processed fully. This cycle repeats for every request, enabling continuous monitoring and optimization.

Practice

(1/5)
1. What is the main purpose of performance monitoring in an Express app?
easy
A. To measure how fast the app responds to requests
B. To add new features to the app
C. To change the app's user interface
D. To store user data securely

Solution

  1. Step 1: Understand performance monitoring

    Performance monitoring tracks how quickly the app handles requests.
  2. Step 2: Identify the main goal

    The goal is to find slow parts and improve speed, not to add features or change UI.
  3. Final Answer:

    To measure how fast the app responds to requests -> Option A
  4. Quick Check:

    Performance monitoring = measure response speed [OK]
Hint: Performance monitoring = measuring app speed [OK]
Common Mistakes:
  • Confusing performance monitoring with adding features
  • Thinking it changes the user interface
  • Assuming it stores user data
2. Which Express middleware code snippet correctly measures request duration?
easy
A. app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { console.log(Date.now() - start); }); next(); });
B. app.use((req, res, next) => { const start = Date.now(); next(); console.log(Date.now() - start); });
C. app.use((req, res) => { console.log('Request received'); });
D. app.use((req, res, next) => { console.log('Start'); next(); console.log('End'); });

Solution

  1. Step 1: Check middleware timing logic

    app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { console.log(Date.now() - start); }); next(); }); starts timer, waits for response finish event, then logs duration correctly.
  2. Step 2: Compare other options

    app.use((req, res, next) => { const start = Date.now(); next(); console.log(Date.now() - start); }); logs too early before response ends. Another option lacks next() call. The remaining option logs 'Start' and 'End' immediately, not duration.
  3. Final Answer:

    app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { console.log(Date.now() - start); }); next(); }); -> Option A
  4. Quick Check:

    Use 'res.on("finish")' to measure full request time [OK]
Hint: Use 'res.on("finish")' event to log after response ends [OK]
Common Mistakes:
  • Logging time before response finishes
  • Forgetting to call next() in middleware
  • Not using response events to measure duration
3. Given this middleware, what will be logged when a request takes 150ms?
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    console.log(`Response time: ${Date.now() - start}ms`);
  });
  next();
});
medium
A. No output logged
B. Response time: 0ms
C. Response time: NaN
D. Response time: 150ms

Solution

  1. Step 1: Understand timer start and finish

    The timer starts at request start and logs when response finishes, so it measures full duration.
  2. Step 2: Calculate logged time

    If request takes 150ms, logged time is approximately 150ms.
  3. Final Answer:

    Response time: 150ms -> Option D
  4. Quick Check:

    Timer logs actual elapsed time on 'finish' event [OK]
Hint: Logs time difference on response finish event [OK]
Common Mistakes:
  • Assuming log happens immediately (0ms)
  • Confusing timer start and end
  • Expecting no output without console.log
4. Why does this middleware fail to log correct response time?
app.use((req, res, next) => {
  const start = Date.now();
  console.log(Date.now() - start);
  next();
});
medium
A. It logs after response ends, so time is too long
B. It logs before response finishes, so time is near zero
C. It uses wrong event to measure time
D. It does not call next(), so request hangs

Solution

  1. Step 1: Analyze when logging happens

    Logging happens immediately after start, before response finishes, so duration is near zero.
  2. Step 2: Check middleware flow

    next() is called, so request continues; no wrong event used; logging is too early.
  3. Final Answer:

    It logs before response finishes, so time is near zero -> Option B
  4. Quick Check:

    Log after response finish for correct timing [OK]
Hint: Log after response finishes, not before [OK]
Common Mistakes:
  • Logging too early before response ends
  • Forgetting to call next() (not here though)
  • Using wrong event to measure time
5. You want to log slow requests taking over 500ms in Express. Which code correctly implements this?
hard
A. app.use((req, res) => { if (Date.now() > 500) console.log('Slow request'); });
B. app.use((req, res, next) => { const start = Date.now(); if (Date.now() - start > 500) console.log('Slow request'); next(); });
C. app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { if (Date.now() - start > 500) console.log('Slow request'); }); next(); });
D. app.use((req, res, next) => { console.log('Slow request'); next(); });

Solution

  1. Step 1: Understand timing and event usage

    app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { if (Date.now() - start > 500) console.log('Slow request'); }); next(); }); measures time from request start to response finish, then checks if duration > 500ms.
  2. Step 2: Check other options

    Other options either check time immediately (always near zero), use wrong conditions like Date.now() > 500, or log unconditionally for all requests.
  3. Final Answer:

    app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { if (Date.now() - start > 500) console.log('Slow request'); }); next(); }); -> Option C
  4. Quick Check:

    Check duration on 'finish' event, then log if slow [OK]
Hint: Check time after response finishes, then log if slow [OK]
Common Mistakes:
  • Checking time too early (before response ends)
  • Logging all requests as slow
  • Not using 'finish' event to measure full duration
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