<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 21 DARSHIL JHA on Medium]]></title>
        <description><![CDATA[Stories by 21 DARSHIL JHA on Medium]]></description>
        <link>https://medium.com/@2023040183?source=rss-c371e37837a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*m303PUfow-zUROQb</url>
            <title>Stories by 21 DARSHIL JHA on Medium</title>
            <link>https://medium.com/@2023040183?source=rss-c371e37837a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:36:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@2023040183/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Redis Caching with Node.js, Express.js and MongoDB]]></title>
            <link>https://medium.com/@2023040183/redis-caching-with-node-js-express-js-and-mongodb-f03fc75d44b7?source=rss-c371e37837a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f03fc75d44b7</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[21 DARSHIL JHA]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 18:14:41 GMT</pubDate>
            <atom:updated>2026-10-09T18:14:41.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Caching is an important technique in backend development that improves application performance by storing frequently accessed data in a temporary storage layer. Instead of retrieving the same information from a database repeatedly, an application can retrieve it from the cache.</p><p>Redis is an in-memory data store commonly used for caching. It stores data in RAM, allowing applications to access frequently requested information with low latency.</p><p>In this project, Redis caching is implemented using Node.js, Express.js, and MongoDB. A simple product API demonstrates how Redis can reduce database queries and improve response times.</p><h3>1. What Is Redis Caching?</h3><p>Redis caching is the process of storing frequently accessed data in Redis so that future requests can retrieve the data without querying the primary database every time.</p><p>For example, consider an e-commerce application where users frequently view product details.</p><p>Without caching, every request may require a MongoDB query. With Redis caching, the application checks Redis first and queries MongoDB only when the requested data is not available in the cache.</p><p><strong>Example:</strong></p><ul><li>First request: Data is fetched from MongoDB and stored in Redis.</li><li>Second request: Data is retrieved directly from Redis.</li><li>When the cache expires or is invalidated, the application fetches fresh data from MongoDB.</li></ul><h3>2. How Redis Caching Works</h3><p>Redis caching commonly follows a strategy called <em>cache-aside</em>.</p><p>The process works as follows:</p><ol><li>The client sends a request to the Express API.</li><li>The application checks Redis for the requested data.</li><li>If the data exists in Redis, it is returned directly to the client. This is called a cache hit.</li><li>If the data does not exist, it is called a cache miss.</li><li>The application retrieves the data from MongoDB.</li><li>The retrieved data is stored in Redis with an expiration time.</li><li>The data is returned to the client.</li></ol><p><strong>Cache flow:</strong></p><p>Client → Express API → Check Redis → Cache hit: Return data</p><p>If the cache misses:</p><p>Client → Express API → Redis miss → MongoDB → Store in Redis → Return data</p><h3>3. Project Overview</h3><p>The project demonstrates Redis caching through a product management API.</p><p><strong>Technologies used:</strong></p><ul><li>Node.js — JavaScript runtime environment.</li><li>Express.js — Backend framework for creating API endpoints.</li><li>MongoDB — Primary database for storing product information.</li><li>Redis — In-memory cache for frequently requested data.</li></ul><p>The application retrieves product information from MongoDB and caches it in Redis. Subsequent requests for the same product can be served from the cache.</p><h3>Example</h3><p>Suppose MongoDB contains the following product:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*KdCjp_-bMvCZB7B_.png" /></figure><p>On the first request, the product is retrieved from MongoDB and saved in Redis.</p><p>On subsequent requests, the cached product is returned without another MongoDB query, as long as the cache entry remains valid.</p><h3>4. Advantages of Redis Caching</h3><ul><li><strong>Improved performance:</strong> Frequently requested data can be retrieved quickly.</li><li><strong>Reduced database load:</strong> Fewer repeated queries are sent to MongoDB.</li><li><strong>Better scalability:</strong> Caching can help an application handle more read requests.</li><li><strong>Low latency:</strong> Redis provides fast access to in-memory data.</li><li><strong>Expiration support:</strong> Cached data can automatically expire after a specified period.</li></ul><h3>5. Project Configuration</h3><p>First, create a Node.js project and install the required packages.</p><pre>mkdir redis-caching<br>cd redis-caching<br>npm init -y<br>npm install express mongoose redis dotenv</pre><p>Install and start MongoDB and Redis separately, or use suitable hosted services.</p><p>Create the following project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*sQy421sXY3_JQ0z0.png" /></figure><p>Create a .env file:</p><p>Press enter or click to view image in full size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*SYi49TqNG_QxWqG_.png" /></figure><p>These connection strings assume that MongoDB and Redis are running locally with their default ports.</p><h3>6. Implementation</h3><h3>Step 1: Create the Product Model</h3><p>Create models/Product.js:</p><pre>const mongoose = require(&quot;mongoose&quot;);</pre><pre>const productSchema = new mongoose.Schema({<br>  name: {<br>    type: String,<br>    required: true<br>  },<br>  price: {<br>    type: Number,<br>    required: true<br>  }<br>});module.exports = mongoose.model(&quot;Product&quot;, productSchema);</pre><p>This model defines the product fields stored in MongoDB.</p><h3>Step 2: Implement Redis Caching</h3><p>Create server.js:</p><pre>require(&quot;dotenv&quot;).config();</pre><pre>const express = require(&quot;express&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>const { createClient } = require(&quot;redis&quot;);<br>const Product = require(&quot;./models/Product&quot;);const app = express();app.use(express.json());const redisClient = createClient({<br>  url: process.env.REDIS_URL<br>});redisClient.on(&quot;error&quot;, (err) =&gt; {<br>  console.error(&quot;Redis Error:&quot;, err.message);<br>});async function startServer() {<br>  await mongoose.connect(process.env.MONGO_URI);<br>  console.log(&quot;MongoDB connected&quot;);  await redisClient.connect();<br>  console.log(&quot;Redis connected&quot;);  app.listen(process.env.PORT || 3000, () =&gt; {<br>    console.log(&quot;Server running on port 3000&quot;);<br>  });<br>}// Create a product<br>app.post(&quot;/products&quot;, async (req, res) =&gt; {<br>  try {<br>    const product = await Product.create(req.body);    res.status(201).json({<br>      message: &quot;Product created successfully&quot;,<br>      product<br>    });<br>  } catch (err) {<br>    res.status(400).json({<br>      error: err.message<br>    });<br>  }<br>});// Get a product with Redis caching<br>app.get(&quot;/products/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const cacheKey = `product:${req.params.id}`;    // Check Redis cache<br>    const cachedProduct = await redisClient.get(cacheKey);    if (cachedProduct) {<br>      return res.json({<br>        source: &quot;Redis Cache&quot;,<br>        product: JSON.parse(cachedProduct)<br>      });<br>    }    // Fetch from MongoDB if cache misses<br>    const product = await Product.findById(req.params.id);    if (!product) {<br>      return res.status(404).json({<br>        message: &quot;Product not found&quot;<br>      });<br>    }    // Store the result in Redis for 60 seconds<br>    await redisClient.setEx(<br>      cacheKey,<br>      60,<br>      JSON.stringify(product)<br>    );    res.json({<br>      source: &quot;MongoDB&quot;,<br>      product<br>    });<br>  } catch (err) {<br>    res.status(500).json({<br>      error: err.message<br>    });<br>  }<br>});// Update a product and invalidate its cache<br>app.put(&quot;/products/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const product = await Product.findByIdAndUpdate(<br>      req.params.id,<br>      req.body,<br>      { new: true, runValidators: true }<br>    );    if (!product) {<br>      return res.status(404).json({<br>        message: &quot;Product not found&quot;<br>      });<br>    }    await redisClient.del(`product:${req.params.id}`);    res.json({<br>      message: &quot;Product updated successfully&quot;,<br>      product<br>    });<br>  } catch (err) {<br>    res.status(400).json({<br>      error: err.message<br>    });<br>  }<br>});startServer().catch((err) =&gt; {<br>  console.error(&quot;Server startup failed:&quot;, err.message);<br>  process.exit(1);<br>});</pre><h3>Step 3: Run the Application</h3><p>Start the application using:</p><pre>node server.js</pre><p>If both databases are running and the connection settings are correct, the server should connect to MongoDB and Redis before accepting requests.</p><h3>7. Results</h3><p>The expected behavior is summarized below.</p><p>RequestData sourceResultFirst GET requestMongoDBData fetched and cachedSecond GET requestRedisCached data returnedGET after cache expiresMongoDBFresh data fetchedGET after product updateMongoDBUpdated data fetched and cached</p><p>These are expected results based on the implementation. Actual response times and behavior should be verified by running the project.</p><h3>8. Real-World Applications of Redis Caching</h3><p>Redis caching is useful in many applications:</p><ul><li>E-commerce websites for frequently viewed products.</li><li>Social media platforms for frequently accessed profiles and feeds.</li><li>News websites for popular articles.</li><li>Booking systems for frequently requested public information.</li><li>APIs for caching expensive database queries.</li><li>Session management and temporary data storage.</li></ul><h3>9. Important Considerations</h3><p>Although Redis caching improves performance, it also introduces some considerations.</p><ul><li><strong>Cache expiration:</strong> Cached data should have an appropriate time-to-live (TTL).</li><li><strong>Cache invalidation:</strong> When source data changes, related cached data must be updated or removed.</li><li><strong>Memory usage:</strong> Redis stores data in memory, so available memory must be managed.</li><li><strong>Data consistency:</strong> Cached values can become stale if updates are not handled correctly.</li><li><strong>Security:</strong> Production deployments should use appropriate authentication, network restrictions, and secure connection settings.</li></ul><p>The example uses cache invalidation after an update. In production, additional handling may be required for Redis failures, concurrent requests, and updates that affect multiple cached records.</p><h3>10. Conclusion</h3><p>Redis caching is an effective technique for improving backend application performance. By storing frequently requested data in memory, Redis reduces repeated database queries and can lower response latency.</p><p>This project demonstrates cache-aside caching using Node.js, Express.js, MongoDB, and Redis. It shows how to retrieve data from a cache, fetch data from the primary database when a cache miss occurs, set an expiration time, and invalidate cached data after an update.</p><p>Redis caching is therefore a useful technique for building efficient, scalable, and responsive web applications.</p><h3>11. References</h3><ol><li>Redis Documentation — Cache-Aside Pattern: <a href="https://redis.io/docs/latest/develop/use-cases/cache-aside/nodejs/">https://redis.io/docs/latest/develop/use-cases/cache-aside/nodejs/</a></li><li>Redis Documentation — Connecting to Redis with Node.js: <a href="https://redis.io/docs/latest/develop/clients/nodejs/connect/">https://redis.io/docs/latest/develop/clients/nodejs/connect/</a></li><li>MongoDB Documentation: <a href="https://www.mongodb.com/docs/">https://www.mongodb.com/docs/</a></li><li>Express.js Documentation: <a href="https://expressjs.com/">https://expressjs.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f03fc75d44b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>