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 Varnish Laravel Package

spatie/laravel-varnish

Integrate Varnish 4/5 with Laravel: add middleware to force-cache selected routes and flush/purge the Varnish cache from within your app. Includes simple configuration and supports Laravel and Lumen.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Cache Layer Alignment: The package is a natural fit for Laravel applications leveraging Varnish as a reverse proxy cache layer, aligning with modern CDN/edge caching architectures. It abstracts Varnish-specific logic (e.g., cache headers, purge operations) into Laravel’s middleware and facade patterns, reducing coupling with infrastructure.
  • Stateless Middleware: The core functionality (e.g., CacheableByVarnish middleware) is stateless and non-blocking, making it suitable for high-throughput APIs or dynamic content sites where Varnish’s TTL-based caching is desirable.
  • Purge Granularity: Supports route-level, URL pattern, or full cache purges, which is critical for e-commerce, SaaS, or content-heavy apps where stale data is unacceptable.
  • Laravel Ecosystem Synergy: Integrates seamlessly with Laravel’s routing (Route::middleware()), HTTP responses, and event system (e.g., CachePurged events), enabling tight integration with existing workflows (e.g., queue-based purges post-model updates).

Integration Feasibility

  • Minimal Boilerplate: Installation requires only composer require + service provider binding, with zero configuration for basic use. Advanced features (e.g., custom Varnish hosts, ban lists) are optional.
  • Varnish Version Agnosticism: Works with Varnish 4/5, reducing lock-in to specific versions. However, assumes Varnish is already deployed (not a self-hosted solution).
  • HTTP Header Control: Leverages Laravel’s Cache-Control and Surrogate-Control headers to enforce Varnish caching, but requires pre-existing knowledge of Varnish’s vcl configuration (e.g., backend definitions, hash logic).
  • Edge Cases: Limited support for dynamic cache keys (e.g., user-specific content) or conditional caching (e.g., ETag-based validation), which may require custom VCL or middleware extensions.

Technical Risk

  • Varnish Misconfiguration: Incorrect vcl rules (e.g., wrong backend definitions, missing hash directives) can lead to silent failures (e.g., cached stale data). The package assumes Varnish is pre-configured correctly.
  • Purge Race Conditions: Concurrent purges (e.g., from multiple Laravel instances) may cause thundering herd problems if not throttled (e.g., via Redis or database locks).
  • Laravel Version Compatibility: Tested against Laravel 8+ (as of 2026), but backward compatibility with older versions (e.g., 7.x) is untested. May require adjustments for custom route model binding or middleware changes.
  • Performance Overhead: Middleware adds minimal overhead (~1–5ms per request), but purge operations (e.g., Varnish::purge()) may introduce latency if Varnish is remote or under load.

Key Questions

  1. Varnish Topology:
    • Is Varnish deployed as a single instance or cluster? Does the package support multi-DC setups (e.g., Varnish::purge() to multiple hosts)?
    • Are there custom VCL rules (e.g., ACLs, edge-side includes) that conflict with the package’s assumptions?
  2. Cache Invalidation Strategy:
    • How are partial purges (e.g., by tag/pattern) handled? Does the app need fine-grained invalidation (e.g., per-user cache)?
    • Are there offline/queue-based purges (e.g., via Laravel Queues) to avoid blocking requests during high traffic?
  3. Monitoring and Observability:
    • How will purge success/failure be monitored? The package lacks built-in metrics (e.g., Prometheus) or logging hooks.
    • Are there circuit breakers for Varnish connectivity issues (e.g., timeouts, 5xx errors)?
  4. Testing and Validation:
    • How will cache hit/miss ratios be validated in staging? The package provides no built-in testing utilities.
    • Are there smoke tests for Varnish-Laravel integration (e.g., verify X-Cache headers, TTL enforcement)?
  5. Future-Proofing:
    • Does the app plan to adopt Laravel 10+ features (e.g., new middleware stack)? Any potential conflicts?
    • Are there plans to extend Varnish usage (e.g., stale-while-revalidate, private caching) that may require custom VCL or middleware?

Integration Approach

Stack Fit

  • Laravel Core: Fully compatible with Laravel’s middleware pipeline, routing system, and HTTP responses. No core framework modifications required.
  • Varnish Configuration:
    • Prerequisite: Varnish must be pre-configured with:
      • A backend directive pointing to Laravel’s origin (e.g., backend laravel).
      • hash directives for cache keys (e.g., req.url, req.http.X-Cache-Key).
      • vcl_recv/vcl_deliver logic to respect Surrogate-Control headers.
    • Recommendation: Use Spatie’s Varnish VCL template as a starting point.
  • Infrastructure:
    • Cloud Providers: Works with AWS CloudFront (Varnish-compatible), Fastly, or self-hosted Varnish (e.g., Kubernetes, bare metal).
    • Load Balancers: Ensure the load balancer forwards X-Forwarded-* headers to Varnish (critical for req.http.host hashing).

Migration Path

  1. Phase 1: Proof of Concept (PoC)
    • Install the package and apply CacheableByVarnish middleware to a non-critical route (e.g., /docs).
    • Verify:
      • Responses include Surrogate-Control: max-age=... headers.
      • curl -I shows X-Cache: HIT after refresh.
      • Manual purges (Varnish::purge('/path')) work.
  2. Phase 2: Incremental Rollout
    • Start with static content (e.g., /assets, /blog).
    • Gradually add dynamic routes (e.g., /products) with short TTLs (e.g., 5s) for testing.
    • Use feature flags to toggle middleware per route.
  3. Phase 3: Full Integration
    • Replace existing cache headers (Cache-Control) with Surrogate-Control for all Varnish-cached routes.
    • Implement purge triggers (e.g., post-model saved events, queue-based purges).
    • Configure Varnish ban lists for bulk invalidations (e.g., /products/*).

Compatibility

  • Laravel:
    • Tested with Laravel 8–10 (as of 2026). For older versions, check for deprecated method calls (e.g., Route::middleware() syntax).
    • Middleware Conflicts: Ensure no other middleware (e.g., ShareHeaders) overrides Cache-Control after CacheableByVarnish.
  • Varnish:
    • Version Support: Officially supports Varnish 4/5. Varnish 6 may require adjustments (e.g., vcl syntax).
    • Custom VCL: If using non-standard VCL (e.g., custom hashing), the package’s Surrogate-Control logic may need extension.
  • PHP Extensions: No additional extensions required beyond Laravel’s defaults.

Sequencing

  1. Pre-requisite: Deploy and configure Varnish with the recommended VCL.
  2. Installation:
    composer require spatie/laravel-varnish
    php artisan vendor:publish --provider="Spatie\Varnish\VarnishServiceProvider" --tag="config"
    
  3. Configuration:
    • Set varnish_host (default: 127.0.0.1:6082).
    • Configure purge_ban_list if using Varnish’s ban mechanism.
  4. Middleware Application:
    Route::middleware(['web', 'cacheable.by.varnish'])->group(function () {
        // Cached routes
    });
    
  5. Purge Integration:
    • Bind to model events:
      Product::saved(function ($product) {
          Varnish::purge("/products/{$product->id}");
      });
      
    • Or use queue-based purges for scalability:
      PurgeVarnish::dispatch($url)->delay(now()->addSeconds(10));
      

Operational Impact

Maintenance

  • Package Updates:
    • Minimal Churn: Spatie packages
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport