0
0
Node.jsframework~30 mins

In-memory caching patterns in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
In-memory caching patterns in Node.js
📖 Scenario: You are building a simple Node.js app that fetches user data from a slow database. To speed up repeated requests, you want to store user data temporarily in memory.
🎯 Goal: Build a basic in-memory cache using a JavaScript object to store user data keyed by user ID. Implement cache lookup, cache insertion, and cache expiration logic.
📋 What You'll Learn
Create an object called cache to hold cached user data
Create a variable called cacheDuration set to 30000 (milliseconds)
Write a function getUserFromCache that returns cached data if not expired
Write a function setUserInCache that stores user data with a timestamp
Add logic to check cache expiration before returning cached data
💡 Why This Matters
🌍 Real World
In-memory caching is used in web servers to speed up repeated data requests and reduce database load.
💼 Career
Understanding caching patterns is important for backend developers to improve application performance and scalability.
Progress0 / 4 steps
1
Create the cache storage object
Create an empty object called cache to store cached user data.
Node.js
Need a hint?

Use const cache = {} to create an empty object.

2
Set cache duration time
Create a variable called cacheDuration and set it to 30000 milliseconds (30 seconds).
Node.js
Need a hint?

Use const cacheDuration = 30000; to set the cache time.

3
Write function to get user from cache
Write a function called getUserFromCache that takes userId as a parameter. It should check if cache[userId] exists and if the cached timestamp is within cacheDuration. Return the cached data if valid, otherwise return null.
Node.js
Need a hint?

Check if cache[userId] exists and if Date.now() - cached.timestamp < cacheDuration. Return cached data or null.

4
Write function to set user in cache
Write a function called setUserInCache that takes userId and userData as parameters. It should store an object in cache[userId] with data set to userData and timestamp set to the current time using Date.now().
Node.js
Need a hint?

Store an object with data and timestamp in cache[userId].