📖 Scenario: You are building a simple Node.js server that responds to client requests. To improve user experience, you want to optimize the response time by caching data and avoiding repeated slow operations.
🎯 Goal: Build a Node.js server that caches data after the first request and serves cached data on subsequent requests to reduce response time.
📋 What You'll Learn
Create a variable to hold cached data
Add a flag to check if data is cached
Implement logic to cache data on first request
Serve cached data on subsequent requests
💡 Why This Matters
🌍 Real World
Caching is used in web servers to speed up responses by storing results of slow operations.
💼 Career
Understanding response time optimization and caching is important for backend developers to build efficient and scalable applications.
Progress0 / 4 steps
1
Create initial data and server setup
Create a variable called data with the string value 'Slow data loaded'. Then create a basic HTTP server using Node.js http module that listens on port 3000.
Node.js
Hint
Use const data = 'Slow data loaded' and http.createServer to create the server.
2
Add cache flag variable
Add a variable called isCached and set it to false. This will track if the data is cached.
Node.js
Hint
Declare let isCached = false before the server creation.
3
Implement caching logic in request handler
Inside the server request handler, create a variable called cachedData initialized to null outside the handler. Then, inside the handler, check if isCached is false. If so, set cachedData to data and set isCached to true. Respond with cachedData.
Node.js
Hint
Use if (!isCached) to set cachedData and update isCached.
4
Complete server with caching optimization
Add a console log inside the if (!isCached) block that says 'Caching data for the first time'. This helps track when caching happens.
Node.js
Hint
Add console.log('Caching data for the first time') inside the caching condition.
Practice
(1/5)
1. Which of the following is a common technique to improve response time in a Node.js application?
easy
A. Writing all code synchronously to keep it simple
B. Using only synchronous file system calls
C. Increasing the number of console.log statements
D. Using asynchronous functions to avoid blocking the event loop
Solution
Step 1: Understand Node.js event loop behavior
Node.js uses an event loop that runs best when tasks are asynchronous, avoiding blocking operations.
Step 2: Identify the impact of async functions
Using asynchronous functions allows Node.js to handle other requests while waiting, improving response time.
Final Answer:
Using asynchronous functions to avoid blocking the event loop -> Option D
Quick Check:
Async = faster response [OK]
Hint: Async code keeps Node.js responsive and fast [OK]
Common Mistakes:
Thinking synchronous code is faster
Ignoring event loop blocking
Believing console.log improves speed
2. Which syntax correctly uses caching middleware in an Express.js app to improve response time?
easy
A. app.use(cacheMiddleware);
B. app.cacheMiddleware();
C. cacheMiddleware(app);
D. app.cache.useMiddleware();
Solution
Step 1: Recall Express middleware usage
Middleware is added using app.use(middlewareFunction) to apply it to requests.
Step 2: Match correct syntax
Only app.use(cacheMiddleware); correctly applies the middleware function.
Final Answer:
app.use(cacheMiddleware); -> Option A
Quick Check:
Middleware added with app.use() [OK]
Hint: Use app.use() to add middleware in Express [OK]
Common Mistakes:
Calling middleware as a method on app
Passing app as argument to middleware
Using incorrect method names
3. What will be the output response time behavior of this Node.js code snippet?
C. getUserFromDb is asynchronous but used synchronously
D. Cache keys are not strings
Solution
Step 1: Check res.send calls in both branches
If cache hit, res.send is called, but code continues and calls res.send again after fetching data.
Step 2: Understand Express response behavior
Calling res.send twice causes an error because response is already sent.
Final Answer:
res.send is called twice causing error -> Option B
Quick Check:
Only one res.send per request allowed [OK]
Hint: Return after sending cached response to avoid double send [OK]
Common Mistakes:
Ignoring multiple res.send calls
Assuming synchronous DB call is fine
Not returning after cache hit
5. You want to optimize response time by streaming a large file in Node.js instead of loading it fully into memory. Which code snippet correctly implements this using Express?