ianyimi

payloadcms redis plugin

by ianyimi
Databases & data
v3
^3.37.0
MIT

Overview

Summary generated from the README

Wraps Payload's database operations with a Redis cache built on ioredis. Read operations such as find, findOne, count and findGlobal are served from Redis when enabled, and write operations invalidate related keys by pattern. Caching is configured per collection or global with custom TTLs, and requires Payload 3.37 or higher and a Redis server.

Features

  • Caches read operations like find, findOne, count, findGlobal and queryDrafts
  • Invalidates related cache entries by pattern after create, update and delete
  • Per-collection and per-global TTL and skip settings
  • Per-request override of skip, TTL and key through request context
  • Custom cache key generation and key prefix
  • Debug logging for cache hits, misses and invalidations

Use cases

  • Reduce database load on read-heavy blogs or storefronts by caching product and post queries
  • Cache rarely changing globals such as site settings for long periods
  • Bypass the cache for specific requests that must always read fresh data

From the author

Redis Plugin for PayloadCMS v3

Installation

npm i payloadcms-redis-plugin

15

Stars

1

Forks

1

Open Issues

1 years ago

Last Updated

185

Weekly Downloads

v0.2.17

npm Version

88.4 KB

Unpacked Size

1

Dependencies

GitHub stars

150 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 202615
Dec 4, 202615
Dec 3, 202615
Dec 2, 202615
Dec 1, 202615
Nov 30, 202615
Nov 29, 202615
Nov 28, 202615
Nov 27, 202615
Nov 26, 202615
Nov 25, 202615
Nov 24, 202615
Nov 23, 202615
Nov 22, 202615
Nov 21, 202615
Nov 20, 202615
Nov 19, 202615
Nov 18, 202615
Nov 17, 202615
Nov 16, 202615
Nov 15, 202615
Nov 14, 202615
Nov 13, 202615
Nov 12, 202615
Nov 11, 202615
Nov 10, 202615
Nov 9, 202615
Nov 8, 202615
Nov 7, 202615
Nov 6, 202615
Nov 5, 202615
Nov 4, 202615
Nov 3, 202615
Nov 2, 202615
Nov 1, 202615
Oct 31, 202615
Oct 30, 202615
Oct 29, 202615
Oct 28, 202615
Oct 27, 202615
Oct 26, 202615
Oct 25, 202615
Oct 24, 202615
Oct 23, 202615
Oct 22, 202615
Oct 21, 202615
Oct 20, 202615
Oct 19, 202615
Oct 18, 202615
Oct 17, 202615
Oct 16, 202615
Oct 15, 202615
Oct 14, 202615
Oct 13, 202615
Oct 12, 202615
Oct 11, 202615
Oct 10, 202615
Oct 9, 202615
Oct 8, 202615
Oct 7, 202615
Oct 6, 202615
Oct 5, 202615
Oct 4, 202615
Oct 3, 202615
Oct 2, 202615
Oct 1, 202615
Sep 30, 202615
Sep 29, 202615
Sep 28, 202615
Sep 27, 202615
Sep 26, 202615
Sep 25, 202615
Sep 24, 202615
Sep 23, 202615
Sep 22, 202615
Sep 21, 202615
Sep 20, 202615
Sep 19, 202615
Sep 18, 202615
Sep 17, 202615
Sep 16, 202615
Sep 15, 202615
Sep 14, 202615
Sep 13, 202615
Sep 12, 202615
Sep 11, 202615
Sep 10, 202615
Sep 9, 202615
Sep 8, 202615
Sep 7, 202615
Sep 6, 202615
npm weekly downloads

