Skip to main content
hooksSource-backedReview first Safety Privacy
Redis logo

Redis Cache Invalidator - Hooks

Automatically clears relevant Redis cache keys when data model files are modified.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Brand
Redis
Brand domain
redis.io
Brand asset source
brandfetch
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
4 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/bin/bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

echo "🔄 Redis Cache Invalidator - Analyzing file changes..."
echo "📄 File: $FILE_PATH"

# Check if this is a model or data file that should trigger cache invalidation
if [[ "$FILE_PATH" == *models/*.js ]] || [[ "$FILE_PATH" == *models/*.py ]] || [[ "$FILE_PATH" == *models/*.ts ]] || [[ "$FILE_PATH" == *schemas/*.* ]] || [[ "$FILE_PATH" == *entities/*.* ]]; then
    
    MODEL_NAME=$(basename "${FILE_PATH%.*}")
    echo "📊 Model detected: $MODEL_NAME"
    
    # Check if Redis CLI is available
    if ! command -v redis-cli >/dev/null 2>&1; then
        echo "⚠️ redis-cli not found - please install Redis CLI tools"
        echo "💡 Install with: apt-get install redis-tools (Ubuntu) or brew install redis (macOS)"
        exit 0
    fi
    
    # Test Redis connection
    if ! redis-cli ping >/dev/null 2>&1; then
        echo "⚠️ Redis server not accessible - skipping cache invalidation"
        echo "💡 Ensure Redis server is running and accessible"
        exit 0
    fi
    
    echo "🔍 Scanning for cache keys related to: $MODEL_NAME"
    
    # Find cache keys related to this model
    CACHE_KEYS=$(redis-cli --scan --pattern "*${MODEL_NAME}*" 2>/dev/null)
    
    if [ -n "$CACHE_KEYS" ]; then
        KEY_COUNT=$(echo "$CACHE_KEYS" | wc -l)
        echo "🗑️ Found $KEY_COUNT cache keys to invalidate:"
        
        # Show first few keys for confirmation
        echo "$CACHE_KEYS" | head -5 | while read -r key; do
            echo "  • $key"
        done
        
        if [ "$KEY_COUNT" -gt 5 ]; then
            echo "  ... and $((KEY_COUNT - 5)) more keys"
        fi
        
        # Delete the keys
        echo "$CACHE_KEYS" | xargs -r redis-cli DEL >/dev/null 2>&1
        echo "✅ Invalidated $KEY_COUNT cache keys for model: $MODEL_NAME"
    else
        echo "ℹ️ No cache keys found for model: $MODEL_NAME"
    fi
    
    # Additional patterns to check
    echo "🔍 Checking additional cache patterns..."
    
    # Check for API route caches
    API_KEYS=$(redis-cli --scan --pattern "api:*${MODEL_NAME}*" 2>/dev/null)
    if [ -n "$API_KEYS" ]; then
        API_COUNT=$(echo "$API_KEYS" | wc -l)
        echo "$API_KEYS" | xargs -r redis-cli DEL >/dev/null 2>&1
        echo "✅ Invalidated $API_COUNT API cache keys"
    fi
    
    # Check for query result caches
    QUERY_KEYS=$(redis-cli --scan --pattern "query:*${MODEL_NAME}*" 2>/dev/null)
    if [ -n "$QUERY_KEYS" ]; then
        QUERY_COUNT=$(echo "$QUERY_KEYS" | wc -l)
        echo "$QUERY_KEYS" | xargs -r redis-cli DEL >/dev/null 2>&1
        echo "✅ Invalidated $QUERY_COUNT query cache keys"
    fi
    
    # Check current Redis stats
    echo ""
    echo "📊 Redis Cache Statistics:"
    TOTAL_KEYS=$(redis-cli DBSIZE 2>/dev/null || echo "unknown")
    MEMORY_USAGE=$(redis-cli INFO memory 2>/dev/null | grep used_memory_human | cut -d: -f2 | tr -d '\r' || echo "unknown")
    echo "  • Total keys: $TOTAL_KEYS"
    echo "  • Memory usage: $MEMORY_USAGE"
    
    echo ""
    echo "💡 Cache Invalidation Tips:"
    echo "  • Use consistent cache key naming patterns"
    echo "  • Consider cache TTL for automatic expiration"
    echo "  • Monitor cache hit/miss ratios"
    echo "  • Use Redis keyspace notifications for advanced invalidation"
    
    echo ""
    echo "🎯 Cache invalidation complete!"
    
elif [[ "$FILE_PATH" == *config/*.* ]] || [[ "$FILE_PATH" == *.env ]]; then
    echo "⚙️ Configuration file detected - consider full cache flush if needed"
    echo "💡 Run 'redis-cli FLUSHDB' manually if configuration affects cached data"
    
else
    echo "ℹ️ File does not require cache invalidation: $FILE_PATH"
fi

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/redis-cache-invalidator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

Features

  • Intelligent cache key invalidation including cache key detection (intelligent cache key detection with pattern matching, cache key scanning with SCAN command, cache key filtering with wildcard patterns, cache key validation with key existence checking), cache key invalidation (selective cache key deletion with DEL command, batch cache key deletion with pipeline operations, cache key pattern matching with wildcard patterns, cache key namespace management with key prefixes), cache key management (cache key organization with consistent naming, cache key indexing with key patterns, cache key lifecycle management with TTL, cache key monitoring with key statistics), and cache key optimization (cache key optimization with efficient patterns, cache key compression with key naming, cache key deduplication with key validation, cache key performance with efficient operations)
  • Model-based cache clearing including model detection (automatic model file detection with path patterns, model name extraction from file paths, model type detection with file extensions, model change detection with file modification), cache clearing (model-specific cache clearing with pattern matching, related cache clearing with dependency tracking, cascade cache clearing with related models, selective cache clearing with targeted invalidation), cache patterns (cache key pattern matching with wildcard patterns, cache namespace patterns with key prefixes, cache hierarchy patterns with nested keys, cache relationship patterns with related keys), and cache consistency (cache consistency maintenance with invalidation, cache coherence with related caches, cache synchronization with data models, cache integrity with validation)
  • Pattern matching for cache keys including pattern detection (cache key pattern detection with wildcard matching, pattern-based cache key scanning with SCAN command, pattern-based cache key filtering with pattern matching, pattern-based cache key validation with pattern validation), pattern matching (wildcard pattern matching with * and ? patterns, regex pattern matching with pattern matching, namespace pattern matching with key prefixes, hierarchical pattern matching with nested patterns), pattern optimization (pattern matching optimization with efficient patterns, pattern caching with pattern compilation, pattern performance with optimized matching, pattern scalability with large key sets), and pattern management (pattern management with pattern libraries, pattern documentation with pattern descriptions, pattern versioning with pattern evolution, pattern testing with pattern validation)
  • Safe asynchronous cache flushing including safe flushing (safe cache flushing with validation, atomic cache operations with transaction support, idempotent cache operations with safe retries, error handling with graceful degradation), asynchronous operations (asynchronous cache invalidation with background processing, non-blocking cache operations with async execution, concurrent cache operations with thread safety, parallel cache operations with performance optimization), cache safety (cache operation safety with validation, cache data safety with backup, cache consistency safety with transactions, cache performance safety with rate limiting), and cache monitoring (cache operation monitoring with logging, cache performance monitoring with metrics, cache error monitoring with error tracking, cache health monitoring with health checks)
  • Multi-language model support including language support (multi-language model support with language detection, language-specific cache patterns with language prefixes, language-specific cache keys with language suffixes, language-specific cache invalidation with language filtering), model languages (JavaScript/TypeScript model support, Python model support, Ruby model support, Go model support), model formats (JSON schema support, YAML schema support, SQL schema support, GraphQL schema support), and model integration (model integration with ORMs, model integration with frameworks, model integration with APIs, model integration with databases)
  • Cache consistency maintenance including consistency management (cache consistency management with invalidation strategies, cache coherence with data models, cache synchronization with database changes, cache integrity with validation), consistency strategies (immediate invalidation with real-time clearing, lazy invalidation with on-demand clearing, time-based invalidation with TTL expiration, event-based invalidation with change events), consistency monitoring (cache consistency monitoring with validation, cache coherence monitoring with checks, cache synchronization monitoring with tracking, cache integrity monitoring with verification), and consistency reporting (cache consistency reporting with reports, cache coherence reporting with analysis, cache synchronization reporting with statistics, cache integrity reporting with validation)
  • Redis connection and management including connection management (Redis connection validation with ping command, Redis connection pooling with connection reuse, Redis connection retry with automatic retry, Redis connection monitoring with health checks), Redis operations (Redis SCAN command for key scanning, Redis DEL command for key deletion, Redis pipeline for batch operations, Redis transaction for atomic operations), Redis monitoring (Redis statistics with DBSIZE and INFO, Redis memory monitoring with memory usage, Redis performance monitoring with latency tracking, Redis health monitoring with health checks), and Redis configuration (Redis configuration management with redis.conf, Redis database selection with -n flag, Redis authentication with AUTH command, Redis cluster support with cluster mode)
  • Development workflow integration including continuous invalidation (real-time cache invalidation on model changes, immediate cache clearing on file modifications, automatic cache synchronization on data model updates, seamless cache integration with development workflow), workflow automation (automated cache invalidation without manual intervention, cache clearing automation with automatic clearing, cache consistency automation with automatic synchronization), and workflow optimization (cache change detection with change tracking, incremental cache invalidation with optimization, cache consistency maintenance with consistency checks)

Use Cases

  • Invalidate cache when data models are modified automatically detecting model file changes, scanning for related cache keys, and invalidating matching cache entries to maintain cache consistency
  • Maintain cache consistency in Redis automatically synchronizing cache with data model changes, ensuring cache coherence across cache layers, and preventing stale data in cache
  • Clear related cache entries automatically detecting related cache keys, clearing dependent cache entries, and maintaining cache relationships
  • Prevent stale data in cache after model changes automatically invalidating stale cache entries, ensuring fresh data in cache, and maintaining data integrity
  • Optimize cache management workflow automatically managing cache invalidation, reducing manual cache management, and streamlining cache operations
  • Development workflow integration seamlessly integrating Redis cache invalidation into development workflows without manual cache clearing or cache management

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/redis-cache-invalidator.sh
  3. Make executable: chmod +x .claude/hooks/redis-cache-invalidator.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • Redis server running and accessible
  • redis-cli installed (apt-get install redis-tools or brew install redis)
  • jq (optional, for JSON parsing)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/redis-cache-invalidator.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Hook Script

#!/bin/bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

echo "🔄 Redis Cache Invalidator - Analyzing file changes..."
echo "📄 File: $FILE_PATH"

# Check if this is a model or data file that should trigger cache invalidation
if [[ "$FILE_PATH" == *models/*.js ]] || [[ "$FILE_PATH" == *models/*.py ]] || [[ "$FILE_PATH" == *models/*.ts ]] || [[ "$FILE_PATH" == *schemas/*.* ]] || [[ "$FILE_PATH" == *entities/*.* ]]; then

    MODEL_NAME=$(basename "${FILE_PATH%.*}")
    echo "📊 Model detected: $MODEL_NAME"

    # Check if Redis CLI is available
    if ! command -v redis-cli >/dev/null 2>&1; then
        echo "⚠️ redis-cli not found - please install Redis CLI tools"
        echo "💡 Install with: apt-get install redis-tools (Ubuntu) or brew install redis (macOS)"
        exit 0
    fi

    # Test Redis connection
    if ! redis-cli ping >/dev/null 2>&1; then
        echo "⚠️ Redis server not accessible - skipping cache invalidation"
        echo "💡 Ensure Redis server is running and accessible"
        exit 0
    fi

    echo "🔍 Scanning for cache keys related to: $MODEL_NAME"

    # Find cache keys related to this model
    CACHE_KEYS=$(redis-cli --scan --pattern "*${MODEL_NAME}*" 2>/dev/null)

    if [ -n "$CACHE_KEYS" ]; then
        KEY_COUNT=$(echo "$CACHE_KEYS" | wc -l)
        echo "🗑️ Found $KEY_COUNT cache keys to invalidate:"

        # Show first few keys for confirmation
        echo "$CACHE_KEYS" | head -5 | while read -r key; do
            echo "  • $key"
        done

        if [ "$KEY_COUNT" -gt 5 ]; then
            echo "  ... and $((KEY_COUNT - 5)) more keys"
        fi

        # Delete the keys
        echo "$CACHE_KEYS" | xargs -r redis-cli DEL >/dev/null 2>&1
        echo "✅ Invalidated $KEY_COUNT cache keys for model: $MODEL_NAME"
    else
        echo "ℹ️ No cache keys found for model: $MODEL_NAME"
    fi

    # Additional patterns to check
    echo "🔍 Checking additional cache patterns..."

    # Check for API route caches
    API_KEYS=$(redis-cli --scan --pattern "api:*${MODEL_NAME}*" 2>/dev/null)
    if [ -n "$API_KEYS" ]; then
        API_COUNT=$(echo "$API_KEYS" | wc -l)
        echo "$API_KEYS" | xargs -r redis-cli DEL >/dev/null 2>&1
        echo "✅ Invalidated $API_COUNT API cache keys"
    fi

    # Check for query result caches
    QUERY_KEYS=$(redis-cli --scan --pattern "query:*${MODEL_NAME}*" 2>/dev/null)
    if [ -n "$QUERY_KEYS" ]; then
        QUERY_COUNT=$(echo "$QUERY_KEYS" | wc -l)
        echo "$QUERY_KEYS" | xargs -r redis-cli DEL >/dev/null 2>&1
        echo "✅ Invalidated $QUERY_COUNT query cache keys"
    fi

    # Check current Redis stats
    echo ""
    echo "📊 Redis Cache Statistics:"
    TOTAL_KEYS=$(redis-cli DBSIZE 2>/dev/null || echo "unknown")
    MEMORY_USAGE=$(redis-cli INFO memory 2>/dev/null | grep used_memory_human | cut -d: -f2 | tr -d '\r' || echo "unknown")
    echo "  • Total keys: $TOTAL_KEYS"
    echo "  • Memory usage: $MEMORY_USAGE"

    echo ""
    echo "💡 Cache Invalidation Tips:"
    echo "  • Use consistent cache key naming patterns"
    echo "  • Consider cache TTL for automatic expiration"
    echo "  • Monitor cache hit/miss ratios"
    echo "  • Use Redis keyspace notifications for advanced invalidation"

    echo ""
    echo "🎯 Cache invalidation complete!"

elif [[ "$FILE_PATH" == *config/*.* ]] || [[ "$FILE_PATH" == *.env ]]; then
    echo "⚙️ Configuration file detected - consider full cache flush if needed"
    echo "💡 Run 'redis-cli FLUSHDB' manually if configuration affects cached data"

else
    echo "ℹ️ File does not require cache invalidation: $FILE_PATH"
fi

exit 0

Examples

Redis Cache Invalidator Hook Script

Complete hook script that invalidates Redis cache keys when model files are modified

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
if [[ "$FILE_PATH" == *models/*.js ]] || [[ "$FILE_PATH" == *models/*.ts ]]; then
  MODEL_NAME=$(basename "${FILE_PATH%.*}")
  if command -v redis-cli >/dev/null 2>&1; then
    if redis-cli ping >/dev/null 2>&1; then
      CACHE_KEYS=$(redis-cli --scan --pattern "*${MODEL_NAME}*" 2>/dev/null)
      if [ -n "$CACHE_KEYS" ]; then
        echo "$CACHE_KEYS" | xargs -r redis-cli DEL >/dev/null 2>&1
        echo "✅ Invalidated cache keys for: $MODEL_NAME"
      fi
    fi
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable Redis cache invalidation

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/redis-cache-invalidator.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Multi-Pattern Cache Invalidation

Enhanced hook script with multiple cache pattern matching

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *models/* ]]; then
  MODEL_NAME=$(basename "${FILE_PATH%.*}")
  if command -v redis-cli >/dev/null 2>&1 && redis-cli ping >/dev/null 2>&1; then
    echo "🔍 Scanning for cache keys related to: $MODEL_NAME"
    redis-cli --scan --pattern "*${MODEL_NAME}*" | while read -r key; do
      redis-cli DEL "$key" >/dev/null 2>&1
      echo "  • Deleted: $key"
    done
    redis-cli --scan --pattern "api:*${MODEL_NAME}*" | xargs -r redis-cli DEL >/dev/null 2>&1
    redis-cli --scan --pattern "query:*${MODEL_NAME}*" | xargs -r redis-cli DEL >/dev/null 2>&1
    echo "✅ Cache invalidation complete"
  fi
fi
exit 0

Batch Cache Invalidation with Pipeline

Enhanced hook script with Redis pipeline for efficient batch operations

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *models/* ]]; then
  MODEL_NAME=$(basename "${FILE_PATH%.*}")
  if command -v redis-cli >/dev/null 2>&1 && redis-cli ping >/dev/null 2>&1; then
    redis-cli --scan --pattern "*${MODEL_NAME}*" | redis-cli --pipe >/dev/null 2>&1 <<EOF
$(redis-cli --scan --pattern "*${MODEL_NAME}*" | sed 's/^/DEL /')
EOF
    echo "✅ Batch cache invalidation complete"
  fi
fi
exit 0

Redis Cache Invalidator Configuration

Example configuration for Redis cache invalidator settings

{
  "redis": {
    "host": "localhost",
    "port": 6379,
    "database": 0,
    "patterns": [
      "*{model}*",
      "api:*{model}*",
      "query:*{model}*",
      "cache:*{model}*"
    ],
    "timeout": 5,
    "retry_attempts": 3
  }
}

Troubleshooting

Hook skips invalidation with redis-cli not found warning

Install Redis CLI tools using 'apt-get install redis-tools' (Ubuntu/Debian) or 'brew install redis' (macOS). The hook gracefully exits if Redis tools are unavailable. Verify redis-cli installation. Test with various Redis installations.

Redis server not accessible error during invalidation

Verify Redis is running with 'redis-cli ping'. Check connection settings in redis.conf. The hook tests connectivity before attempting invalidation and exits safely if unreachable. Verify Redis connection. Test with various Redis configurations.

Too many or too few cache keys being invalidated

Review cache key naming patterns. The hook uses wildcard matching on model names. Use consistent prefixes like 'api:', 'query:', 'model:' for precise pattern matching and control. Verify cache key patterns. Test with various cache key naming conventions.

Hook triggers on non-model files causing unnecessary scans

The hook only processes files in /models/, /schemas/, /entities/ directories. Organize your codebase to match these patterns or customize the path matching logic in the script. Verify file path patterns. Test with various project structures.

Cache invalidation completes but stale data persists

Check if your application uses multiple Redis databases (DB0, DB1, etc.) or instances. The hook targets the default database. Use 'redis-cli -n ' to verify which database stores your cache. Verify Redis database selection. Test with various Redis database configurations.

Redis SCAN command is slow on large key sets

SCAN can be slow with millions of keys. Use cursor-based scanning with SCAN cursor COUNT option. Consider using Redis keyspace notifications for event-driven invalidation. Optimize cache key patterns. Test with various key set sizes.

Cache invalidation fails with permission denied errors

Verify Redis user has DEL and SCAN permissions. Check Redis ACL configuration. Ensure Redis connection uses appropriate authentication. Verify Redis permissions. Test with various Redis permission configurations.

Multiple Redis instances or clusters not supported

Hook targets single Redis instance. For clusters, use Redis Cluster mode with redis-cli --cluster option. For multiple instances, configure hook to iterate through instances. Verify Redis topology. Test with various Redis configurations.

Source citations

Add this badge to your README

Show that Redis Cache Invalidator - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/redis-cache-invalidator.svg)](https://heyclau.de/entry/hooks/redis-cache-invalidator)

How it compares

Redis Cache Invalidator - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Next steps differ across entries — use the actions in the table below to copy install commands and source links per resource.

Field

Automatically clears relevant Redis cache keys when data model files are modified.

Open dossier

Detects unused CSS selectors when stylesheets are modified to keep CSS lean using PurgeCSS, PostCSS, and content analysis. This hook runs on CSS/SCSS file write/edit operations and analyzes stylesheets to identify unused selectors, generate optimized output, and report before/after size metrics.

Open dossier

A PostToolUse hook that reminds you to enable native query logging for PostgreSQL, Prisma, Sequelize, and TypeORM, and flags possible N+1 patterns when you edit SQL or data-access files.

Open dossier

Alerts when files exceed size thresholds that could impact performance. This PostToolUse hook provides comprehensive file size monitoring when files are created or modified, automatically detecting files that exceed recommended size thresholds for different file types and providing optimization suggestions.

Open dossier
Next stepsDiffers
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
BrandRedis logoRedis
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-10-192025-09-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically after bash, write, or edit activity and inspects files that look like query, model, repository, DAO, or SQL files. Creates .claude/logs/query-performance.log and appends database command or file-analysis events. Uses grep-based heuristics for query warnings and should not be treated as proof of a performance defect.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Reads query-related source files and may print file paths, query patterns, and database command strings to local hook output. Stores analyzed file paths and database command text in .claude/logs/query-performance.log. Database command text may include connection names, database names, or other operational details if typed directly into the command.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/redis-cache-invalidator.sh && chmod +x .claude/hooks/redis-cache-invalidator.sh
mkdir -p .claude/hooks && touch .claude/hooks/css-unused-selector-detector.sh && chmod +x .claude/hooks/css-unused-selector-detector.sh
mkdir -p .claude/hooks && touch .claude/hooks/file-size-warning-monitor.sh && chmod +x .claude/hooks/file-size-warning-monitor.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/redis-cache-invalidator.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/css-unused-selector-detector.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": [
        "bash",
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/file-size-warning-monitor.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.