Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Responsecache Laravel Package

spatie/laravel-responsecache

Cache full Laravel responses to speed up your app. Automatically caches successful text-based GET requests (HTML/JSON), with easy middleware per route, configurable lifetimes, and optional stale-while-revalidate “grace” caching to refresh in the background.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Full-Stack Caching: The package integrates seamlessly with Laravel’s middleware stack, enabling response-level caching without requiring application-layer modifications. This aligns well with Laravel’s middleware-first architecture (e.g., CacheResponse as a middleware).
  • Granular Control: Supports route-level, controller-level (via PHP attributes), and global caching configurations, making it adaptable to monolithic or modular Laravel applications.
  • Flexible Cache Strategies:
    • Strict Caching: Full bypass of application logic for cached responses.
    • Flexible Caching: Stale-while-revalidate pattern for gradual updates (e.g., dashboards).
    • Exclusion Rules: Opt-out via #[NoCache] or middleware exclusion.
  • Cache Invalidation: Leverages Laravel’s existing cache drivers (Redis, database, etc.), ensuring consistency with the app’s caching strategy.

Integration Feasibility

  • Low Friction: Requires minimal setup (composer install + middleware registration). No database migrations or schema changes.
  • Laravel Ecosystem Compatibility:
    • Works with Laravel 12/13 (PHP 8.4/8.5) and back to Laravel 11 (PHP 8.3).
    • Integrates with Laravel’s cache drivers (Redis, Memcached, file, database).
    • Supports API responses (JSON) and HTML (e.g., Blade templates).
  • Middleware Integration: Can be applied globally (via App\Http\Kernel) or selectively (route groups/controllers).
  • Event-Driven Extensibility: Emits events (CacheMissed, CacheStored) for custom logic (e.g., analytics, logging).

Technical Risk

Risk Area Assessment Mitigation
Cache Invalidation Risk of stale data if business logic changes but cache isn’t invalidated. Use tags (CacheResponse::for()->withTags()) or manual invalidation (ResponseCache::forget()).
Performance Overhead Initial cache generation may slow first requests. Use flexible caching for high-traffic endpoints or short TTLs for dynamic content.
CSRF/Session Issues Cached responses may break CSRF tokens or session-dependent content. Exclude routes with #[NoCache] or use CsrfTokenReplacer middleware.
Cache Key Collisions Custom cache keys may conflict with default hashing. Use explicit cache keys or debug with X-Response-Cache headers.
Testing Complexity Cached responses complicate unit/integration tests. Use ResponseCache::clear() in tests or mock the middleware.
Dependency Bloat Adds ~50KB to vendor size (minimal impact). Negligible for most applications.

Key Questions for TPM

  1. Cache Granularity:
    • Should caching be applied globally, per-route, or per-controller?
    • Are there dynamic segments (e.g., /posts/{id}) that require custom key generation?
  2. Staleness Tolerance:
    • Which endpoints can tolerate flexible caching (stale-while-revalidate)?
    • What’s the maximum acceptable staleness (e.g., 5 minutes for dashboards)?
  3. Invalidation Strategy:
    • How will cache be invalidated for user-specific data (e.g., after login)?
    • Should tags be used for bulk invalidation (e.g., user:123)?
  4. Monitoring:
    • How will cache hit/miss ratios be tracked (e.g., Prometheus, custom logging)?
    • Are there SLOs for cache performance (e.g., 99% cache hit rate)?
  5. Edge Cases:
    • Are there authenticated routes that should never be cached?
    • How will WebSocket/real-time updates interact with cached responses?
  6. Fallbacks:
    • What’s the fallback if the cache driver fails (e.g., Redis downtime)?
    • Should graceful degradation be implemented (e.g., serve stale content)?

Integration Approach

Stack Fit

  • Laravel Core: Native integration with Laravel’s middleware, cache drivers, and routing.
  • PHP Version: Supports PHP 8.3+ (Laravel 11+) and PHP 8.5+ (Laravel 13).
  • Cache Backends: Compatible with Redis, Memcached, database, and file drivers.
  • Frontend/Backend Agnostic: Works with Blade templates, APIs (JSON), and SPAs (if cached at the edge).
  • Tooling:
    • Laravel Forge/Vapor: Easy deployment with Redis caching.
    • Laravel Horizon: Can integrate with queue-based cache invalidation.

Migration Path

Phase Action Items Dependencies
Assessment Audit routes/controllers for cache eligibility (GET, text-based responses). Analytics data (e.g., slowest endpoints).
Pilot Apply caching to low-risk routes (e.g., static pages, public APIs). Monitoring (cache hit/miss rates).
Gradual Rollout Expand to high-traffic routes (e.g., product listings, dashboards). Feature flags for A/B testing.
Optimization Tune TTLs, tags, and flexible caching based on performance data. Load testing.
Global Enable Apply default caching middleware to App\Http\Kernel. Review exclusion rules.

Compatibility

  • Middleware Conflicts:
    • No conflicts with most middleware (e.g., auth, CORS), but order matters (cache should run after auth but before logging).
    • Avoid: Placing CacheResponse after middleware that modifies responses (e.g., AppendsAuthToken).
  • Package Conflicts:
    • No known conflicts with other Spatie packages (e.g., laravel-permission).
    • Potential conflict: Packages that modify HTTP responses post-execution (e.g., laravel-activitylog).
  • Laravel Features:
    • Works with: API resources, Blade directives, Inertia.js, Livewire (if cached at the edge).
    • Limitation: Livewire may not work well with full-page caching (use partial caching instead).

Sequencing

  1. Setup:
    • Install package: composer require spatie/laravel-responsecache.
    • Publish config: php artisan vendor:publish --provider="Spatie\ResponseCache\ResponseCacheServiceProvider".
    • Configure cache driver (Redis recommended for production).
  2. Testing:
    • Test in staging with CacheResponse::for(seconds(10)) for quick iteration.
    • Verify X-Response-Cache headers in responses.
  3. Deployment:
    • Start with short TTLs (e.g., 5 minutes) and monitor.
    • Gradually increase TTLs based on cache hit rates.
  4. Monitoring:
    • Track CacheMissed events and adjust invalidation logic.
    • Set up alerts for cache bloat (e.g., Redis memory usage).

Operational Impact

Maintenance

  • Cache Invalidation:
    • Automatic: Invalidate via tags (e.g., user:123) or manually (ResponseCache::forget()).
    • Scheduled: Use Laravel tasks (artisan schedule) to clear stale cache.
  • Configuration Drift:
    • Centralize cache rules in config files or route service providers to avoid scattered middleware.
  • Dependency Updates:
    • Monitor Spatie’s release cycle (quarterly major updates).
    • Test upgrades in staging before production.

Support

  • Debugging:
    • Use X-Response-Cache headers to diagnose misses/hits.
    • Log CacheMissedEvent for troubleshooting.
  • Common Issues:
    • Stale CSRF tokens: Exclude routes with #[NoCache] or use CsrfTokenReplacer.
    • Cache key collisions: Use custom keys for dynamic routes.
    • Performance regressions: Profile with tideways/xhprof or Blackfire.
  • Documentation:
    • Maintain an internal runbook for cache invalidation procedures.
    • Train devs on #[Cache] attributes vs. middleware.

Scaling

  • Horizontal Scaling:
    • Stateless: Cache is stored externally (Redis), so scaling Laravel instances is seamless.
    • Cache Sharding: Use Redis cluster for
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai