implementing-database-caching

0
0
Source

Process use when you need to implement multi-tier caching to improve database performance. This skill sets up Redis, in-memory caching, and CDN layers to reduce database load. Trigger with phrases like "implement database caching", "add Redis cache layer", "improve query performance with caching", or "reduce database load".

Install

mkdir -p .claude/skills/implementing-database-caching && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6337" && unzip -o skill.zip -d .claude/skills/implementing-database-caching && rm skill.zip

Installs to .claude/skills/implementing-database-caching

About this skill

Database Cache Layer

Overview

Implement multi-tier caching strategies using Redis, application-level in-memory caches, and query result caching to reduce database load and improve read latency. This skill covers cache-aside, write-through, and write-behind patterns with proper invalidation strategies, TTL configuration, and cache stampede prevention.

Prerequisites

  • Redis server (6.x+) available or Docker for running docker run redis:7-alpine
  • redis-cli installed for cache inspection and debugging
  • Application framework with Redis client library (ioredis, redis-py, Jedis, go-redis)
  • Database query profiling data identifying read-heavy and slow queries
  • Understanding of data freshness requirements (how stale can cached data be)
  • Monitoring tools for cache hit rate and Redis memory usage

Instructions

  1. Profile database queries to identify caching candidates. Focus on queries that: execute more than 100 times per minute, take longer than 50ms, return data that changes less frequently than every 5 minutes, and produce results smaller than 1MB. Use pg_stat_statements or MySQL slow query log.

  2. Design the cache key schema with a consistent naming convention: service:entity:identifier:variant. Examples: app:user:12345:profile, app:products:category:electronics:page:1. Include a version prefix to enable bulk invalidation: v2:app:user:12345.

  3. Implement the cache-aside pattern for read-heavy data:

    • Check Redis first: GET app:user:12345:profile
    • On cache miss: query database, then SET app:user:12345:profile <json> EX 3600
    • On data update: DEL app:user:12345:profile to invalidate
    • Wrap in a helper function that abstracts cache-then-database logic
  4. Configure TTL values based on data change frequency:

    • Static reference data (countries, categories): TTL 24 hours or longer
    • User profile data: TTL 15-60 minutes
    • Product listings: TTL 5-15 minutes
    • Session data: TTL matching session timeout
    • Real-time data (inventory counts, prices): TTL 30-60 seconds or skip caching
  5. Implement cache stampede prevention for high-traffic cache keys:

    • Probabilistic early expiration: Refresh cache at TTL * 0.8 with probability 1 / concurrent_requests
    • Distributed lock: Use SET key:lock NX EX 5 to let one request refresh while others serve stale data
    • Stale-while-revalidate: Serve expired cache while refreshing in background
  6. Add application-level L1 cache using an in-memory LRU cache (Node.js: lru-cache, Python: cachetools, Java: Caffeine) for per-process caching of ultra-hot data. Set L1 TTL shorter than Redis TTL (e.g., 60 seconds L1, 5 minutes Redis).

  7. Configure Redis for production:

    • Set maxmemory to 75% of available RAM
    • Set maxmemory-policy allkeys-lru for cache workloads
    • Enable save "" (disable RDB persistence) for pure cache use
    • Configure tcp-keepalive 60 and timeout 300
  8. Implement cache invalidation on data mutations. After INSERT, UPDATE, or DELETE operations, delete the corresponding cache key and any aggregate/list cache keys that include the modified data. Use Redis key patterns or tag-based invalidation for related keys.

  9. Add cache metrics instrumentation: track cache hit rate (hits / (hits + misses)), cache miss latency (time to populate from DB), Redis memory usage, eviction rate, and average key TTL remaining. Alert when hit rate drops below 80%.

  10. Test cache behavior under load: verify cache hit rate reaches 90%+ for targeted queries, confirm cache invalidation works correctly on updates, and measure end-to-end latency improvement compared to direct database queries.

Output

  • Redis configuration file with memory limits, eviction policy, and persistence settings
  • Cache wrapper module with get/set/invalidate functions and stampede prevention
  • Cache key schema documentation with naming conventions and TTL values per data type
  • Invalidation logic integrated with data access layer for automatic cache clearing on mutations
  • Monitoring dashboard queries for cache hit rate, memory usage, and eviction tracking

Error Handling

ErrorCauseSolution
Redis connection refusedRedis server down or network issueImplement circuit breaker pattern; fall through to database on cache unavailability; retry with exponential backoff
Cache stampede on popular key expirationMany concurrent requests hit cache miss simultaneouslyUse distributed locking or probabilistic early refresh; extend TTL with jitter (TTL + random(0, TTL*0.1))
Stale data served after database updateCache invalidation missed or delayedAudit invalidation paths; use publish/subscribe for cache invalidation events; reduce TTL for sensitive data
Redis out of memory (OOM)Cache size exceeds maxmemory settingEnable allkeys-lru eviction; reduce TTLs; audit large keys with redis-cli --bigkeys; increase maxmemory
Cache key collisionDifferent data stored under the same key patternInclude all discriminating parameters in the cache key; add content hash to key for variant detection

Examples

Caching product catalog for an e-commerce site: Product detail pages query 3 tables (products, categories, reviews_summary). Cache the assembled product JSON in Redis with TTL of 10 minutes. Cache hit rate reaches 95% since products change rarely. Category pages use list cache keys app:products:category:electronics:sort:price:page:1 with 5-minute TTL. On product update, invalidate both the product key and all category list keys containing that product.

User session caching with Redis: Store session data as Redis hashes (HSET session:abc123 userId 456 role admin lastAccess 1705341234). Set TTL to 30 minutes with sliding expiration on each access (EXPIRE session:abc123 1800). Session reads drop from 2ms (PostgreSQL) to 0.1ms (Redis), eliminating 50,000 database queries per minute.

API response caching with stale-while-revalidate: Dashboard endpoint takes 3 seconds to compute. Cache the response with 5-minute TTL. When TTL expires, the first request triggers an async background refresh while serving the stale cached response. Subsequent requests within the refresh window also receive the stale response. Dashboard always loads in under 5ms from the client perspective.

Resources

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.