139+15 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026139
Dec 4, 2026153
Dec 3, 2026150
Dec 2, 2026123
Dec 1, 2026124
Nov 30, 2026134
Nov 29, 2026150
Nov 28, 2026139
Nov 27, 2026113
Nov 26, 2026113
Nov 25, 2026114
Nov 24, 2026113
Nov 23, 2026111
Nov 22, 202689
Nov 21, 2026100
Nov 20, 2026114
Nov 19, 2026121
Nov 18, 2026123
Nov 17, 2026118
Nov 16, 2026115
Nov 15, 2026127
Nov 14, 2026153
Nov 13, 2026154
Nov 12, 2026172
Nov 11, 2026176
Nov 10, 2026181
Nov 9, 2026178
Nov 8, 2026181
Nov 7, 2026149
Nov 6, 2026136
Nov 5, 2026147
Nov 4, 2026169
Nov 3, 2026178
Nov 2, 2026339
Nov 1, 2026323
Oct 31, 2026331
Oct 30, 2026323
Oct 29, 2026272
Oct 28, 2026235
Oct 27, 2026223
Oct 26, 202657
Oct 25, 202683
Oct 24, 202677
Oct 23, 202660
Oct 22, 2026138
Oct 21, 2026153
Oct 20, 2026150
Oct 19, 2026155
Oct 18, 2026128
Oct 17, 2026118
Oct 16, 2026127
Oct 15, 202667
Oct 14, 202693
Oct 13, 202699
Oct 12, 2026138
Oct 11, 2026152
Oct 10, 2026159
Oct 9, 2026160
Oct 8, 2026148
Oct 7, 2026113
Oct 6, 2026106
Oct 5, 202665
Oct 4, 202664
Oct 3, 202670
Oct 2, 202690
Oct 1, 2026101
Sep 30, 2026105
Sep 29, 2026128
Sep 28, 2026147
Sep 27, 2026142
Sep 26, 2026135
Sep 25, 2026141
Sep 24, 2026147
Sep 23, 2026154
Sep 22, 2026154
Sep 21, 2026146
Sep 20, 2026151
Sep 19, 2026178
Sep 18, 2026170
Sep 17, 2026177
Sep 16, 2026173
Sep 15, 2026150
Sep 14, 2026149
Sep 13, 2026173
Sep 12, 2026178
Sep 11, 2026166
Sep 10, 2026168
Sep 9, 2026176
Sep 8, 2026176
Sep 7, 2026164
Sep 6, 2026124

Each point is npm's rolling 7-day download count.

Health Score

