Back to journal

    Developer journal

    Redis Caching with Node.js and Express: A Practical Guide

    Learn how to integrate Redis caching into Node.js and Express applications using cache-aside patterns, TTL, cache invalidation, rate limiting, and production reliability techniques.

    28 min read66 sections
    Redis Caching with Node.js and Express: A Practical Guide article cover
    In this article66 sectionsBrowse sections
    28 min read · 5,427 words

    Redis Caching with Node.js and Express: A Practical Guide

    As a backend application grows, database queries and repeated API requests can become significant performance bottlenecks.

    Imagine an e-commerce application where thousands of users repeatedly request the same product information. Every request reaches Express, queries MongoDB, processes the result, and returns the response.

    Even when the requested data rarely changes, the application repeats much of the same work.

    This is where caching becomes useful.

    Redis is an in-memory data store commonly used to cache frequently accessed data, manage distributed rate limits, store temporary information, and support real-time applications.

    When integrated properly, Redis can reduce database load, improve API response times, and help applications handle larger workloads.

    In this guide, we will integrate Redis into a Node.js and Express application using MongoDB as the primary database.

    We will cover cache-aside architecture, expiration, invalidation, cache consistency, rate limiting, session storage, and production deployment considerations.

    1. What Is Redis?

    Redis is an in-memory data store that supports multiple data structures and operations.

    Unlike a traditional relational or document database, Redis is designed to provide fast access to data held primarily in memory.

    It supports several data structures, including:

    Data structureCommon use case
    StringsCache values, counters, temporary tokens
    HashesStructured records and object fields
    ListsQueues and ordered collections
    SetsUnique values and membership checks
    Sorted SetsLeaderboards and ranking systems
    StreamsEvent processing and message workflows
    BitmapsCompact boolean tracking
    HyperLogLogApproximate cardinality counting

    Redis is commonly used alongside databases such as MongoDB and PostgreSQL rather than automatically replacing them.

    For example:

    • MongoDB stores permanent application records.
    • Redis stores frequently accessed temporary copies.
    • Express coordinates requests between the frontend, Redis, and MongoDB.

    A simplified architecture:

                 React Application
                         |
                     Express API
                         |
                  Redis Cache Check
                         |
                  +------+------+
                  |             |
               Cache Hit      Cache Miss
                  |             |
                  |          MongoDB
                  |             |
                  |         Store Result
                  |             |
                  +------+------+
                         |
                     API Response
    

    The application checks Redis first. If the requested information exists, it returns the cached value. Otherwise, it retrieves the information from MongoDB and stores a copy in Redis.

    This reduces repeated database work.

    Official documentation: Redis Documentation.

    2. Why Use Redis in a Node.js Application?

    Consider a product API:

    GET /api/products/123
    

    Without caching, every request may execute a database query:

    const product = await Product.findById('123')
    

    If 5,000 users request the same product within a short period, the application could execute thousands of identical queries.

    With Redis, the application can retrieve the product from memory after the first database lookup.

    Benefits of Redis Caching

    1. Reduced database load

    Frequently accessed data can be served without repeatedly querying MongoDB.

    2. Faster data retrieval

    Redis can serve cached values with very low latency, reducing the time spent waiting for database operations.

    3. Improved scalability

    Caching can reduce pressure on database connection pools and help the backend handle more read requests.

    4. Shared cache across multiple instances

    Unlike a local JavaScript object, Redis can be shared by multiple Node.js processes and servers.

    5. Additional backend capabilities

    Redis also supports temporary tokens, counters, rate limiting, distributed coordination, and other use cases.

    However, Redis is not automatically beneficial for every API.

    If an endpoint returns rapidly changing data or performs an inexpensive query, the additional cache lookup and invalidation logic may not be worthwhile.

    Measure the actual bottleneck before introducing caching.

    3. Understanding Cache-Aside Architecture

    Cache-aside is one of the most common caching strategies.

    The application controls when data is loaded into the cache and when cached entries are invalidated.

    The process looks like this:

                  Incoming Request
                          |
                     Check Redis
                          |
                    +-----+-----+
                    |           |
                 Cache Hit   Cache Miss
                    |           |
                    |        Query MongoDB
                    |           |
                    |        Store in Redis
                    |           |
                    +-----+-----+
                          |
                     Return Result
    

    There are three main operations.

    Cache Hit

    The requested value already exists in Redis.

    The application returns the cached value without querying MongoDB.

    Cache Miss

    The requested value is not available in Redis.

    The application queries MongoDB, stores the result in Redis, and returns it.

    Cache Invalidation

    When the underlying database record changes, the application deletes the corresponding cache entry.

    The next request retrieves the updated record from MongoDB and repopulates Redis.

    This pattern is useful because MongoDB remains the authoritative source of data.

    Redis only stores a temporary representation.

    4. Installing Redis

    There are several ways to run Redis during development and production.

    Option A: Docker

    If Docker is installed, you can run Redis using:

    docker run -d \
      --name redis \
      -p 127.0.0.1:6379:6379 \
      redis:latest
    

    This exposes Redis only on the local loopback interface.

    For a repeatable development environment, consider using a pinned Redis image version instead of latest.

    You can inspect the container:

    docker ps
    

    Connect using Redis CLI:

    docker exec -it redis redis-cli
    

    Test the connection:

    PING
    

    Expected response:

    PONG
    

    Option B: Managed Redis

    For production applications, managed Redis-compatible services can reduce operational work.

    Depending on your infrastructure, options include:

    • Redis Cloud.
    • Amazon ElastiCache for Redis OSS or Valkey.
    • Amazon MemoryDB.
    • Self-hosted Redis or Valkey.

    Evaluate persistence requirements, availability, network topology, authentication, TLS, and cost before choosing a service.

    For an AWS deployment, a managed cache service in the same VPC as the EC2 application can provide a practical architecture.

    Avoid exposing Redis directly to the public internet.

    5. Installing the Node.js Redis Client

    Redis provides an official Node.js client called node-redis.

    Install it:

    npm install redis
    

    For our example, the application will use:

    • Express.js.
    • MongoDB with Mongoose.
    • Redis using node-redis.

    Install the remaining packages if they are not already present:

    npm install express mongoose dotenv
    

    A suggested project structure:

    src/
      config/
        database.js
        redis.js
    
      controllers/
        product.controller.js
    
      middleware/
        errorHandler.js
    
      models/
        product.model.js
    
      routes/
        product.routes.js
    
      services/
        product.service.js
        cache.service.js
    
      app.js
      server.js
    

    Separating Redis configuration and cache operations makes the application easier to maintain.

    6. Connecting Redis to Node.js

    Create an environment file:

    PORT=5000
    
    MONGODB_URI=mongodb://127.0.0.1:27017/myapp
    
    REDIS_URL=redis://127.0.0.1:6379
    

    For production, use a secured Redis endpoint and the appropriate TLS and authentication configuration.

    Create src/config/redis.js:

    import { createClient } from 'redis'
    
    export const redisClient = createClient({
      url: process.env.REDIS_URL,
    })
    
    redisClient.on('error', (error) => {
      console.error('Redis Client Error:', error)
    })
    
    redisClient.on('connect', () => {
      console.log('Connecting to Redis...')
    })
    
    redisClient.on('ready', () => {
      console.log('Redis connection ready')
    })
    
    redisClient.on('reconnecting', () => {
      console.log('Reconnecting to Redis...')
    })
    
    redisClient.on('end', () => {
      console.log('Redis connection closed')
    })
    
    export async function connectRedis() {
      if (!redisClient.isOpen) {
        await redisClient.connect()
      }
    }
    

    The Redis client is created once and reused throughout the application.

    Do not create a new Redis connection for every incoming API request.

    Initialize the Connections

    Create src/server.js:

    import 'dotenv/config'
    
    import app from './app.js'
    import { connectRedis } from './config/redis.js'
    import { connectDatabase } from './config/database.js'
    
    const PORT = process.env.PORT || 5000
    
    async function startServer() {
      await connectDatabase()
    
      await connectRedis()
    
      app.listen(PORT, () => {
        console.log(`Server running on port ${PORT}`)
      })
    }
    
    startServer().catch((error) => {
      console.error('Application startup failed:', error)
    
      process.exit(1)
    })
    

    This example requires both MongoDB and Redis during startup.

    That is a deliberate availability choice: the application does not start unless both dependencies are ready.

    Later, we will discuss an alternative where Redis is optional and the API continues operating without caching.

    Official reference: Node.js Redis Client — Connection.

    7. Understanding Redis Keys and Expiration

    Redis stores values using keys.

    For example:

    SET product:123 "Product information"
    

    Retrieve the value:

    GET product:123
    

    A useful key naming convention is important as the application grows.

    Examples:

    cache:product:123
    cache:user:456
    cache:category:electronics
    session:abc123
    rate-limit:ip:192.0.2.10
    

    Use consistent prefixes to identify the purpose of each key.

    7.1 Setting Expiration

    Cached data should usually have a time-to-live (TTL).

    A TTL determines how long a key remains available before Redis automatically expires it.

    Example:

    SET cache:product:123 "Product information" EX 300
    

    This stores the value for 300 seconds.

    You can inspect the remaining lifetime:

    TTL cache:product:123
    

    Set an expiration on an existing key:

    EXPIRE cache:product:123 300
    

    Remove a key manually:

    DEL cache:product:123
    

    Expiration is important because cached data can become outdated.

    For example:

    • Product information might be cached for five minutes.
    • Public category information might be cached for thirty minutes.
    • A temporary verification token might have a much shorter lifetime.

    The appropriate TTL depends on the business requirements and how frequently the underlying data changes.

    A TTL bounds the maximum lifetime of an entry, but it does not guarantee that cached information is always current.

    8. Building a Reusable Cache Service

    Instead of writing Redis commands inside every controller, create a reusable service.

    Create src/services/cache.service.js:

    import { redisClient } from '../config/redis.js'
    
    export async function getCache(key) {
      const value = await redisClient.get(key)
    
      if (value === null) {
        return null
      }
    
      return JSON.parse(value)
    }
    
    export async function setCache(key, value, ttl = 300) {
      await redisClient.set(
        key,
        JSON.stringify(value),
        {
          EX: ttl,
        }
      )
    }
    
    export async function deleteCache(key) {
      await redisClient.del(key)
    }
    
    export async function deleteCacheByPattern(pattern) {
      let cursor = '0'
    
      do {
        const result = await redisClient.scan(cursor, {
          MATCH: pattern,
          COUNT: 100,
        })
    
        cursor = result.cursor
    
        if (result.keys.length > 0) {
          await redisClient.del(result.keys)
        }
      } while (cursor !== '0')
    }
    

    This provides four reusable operations:

    • getCache()
    • setCache()
    • deleteCache()
    • deleteCacheByPattern()

    The pattern deletion function uses SCAN instead of KEYS.

    This distinction matters in production.

    KEYS can block Redis while scanning a large keyspace. SCAN iterates incrementally, although it may return duplicate keys and should not be treated as an atomic snapshot.

    For large deployments, deleting many matching keys should also be controlled to avoid generating excessive Redis traffic.

    Important Serialization Considerations

    Redis strings store serialized JSON in this example.

    This works well for ordinary API response objects.

    However:

    • JSON.stringify() cannot serialize circular references.
    • Date values return as strings after parsing.
    • undefined values are not preserved as ordinary JSON properties.
    • Large cached objects can consume significant memory.
    • Cached data should be validated if it crosses trust boundaries.

    Avoid caching entire Mongoose documents with internal metadata when a smaller plain response object is sufficient.

    9. Implementing Cache-Aside in Express

    Now we can integrate Redis into a real API.

    Assume we have a MongoDB product model.

    Create src/models/product.model.js:

    import mongoose from 'mongoose'
    
    const productSchema = new mongoose.Schema(
      {
        name: {
          type: String,
          required: true,
        },
    
        price: {
          type: Number,
          required: true,
        },
    
        category: {
          type: String,
          required: true,
        },
    
        stock: {
          type: Number,
          default: 0,
        },
      },
      {
        timestamps: true,
      }
    )
    
    export default mongoose.model('Product', productSchema)
    

    Create src/services/product.service.js:

    import Product from '../models/product.model.js'
    
    import {
      getCache,
      setCache,
      deleteCache,
    } from './cache.service.js'
    
    const PRODUCT_CACHE_TTL = 300
    
    export async function getProductById(productId) {
      const cacheKey = `cache:product:${productId}`
    
      // 1. Check Redis
      const cachedProduct = await getCache(cacheKey)
    
      if (cachedProduct !== null) {
        return {
          product: cachedProduct,
          cacheHit: true,
        }
      }
    
      // 2. Fetch from MongoDB
      const product = await Product.findById(productId).lean()
    
      if (!product) {
        return {
          product: null,
          cacheHit: false,
        }
      }
    
      // 3. Store in Redis
      await setCache(
        cacheKey,
        product,
        PRODUCT_CACHE_TTL
      )
    
      return {
        product,
        cacheHit: false,
      }
    }
    
    export async function updateProduct(productId, updates) {
      const product = await Product.findByIdAndUpdate(
        productId,
        updates,
        {
          new: true,
          runValidators: true,
        }
      ).lean()
    
      if (!product) {
        return null
      }
    
      // 4. Invalidate the cached record
      await deleteCache(`cache:product:${productId}`)
    
      return product
    }
    

    The flow is straightforward:

    1. Check Redis.
    2. Return the cached product if it exists.
    3. Query MongoDB on a cache miss.
    4. Store the result with a TTL.
    5. Delete the cache entry after a successful update.

    Notice that the database is updated before the cache is invalidated.

    This is important because MongoDB remains the source of truth.

    Create the Controller

    src/controllers/product.controller.js:

    import {
      getProductById,
      updateProduct,
    } from '../services/product.service.js'
    
    export async function getProduct(req, res) {
      const result = await getProductById(req.params.id)
    
      if (!result.product) {
        return res.status(404).json({
          success: false,
          message: 'Product not found',
        })
      }
    
      res.set(
        'X-Cache',
        result.cacheHit ? 'HIT' : 'MISS'
      )
    
      return res.json({
        success: true,
        data: result.product,
      })
    }
    
    export async function updateProductController(req, res) {
      const product = await updateProduct(
        req.params.id,
        req.body
      )
    
      if (!product) {
        return res.status(404).json({
          success: false,
          message: 'Product not found',
        })
      }
    
      return res.json({
        success: true,
        data: product,
      })
    }
    

    Configure the Routes

    src/routes/product.routes.js:

    import { Router } from 'express'
    
    import {
      getProduct,
      updateProductController,
    } from '../controllers/product.controller.js'
    
    const router = Router()
    
    router.get('/:id', getProduct)
    
    router.patch('/:id', updateProductController)
    
    export default router
    

    Configure the Express Application

    src/app.js:

    import express from 'express'
    
    import productRoutes from './routes/product.routes.js'
    
    const app = express()
    
    app.use(express.json())
    
    app.use('/api/products', productRoutes)
    
    export default app
    

    Now request the same product multiple times:

    GET /api/products/123
    

    The first request returns:

    X-Cache: MISS
    

    Subsequent requests return:

    X-Cache: HIT
    

    As long as the cache entry remains available, the application can avoid repeatedly querying MongoDB.

    10. Cache Invalidation: Keeping Data Fresh

    Caching introduces an important problem: stale data.

    Imagine the application caches a product with this information:

    {
      "name": "Mechanical Keyboard",
      "price": 2500,
      "stock": 20
    }
    

    A user purchases five units.

    MongoDB now contains:

    {
      "name": "Mechanical Keyboard",
      "price": 2500,
      "stock": 15
    }
    

    But Redis may still contain the previous value.

    Without invalidation, the application could return an incorrect stock count.

    10.1 Delete-on-Write Strategy

    The simplest strategy is to invalidate the cache after a successful database update.

    await Product.findByIdAndUpdate(productId, updates)
    
    await deleteCache(`cache:product:${productId}`)
    

    The next request loads the updated document from MongoDB.

    This is often simpler and safer than trying to update the cached object manually.

    Suppose the application also caches product lists:

    cache:product:123
    cache:products:category:electronics
    cache:products:featured
    

    Updating a product may affect all three.

    Invalidating only the individual product cache is insufficient if the cached lists contain outdated information.

    You need an invalidation strategy for related entries.

    One simple approach is to maintain a cache namespace or version.

    For example:

    cache:products:v1:category:electronics
    

    When the product catalogue changes, increment the catalogue version.

    New requests use the new namespace, leaving old entries to expire naturally.

    Another approach is to explicitly delete known related cache keys.

    The correct strategy depends on how many cached views depend on the modified record.

    10.3 Avoid Deleting Every Cache Key

    A tempting approach is to delete all Redis keys after every database update.

    Do not do this.

    It removes useful cache entries, creates unnecessary cache misses, and may cause a sudden increase in database load.

    Invalidate only the entries affected by the write operation.

    10.4 Cache Invalidation Is Not Automatically Atomic

    There is a subtle race condition in the simple delete-on-write pattern.

    Consider this sequence:

    1. Request A reads an old product from MongoDB.
    2. Request B updates the product in MongoDB.
    3. Request B deletes the Redis cache entry.
    4. Request A finishes and writes its old product into Redis.

    The stale value is now cached again.

    For ordinary product descriptions, a short TTL may make this acceptable.

    For highly sensitive data such as stock, balances, or permissions, stronger consistency controls may be necessary.

    Possible solutions include:

    • Versioned cache keys.
    • Compare-and-set logic.
    • Atomic Redis scripts.
    • Database version checks.
    • Event-driven invalidation.
    • Avoiding cache use for data that requires immediate consistency.

    The important lesson is that deleting a cache key after a database write does not eliminate every possible stale-data race.

    11. Handling Cache Stampedes

    A cache stampede occurs when many requests attempt to load the same missing or expired cache entry simultaneously.

    For example:

                  Cache Expires
                        |
                 100 Requests Arrive
                        |
                  Cache Misses
                        |
              +---------+---------+
              |         |         |
           Query DB  Query DB  Query DB
              |         |         |
              +---------+---------+
                        |
                  Database Load
    

    Instead of one database query, the application might execute 100 identical queries.

    This defeats part of the purpose of caching.

    11.1 Simple Prevention: Randomized TTL

    One approach is to introduce a small amount of random variation in cache expiration.

    const BASE_TTL = 300
    
    const ttl = BASE_TTL + Math.floor(Math.random() * 60)
    
    await setCache(cacheKey, product, ttl)
    

    This reduces the likelihood that large numbers of related cache entries expire simultaneously.

    However, it does not fully prevent concurrent requests for the same key from causing a stampede.

    11.2 Single-Flight Loading

    Another approach is to allow only one request to load a missing value while other requests wait for the result.

    For a single Node.js process, a simple in-memory map can provide this behavior:

    const pendingLoads = new Map()
    
    export async function loadWithSingleFlight(key, loader) {
      if (pendingLoads.has(key)) {
        return pendingLoads.get(key)
      }
    
      const promise = loader()
    
      pendingLoads.set(key, promise)
    
      try {
        return await promise
      } finally {
        pendingLoads.delete(key)
      }
    }
    

    Use it around the database-loading operation:

    const product = await loadWithSingleFlight(
      cacheKey,
      async () => {
        const existing = await getCache(cacheKey)
    
        if (existing !== null) {
          return existing
        }
    
        const record = await Product.findById(productId).lean()
    
        if (record) {
          await setCache(cacheKey, record, PRODUCT_CACHE_TTL)
        }
    
        return record
      }
    )
    

    This reduces duplicate work within one Node.js process.

    However, an in-memory map does not coordinate multiple PM2 processes or multiple EC2 instances.

    11.3 Distributed Locking

    For workloads where cache stampedes are significant across multiple application instances, Redis can coordinate loading using an atomic lock.

    For example:

    SET lock:product:123 unique-token NX PX 10000
    

    The command attempts to acquire a lock only when the key does not already exist.

    • NX means set only if the key does not exist.
    • PX sets the lock expiration in milliseconds.
    • unique-token identifies the lock owner.

    When releasing the lock, the application must verify that the token still matches before deleting the lock.

    Otherwise, an expired lock might have been acquired by another process and accidentally deleted by the original owner.

    For robust implementations, use a well-reviewed distributed locking or cache-stampede strategy rather than writing an incomplete lock implementation.

    Redis's official cache-aside guide demonstrates single-flight locking and stampede mitigation.

    Reference: Redis — Cache-Aside with Node.js.

    12. Caching API Responses

    So far, we have cached individual MongoDB records.

    You can also cache the results of entire API endpoints.

    For example:

    GET /api/products?category=electronics&page=1
    

    The cache key should account for every parameter that affects the response.

    const cacheKey =
      `cache:products:${category}:page:${page}`
    

    A reusable Express middleware can handle cached responses.

    import {
      getCache,
      setCache,
    } from '../services/cache.service.js'
    
    export function cacheResponse(ttl = 300) {
      return async (req, res, next) => {
        try {
          const cacheKey = `cache:response:${req.originalUrl}`
    
          const cached = await getCache(cacheKey)
    
          if (cached !== null) {
            res.set('X-Cache', 'HIT')
    
            return res.json(cached)
          }
    
          const originalJson = res.json.bind(res)
    
          res.json = (body) => {
            if (res.statusCode === 200) {
              setCache(cacheKey, body, ttl).catch((error) => {
                console.error('Cache write failed:', error)
              })
            }
    
            return originalJson(body)
          }
    
          res.set('X-Cache', 'MISS')
    
          next()
        } catch (error) {
          next(error)
        }
      }
    }
    

    Apply it:

    router.get(
      '/',
      cacheResponse(120),
      getProducts
    )
    

    This is a simplified response-cache middleware.

    Before using it in production, consider the following limitations:

    • The key must include all relevant query parameters.
    • User-specific responses must not be shared between users.
    • Authentication and authorization must happen before serving private cached data.
    • Non-200 responses should not be cached accidentally.
    • Streaming and file responses need separate handling.
    • Cache invalidation must account for every endpoint affected by a write.
    • Cache serialization failures must not break the API response.

    For public catalogue endpoints, response caching can be useful.

    For private dashboards or personalized account data, entity-level caching with carefully designed authorization is often safer.

    13. Using Redis for Distributed Rate Limiting

    Caching is not the only useful Redis feature.

    Rate limiting helps protect an API from excessive requests.

    For example, a login endpoint might limit how many attempts a user can make within a defined period.

    A local in-memory rate limiter works only within one process.

    If your application runs across several PM2 workers or EC2 instances, each process might maintain a different counter.

    Redis provides shared state that multiple application instances can access.

    13.1 Install the Rate Limiting Packages

    npm install express-rate-limit rate-limit-redis
    

    13.2 Configure a Redis Store

    import { rateLimit } from 'express-rate-limit'
    
    import { RedisStore } from 'rate-limit-redis'
    
    import { redisClient } from './config/redis.js'
    
    export const loginLimiter = rateLimit({
      windowMs: 15 * 60 * 1000,
    
      limit: 5,
    
      standardHeaders: 'draft-8',
    
      legacyHeaders: false,
    
      store: new RedisStore({
        sendCommand: (...args) => redisClient.sendCommand(args),
      }),
    
      message: {
        success: false,
        message: 'Too many login attempts. Try again later.',
      },
    })
    

    Apply it to the login endpoint:

    app.post('/api/auth/login', loginLimiter, loginController)
    

    The Redis store allows multiple application processes to share rate-limit state.

    This example uses the package's standard store interface. Check the current package documentation and compatibility requirements for your installed versions.

    Important Rate-Limiting Considerations

    • Configure Express proxy trust correctly when Nginx is in front of the application.
    • Do not blindly trust arbitrary forwarded IP headers.
    • Use appropriate keys for the limit, such as IP address, account identifier, or API key.
    • Consider stricter rules for authentication and password-reset endpoints.
    • Decide whether requests should be allowed or rejected if Redis becomes unavailable.

    A rate limiter is a security control, so its failure policy should be deliberate.

    References:

    14. Using Redis for Session Storage

    Express applications sometimes store sessions in server memory.

    This can become problematic when an application runs across multiple Node.js processes.

    For example:

                    Load Balancer
                         |
                 +-------+-------+
                 |               |
              Server A         Server B
                 |               |
            Local Sessions  Local Sessions
    

    A session created on Server A may not exist on Server B.

    Redis can provide shared session storage.

    Install the packages:

    npm install express-session connect-redis
    

    Example:

    import session from 'express-session'
    
    import { RedisStore } from 'connect-redis'
    
    import { redisClient } from './config/redis.js'
    
    app.use(
      session({
        store: new RedisStore({
          client: redisClient,
          prefix: 'session:',
        }),
    
        secret: process.env.SESSION_SECRET,
    
        resave: false,
    
        saveUninitialized: false,
    
        cookie: {
          httpOnly: true,
          secure: process.env.NODE_ENV === 'production',
          sameSite: 'lax',
          maxAge: 1000 * 60 * 60 * 24,
        },
      })
    )
    

    This example assumes a deployment where the cookie can use the specified attributes. Cross-site frontend and backend deployments may require different SameSite, Secure, domain, and CSRF configurations.

    For production:

    • Use a strong session secret.
    • Configure HTTPS correctly.
    • Review cookie attributes.
    • Set an appropriate session expiration.
    • Protect session endpoints against CSRF where necessary.
    • Avoid storing unnecessary sensitive data in sessions.
    • Configure trusted proxy behavior when TLS terminates at Nginx.

    Redis session storage is useful when an application needs centralized, shared session state.

    It is not mandatory for every JWT-based authentication architecture.

    15. Handling Redis Failures

    A production application should not assume Redis is always available.

    Redis can become unavailable because of:

    • Network interruptions.
    • Server restarts.
    • Connection limits.
    • Resource exhaustion.
    • Configuration errors.
    • Managed service maintenance.

    The application must decide what happens when Redis fails.

    There are two common strategies.

    15.1 Fail Open

    If Redis is unavailable, the application continues without caching.

    Request
       |
    Redis Available?
       |
       +-- Yes --> Check Cache
       |              |
       |          Hit / Miss
       |
       +-- No --> Query MongoDB
                      |
                  Return Result
    

    This is often appropriate for non-critical application caches.

    The API remains available, although database load may increase.

    15.2 Fail Closed

    If Redis is unavailable, the application rejects the operation.

    This may be appropriate when Redis stores state that is essential to enforcing a security or business rule.

    For example, if a distributed rate limiter cannot verify its state, allowing every request may violate a security requirement.

    The correct approach depends on the feature.

    15.3 Implement Cache Fallback

    For ordinary product caching, a fallback can look like this:

    export async function safeGetCache(key) {
      try {
        return await getCache(key)
      } catch (error) {
        console.error('Redis read failed:', error)
    
        return null
      }
    }
    
    export async function safeSetCache(key, value, ttl) {
      try {
        await setCache(key, value, ttl)
      } catch (error) {
        console.error('Redis write failed:', error)
      }
    }
    

    Use the safe methods in your product service:

    export async function getProductById(productId) {
      const cacheKey = `cache:product:${productId}`
    
      const cached = await safeGetCache(cacheKey)
    
      if (cached !== null) {
        return cached
      }
    
      const product = await Product.findById(productId).lean()
    
      if (product) {
        await safeSetCache(
          cacheKey,
          product,
          PRODUCT_CACHE_TTL
        )
      }
    
      return product
    }
    

    Now a Redis read or write failure does not prevent a normal product lookup from succeeding, provided MongoDB is available.

    However, this is only appropriate for a non-critical cache.

    Do not use the same fallback policy for sessions, distributed locks, or security-sensitive rate limits without explicitly evaluating the consequences.

    15.4 Monitor Redis Health

    Useful monitoring signals include:

    • Connection status.
    • Command latency.
    • Cache hit ratio.
    • Cache miss ratio.
    • Memory usage.
    • Eviction count.
    • Expired key count.
    • Connection count.
    • Error rate.

    You should also monitor the underlying database because cache failures may increase database traffic.

    16. Choosing the Right Cache TTL

    TTL selection is one of the most important caching decisions.

    A TTL that is too short reduces the cache hit ratio.

    A TTL that is too long increases the possibility of stale responses.

    Consider these example policies:

    Data typeExample TTLReason
    Public categories30 minutesChanges infrequently
    Product descriptions5 minutesModerate freshness requirements
    Public user profiles2 minutesChanges occasionally
    Temporary verification dataBusiness-defined short lifetimeTime-sensitive
    Frequently changing stockVery short or no cacheAccuracy matters

    These are illustrative values, not universal recommendations.

    A good TTL should account for:

    • How frequently data changes.
    • How many requests read the data.
    • How costly the database query is.
    • How stale the application can tolerate the response becoming.
    • Whether explicit invalidation exists.

    For some information, caching may be inappropriate.

    For example, financial balances and inventory reservations often require stronger consistency guarantees than ordinary product descriptions.

    17. Avoiding Common Redis Mistakes

    Mistake 1: Caching Everything

    Not every database query needs Redis.

    Caching data that is rarely requested can waste memory and add complexity.

    Better approach: Cache frequently accessed data where measurement demonstrates a meaningful benefit.

    Mistake 2: Using Redis as the Primary Database Without a Reason

    A cache is not automatically a durable source of truth.

    Better approach: Keep permanent application records in the database designed for that purpose, unless you have deliberately designed a Redis-backed persistence architecture.

    Mistake 3: Forgetting Cache Invalidation

    Cached records can become outdated after updates or deletions.

    Better approach: Design invalidation as part of every relevant write operation.

    Mistake 4: Using KEYS in Production

    Scanning a large Redis keyspace with KEYS can block the server.

    Better approach: Use SCAN for incremental iteration and avoid broad deletion where possible.

    Mistake 5: Creating a Redis Connection for Every Request

    This introduces unnecessary connection overhead and resource consumption.

    Better approach: Reuse a properly managed Redis client.

    Mistake 6: Caching Private Responses Under Shared Keys

    Two users might receive the same cached response even though they should see different data.

    Better approach: Design keys around the actual authorization and response scope, and authenticate and authorize before returning private cached information.

    Mistake 7: Ignoring Memory Limits

    Redis stores data in memory, and unrestricted cache growth can create operational problems.

    Better approach: Set memory limits, choose an appropriate eviction policy, monitor memory usage, and use TTLs for temporary data.

    Mistake 8: Ignoring Cache Stampedes

    Many simultaneous misses can overload the database.

    Better approach: Use TTL jitter, request coalescing, or a distributed single-flight strategy when required.

    18. Redis Deployment and Production Configuration

    A local Redis instance is suitable for development, but production requires additional planning.

    Consider:

    Network Security

    • Keep Redis on a private network.
    • Restrict access to application servers.
    • Use authentication and TLS where appropriate.
    • Never expose an unauthenticated Redis instance publicly.

    Memory Management

    Configure appropriate memory limits and an eviction policy.

    For a cache workload, policies such as allkeys-lru or allkeys-lfu may be appropriate depending on access patterns.

    However, do not apply a cache eviction policy blindly to a Redis instance that also stores persistent or security-critical data.

    Separate workloads when their retention and availability requirements differ.

    Persistence

    Redis supports persistence mechanisms such as RDB snapshots and AOF.

    For a disposable cache, losing cached values may simply cause cache misses.

    For sessions, queues, or other important data, persistence and recovery requirements deserve more attention.

    Do not assume persistence alone provides high availability or backup guarantees.

    High Availability

    For applications with stricter availability requirements, consider:

    • Managed Redis-compatible services.
    • Replication.
    • Sentinel or cluster configurations where appropriate.
    • Backups and recovery testing.
    • Connection and failover behavior.

    A single Redis process on the same EC2 instance as your application can become a shared failure point.

    19. When Should You Use Redis?

    Redis is useful when an application needs fast shared access to temporary or frequently reused information.

    Common use cases include:

    Use caseWhy Redis helps
    API response cachingReduces repeated database queries
    Session storageShares session state between instances
    Rate limitingMaintains distributed counters
    LeaderboardsUses sorted sets for rankings
    Temporary verification codesSupports expiring values
    Job queuesSupports queue-related workflows
    Real-time countersProvides fast atomic increments
    Distributed coordinationProvides shared locking and signaling primitives

    Redis may not be necessary when:

    • The application has very little traffic.
    • Database queries are already inexpensive.
    • Data changes too frequently to benefit from caching.
    • A local cache is sufficient for a single-process tool.
    • Operational complexity outweighs the expected benefit.

    Start with the simplest architecture that meets the application's requirements.

    Introduce Redis when there is a clear need.

    20. Production Readiness Checklist

    Before deploying Redis caching in a production Node.js application, review these points.

    Redis connection

    • Redis client is initialized once.
    • Connection errors are handled.
    • Reconnection behavior is understood.
    • Shutdown closes the client properly.
    • Redis is accessible only through trusted network paths.

    Caching

    • Cache keys follow a consistent naming convention.
    • Appropriate TTL values are configured.
    • Cache invalidation is implemented.
    • Cache misses are handled correctly.
    • Missing database records have a deliberate caching policy.
    • Sensitive information is not accidentally shared.

    Reliability

    • Cache failures have an explicit fail-open or fail-closed policy.
    • Cache stampedes are considered.
    • Memory usage is monitored.
    • Eviction policy matches the workload.
    • Database fallback capacity is understood.

    Security

    • Redis is not publicly exposed.
    • Authentication and TLS are configured where appropriate.
    • Private data is isolated by user or tenant.
    • Rate limiting uses trusted client identity.
    • Redis credentials are stored securely.

    Monitoring

    • Cache hit and miss rates are measured.
    • Redis latency is monitored.
    • Memory and eviction metrics are monitored.
    • Connection errors are logged.
    • MongoDB load is monitored alongside Redis.

    Conclusion

    Redis is a powerful addition to a Node.js backend when used for the right workloads.

    With cache-aside architecture, Express can check Redis before querying MongoDB, reducing repeated database operations and improving response times for frequently accessed data.

    However, successful caching requires more than storing JSON under a Redis key.

    You must also consider TTL, invalidation, cache stampedes, data consistency, memory limits, failure handling, and security.

    Start with a small number of high-value cache candidates, measure the results, and expand only when the improvement justifies the additional complexity.

    The most important principle is simple: MongoDB remains the source of truth, while Redis accelerates access to data that can safely be cached.

    Official References

    1. Redis Documentation
    2. Redis — Cache-Aside Pattern
    3. Redis — Cache-Aside with Node.js
    4. Redis — Node.js Client
    5. Redis — Node.js Connection
    6. Redis — Rate Limiting
    7. Redis — Key Expiration
    8. Redis — SCAN
    9. Express Rate Limit
    10. MongoDB Node.js Driver Documentation
    11. Connect Redis

    Enjoyed this read?

    Keep the conversation going.

    Follow along for more practical development notes, or reach out to talk about a project.

    Keep exploring

    Related articles

    More guides connected by the topics in this article.

    Browse the journal