42/100Fair

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1083913111-root.svg)](https://payloaddirectory.dev/plugins/1083913111-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1083913111-root"><img src="https://payloaddirectory.dev/badge/1083913111-root.svg" alt="Payload Directory"></a>
Updated Oct 31, 2025Created Oct 27, 2025Published Oct 31, 2025

README

PayloadCMS Redis Plugin

npm version License: MIT

A transparent Redis caching layer plugin for Payload CMS v3 that automatically caches database queries to improve performance.

Features

  • Automatic Query Caching - Transparently caches all read operations (find, findOne, count, etc.)
  • Smart Invalidation - Automatically invalidates cache on write operations (create, update, delete)
  • Flexible Configuration - Enable caching per collection or globally with custom TTL
  • Per-Request Override - Control cache behavior on individual requests
  • Custom Cache Keys - Generate custom cache keys based on your needs
  • Pattern-Based Invalidation - Invalidate related cache entries using Redis patterns
  • Debug Mode - Optional logging for cache hits, misses, and invalidations
  • Zero Breaking Changes - Works seamlessly with existing Payload applications

Installation

npm install payloadcms-redis-plugin ioredis
# or
yarn add payloadcms-redis-plugin ioredis
# or
pnpm add payloadcms-redis-plugin ioredis

Requirements

  • Payload CMS v3.37.0 or higher
  • Node.js 18.20.2+ or 20.9.0+
  • Redis server

Quick Start

Basic Setup

import { buildConfig } from 'payload'
import { redisCache } from 'payloadcms-redis-plugin'

export default buildConfig({
  plugins: [
    redisCache({
      // Connect via URL
      redis: {
        url: 'redis://localhost:6379',
      },
      // Enable caching for specific collections
      collections: {
        posts: true,
        articles: true,
      },
    }),
  ],
  // ... rest of your config
})

Using Existing Redis Client

import { Redis } from 'ioredis'
import { redisCache } from 'payloadcms-redis-plugin'

const redisClient = new Redis({
  host: 'localhost',
  port: 6379,
  password: 'your-password',
  db: 0,
})

export default buildConfig({
  plugins: [
    redisCache({
      // Use existing client
      redis: {
        client: redisClient,
      },
      collections: {
        posts: true,
      },
    }),
  ],
})

Configuration

Plugin Options

type RedisPluginConfig = {
  // Redis connection (provide either client or url)
  redis: { client: Redis; url?: never } | { client?: never; url: string }

  // Collections to cache
  collections?: Partial<Record<CollectionSlug, CacheOptions | true>>

  // Globals to cache
  globals?: Partial<Record<GlobalSlug, CacheOptions | true>>

  // Enable debug logging
  debug?: boolean

  // Default cache behavior
  defaultCacheOptions?: {
    generateKey?: (operation: string, args: DBOperationArgs) => string
    keyPrefix?: string
    ttl?: number // in seconds, default: 300 (5 minutes)
  }
}

Cache Options

type CacheOptions = {
  key?: string // Custom cache key override
  skip?: boolean // Skip cache for this collection/query
  tags?: string[] // Tags for grouped invalidation (future feature)
  ttl?: number // Time-to-live in seconds
}

Advanced Configuration

redisCache({
  redis: {
    url: process.env.REDIS_URL,
  },

  // Configure collections with custom TTL
  collections: {
    posts: {
      ttl: 600, // Cache posts for 10 minutes
      skip: false,
    },
    articles: {
      ttl: 1800, // Cache articles for 30 minutes
    },
    users: true, // Use default TTL (5 minutes)
  },

  // Cache global configurations
  globals: {
    settings: true,
  },

  // Custom default options
  defaultCacheOptions: {
    keyPrefix: 'myapp',
    ttl: 300,
    generateKey: (operation, args) => {
      // Custom key generation logic
      const { slug, where, locale } = args
      return `${slug}:${operation}:${locale || 'default'}:${JSON.stringify(where)}`
    },
  },

  // Enable debug logging
  debug: true,
})

Usage

Per-Request Cache Control

Override cache behavior for individual requests:

// Skip cache for a specific query
const freshPosts = await payload.find({
  collection: 'posts',
  req: {
    context: {
      cache: {
        skip: true, // Bypass cache, always hit database
      },
    },
  },
})

// Custom TTL for a specific query
const shortLivedPosts = await payload.find({
  collection: 'posts',
  req: {
    context: {
      cache: {
        ttl: 60, // Cache for 1 minute only
      },
    },
  },
})

// Custom cache key
const customCachedPosts = await payload.find({
  collection: 'posts',
  req: {
    context: {
      cache: {
        key: 'posts:featured',
      },
    },
  },
})

Cached Operations

The following database operations are automatically cached:

Read Operations (cached before hitting database):

  • find - Query collections with pagination
  • findOne - Query single document by ID
  • findGlobal - Query global configurations
  • findGlobalVersions - Query global version history
  • count - Count documents
  • countVersions - Count document versions
  • countGlobalVersions - Count global versions
  • queryDrafts - Query draft documents

Write Operations (invalidate cache after database update):

  • create - Create new document
  • createMany - Batch create
  • updateOne - Update single document
  • updateMany - Batch update
  • deleteOne - Delete single document
  • deleteMany - Batch delete
  • upsert - Create or update
  • updateGlobal - Update global config
  • updateGlobalVersion - Update global version
  • deleteVersions - Delete document versions

How It Works

Cache Key Generation

By default, cache keys are generated using MD5 hashing:

[prefix]:[slug]:[operation]:[md5-hash]

The hash includes: { slug, locale, operation, where }

Example keys:

posts:find:a1b2c3d4e5f6g7h8
myapp:articles:count:x9y8z7w6v5u4t3s2

Cache Flow

Read Operations:

Request → Check cache config → Check skip flag
  ↓ (cache enabled)
  Check Redis → HIT: Return cached → MISS: Hit DB → Store in Redis → Return
  ↓ (cache disabled/skipped)
  Hit DB directly

Write Operations:

Request → Execute on DB → Get cache config → Check skip flag
  ↓ (cache enabled)
  Invalidate pattern → Return result
  ↓ (cache disabled/skipped)
  Return result directly

Automatic Invalidation

When data changes, the plugin automatically invalidates related cache entries using pattern matching:

// Creating a post invalidates all post queries
await payload.create({
  collection: 'posts',
  data: { title: 'New Post' },
})
// Invalidates: posts:*, myapp:*:posts:*, etc.

// Updating an article invalidates all article queries
await payload.update({
  collection: 'articles',
  id: '123',
  data: { title: 'Updated' },
})
// Invalidates: articles:*, myapp:*:articles:*, etc.

Debug Mode

Enable debug logging to monitor cache behavior:

redisCache({
  redis: { url: 'redis://localhost:6379' },
  collections: { posts: true },
  debug: true,
})

Console output:

[RedisPlugin] [find] [posts] Cache HIT
[RedisPlugin] [find] [articles] Cache MISS
[RedisPlugin] [create] [posts] Invalidating pattern: posts:*
[RedisPlugin] [update] [posts] Cache SKIP (per-request)

TypeScript Support

The plugin includes full TypeScript definitions and extends Payload's RequestContext type:

declare module 'payload' {
  export interface RequestContext {
    cache?: {
      key?: string
      skip?: boolean
      tags?: string[]
      ttl?: number
    }
  }
}

Performance Considerations

  • Default TTL: 5 minutes (300 seconds)
  • Pattern Matching: Uses redis.keys() for invalidation (consider SCAN in production with large keyspaces)
  • Silent Failures: Cache errors don't break database queries
  • Memory: Monitor Redis memory usage based on your cache strategy
  • Expiration: Redis automatically removes expired keys

Development

# Install dependencies
pnpm install

# Run development server
pnpm dev

# Run tests
pnpm test

# Build plugin
pnpm build

# Lint code
pnpm lint

Examples

E-commerce Site

redisCache({
  redis: { url: process.env.REDIS_URL },
  collections: {
    products: { ttl: 3600 }, // Cache products for 1 hour
    categories: { ttl: 7200 }, // Cache categories for 2 hours
    orders: { skip: true }, // Never cache orders
    customers: { ttl: 600 }, // Cache customers for 10 minutes
  },
  globals: {
    siteSettings: { ttl: 86400 }, // Cache site settings for 24 hours
  },
})

Blog Platform

redisCache({
  redis: { url: process.env.REDIS_URL },
  collections: {
    posts: { ttl: 1800 }, // Cache posts for 30 minutes
    authors: { ttl: 3600 }, // Cache authors for 1 hour
    comments: { ttl: 300 }, // Cache comments for 5 minutes
  },
  defaultCacheOptions: {
    keyPrefix: 'blog',
    ttl: 600,
  },
  debug: process.env.NODE_ENV === 'development',
})

Troubleshooting

Redis Connection Issues

// Test Redis connection
const redis = new Redis('redis://localhost:6379')
await redis.ping() // Should return 'PONG'

Cache Not Working

  1. Enable debug mode to see cache behavior
  2. Verify collection/global is configured for caching
  3. Check if skip: true is set
  4. Ensure Redis server is running and accessible

High Memory Usage

  1. Reduce TTL values
  2. Be selective about which collections to cache
  3. Monitor Redis memory with redis-cli info memory
  4. Consider using Redis maxmemory policies

Contributing

Contributions are welcome! Please see the GitHub repository for issues and pull requests.

License

MIT

Author

Isaiah Anyimi pls hire me

Similar plugins