Weave 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

Fos Http Cache Cloudfront Laravel Package

jean-beru/fos-http-cache-cloudfront

CloudFront proxy implementation for FOSHttpCache. Create an AWS CloudFront client, instantiate the proxy with your distribution ID, purge single URLs or wildcard patterns, then call flush(). Supports custom caller reference generators to avoid duplicate requests.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Purpose Alignment: The package is a CloudFront-specific implementation of FOSHttpCache, enabling edge caching for Laravel applications. It fits well in architectures where:
    • CloudFront is the primary CDN for static/dynamic content delivery.
    • FOSHttpCache is already used for HTTP-level caching (e.g., Symfony-based Laravel apps), now pinned to 3.x.
    • Cache invalidation is manual or scripted today, and automation is desired.
  • Design Philosophy:
    • Proxy Pattern: Extends FOSHttpCache’s proxy interface (purge(), flush()) with CloudFront-specific logic, reducing boilerplate for AWS API calls.
    • AWS SDK Abstraction: Uses async-aws/cloudfront to handle low-level CloudFront API interactions (e.g., invalidations, warmup).
    • Laravel Agnostic: Designed for PHP/Symfony, not Laravel-native (e.g., no service providers, facades, or queue jobs).
  • Key Strengths:
    • Decoupled from Laravel: Can be used in non-Laravel PHP apps if FOSHttpCache is present.
    • Async Support: Built on AWS SDK v3’s async client for non-blocking requests.
    • Caller Reference Handling: Prevents duplicate invalidation requests via configurable generators — now reliably functional (see 1.3.0).
  • Key Weaknesses:
    • No Laravel Integration: Requires manual setup (e.g., binding to Laravel’s container, integrating with cache drivers).
    • AWS Dependency: Tight coupling to CloudFront and AWS SDK v3 may conflict with existing Laravel AWS integrations.
    • Limited Observability: No built-in logging or monitoring for invalidation failures.
    • New in 1.3.0 — Narrowed Dependency Floor: FOSHttpCache 2.x is dropped; adopters must be on 3.x.

Release 1.3.0 Delta (Impact on This Assessment)

Change Type Assessment Impact
chore: … drop friendsofsymfony/http-cache 2.x (PR #13) Breaking Raises the minimum supported FOSHttpCache to 3.x. Any app (or internal library) still resolving friendsofsymfony/http-cache:^2 must be upgraded before adopting 1.3.0. Pinning ^1.2 becomes the safe fallback only if 2.x support is a hard requirement.
fix: pass CallerReference as string to createInvalidation (PR #11) Correctness fix Previously the caller reference could be serialized as a non-string, producing CloudFront InvalidArgument 400s on invalidation. This directly retires our highest-likelihood runtime failure mode and makes the DateCallerReferenceGenerator dedup strategy trustworthy.
fix: type url parameter of CloudFront::purge() (PR #15) Behavioural / minor BC Method signature is now strictly typed. Callers passing ints, Stringable objects, or unvalidated route parameters will now hit a TypeError instead of an implicit cast. Audit call sites; cast explicitly.
fix: README links and code samples (PR #12) Documentation Reduced ramp-up friction. Note: README now shows the async-aws client — the PoC snippet in our prior assessment used the AWS SDK v2 Aws\CloudFront\CloudFrontClient, which conflicts. Corrected below.
chore: update CI workflow and add Dependabot (PR #10) Supply chain / maintenance Positive maintenance signal: automated dependency visibility and a maintained CI matrix. Slightly reduces the "small-maintainer" bus-factor risk, though it remains a single-maintainer package.

Verdict: update required. The 2.x dependency drop is a breaking change for a subset of adopters, and the CallerReference fix changes the risk posture.

Integration Feasibility

  • Core Features Supported:
    • Cache Invalidation: Supports both single-path (/homepage) and wildcard (/assets/*) purges.
    • Batch Invalidation: Accumulates purges and flushes them in a single API call (efficient for CloudFront).
    • Cache Warmup: Implicitly supported via purge() (CloudFront pre-loads URLs on invalidation).
    • TTL Respect: Relies on CloudFront’s Cache-Control settings (configured separately).
  • Gaps:
    • No Laravel Cache Driver Integration: Cannot directly replace Laravel’s cache() facade or Cache tagging.
    • No Event Listeners: Requires manual triggers (e.g., after model updates) for invalidation.
    • No Queue Support: Invalidation is synchronous; no Laravel queue integration for async processing.
  • Dependencies:
    • Hard Dependencies:
      • async-aws/cloudfront (AWS SDK v3).
      • symfony/http-cache / friendsofsymfony/http-cache ^3.0 (2.x no longer accepted as of 1.3.0).
    • Soft Dependencies:
      • aws/aws-sdk-php (if using v2; avoid due to conflicts).
      • Laravel’s cache facade (for hybrid caching strategies).

Technical Risk

Risk Area Severity Mitigation Strategy
FOSHttpCache 2.x → 3.x Upgrade (new, 1.3.0) High Inventory transitive friendsofsymfony/http-cache constraints (composer why). Upgrade to 3.x in the same change window; validate Symfony component versions and PHP floor. Pin ^1.3 only after resolution succeeds.
AWS SDK Version Conflicts High Enforce async-aws/cloudfront via composer.json and resolve with platform-check.
Laravel Integration Gaps High Create a custom service provider to bind the proxy and extend Laravel’s Cache facade.
Strict purge() Parameter Typing (new, 1.3.0) Medium Grep invalidation call sites for non-string arguments (ints, Stringable, route models); cast explicitly and add a static-analysis rule (PHPStan level ≥ 5).
CloudFront Configuration Drift Medium Validate CacheBehaviors (e.g., ForwardedValues, TrustedSigners) before adoption.
Rate Limiting Medium Monitor CloudFront API throttling (default: 1,000 requests/second); batch purges.
Testing Complexity Medium Use mocks for AWS SDK in unit tests; integrate with Laravel’s HTTP tests for E2E.
Duplicate Invalidations Low (downgraded) 1.3.0 fixes CallerReference string casting; DateCallerReferenceGenerator deduplication now behaves as documented. Retain a dedup assertion in tests.
Single-Maintainer / Bus Factor Medium (slightly improved) Dependabot + CI added; still a one-maintainer package. Track upstream releases; budget for a fork if abandoned.

Key Questions

  1. Upgrade Path (new):
    • Which of our services still resolve friendsofsymfony/http-cache:^2, and what blocks a 3.x upgrade (Symfony minor version, PHP floor, custom proxy subclasses)?
    • Does FOSHttpCache 3.x’s supported Symfony range cover the framework version bundled with our target Laravel release (Laravel 11 ships Symfony 7)?
  2. AWS Infrastructure:
    • Are CloudFront invalidation permissions (cloudfront:CreateInvalidation) granted to the Laravel app’s IAM role?
    • Does the CloudFront distribution use origin groups or lambda@edge, which might complicate cache invalidation?
  3. Caching Strategy:
    • Should this replace Laravel’s file/redis cache drivers or act as a secondary cache layer?
    • How will Cache-Control headers be synchronized between Laravel and CloudFront?
  4. Performance:
    • What is the expected cache hit ratio? Will CloudFront’s default TTL (24h) conflict with business needs?
    • Are there plans to implement cache tagging (e.g., purge by tag) for dynamic content (e.g., user-specific pages)?
  5. Operational Impact:
    • How will invalidation failures be monitored (e.g., AWS CloudTrail vs. Laravel logs)?
    • What fallback mechanism exists if CloudFront invalidation fails (e.g., Redis purge)?
  6. Laravel-Specific:
    • Should invalidations be triggered by model events (e.g., eloquent.updated) or custom commands?
    • Will this integrate with Laravel’s queue system for async invalidations?

Integration Approach

Stack Fit

  • Ideal Use Cases:
    • Laravel + CloudFront: Apps using CloudFront for CDN and FOSHttpCache 3.x for HTTP caching.
    • Hybrid Caching: Systems with Redis/Memcached as primary cache and CloudFront as edge cache.
    • Legacy Migration: Replacing custom CloudFront invalidation scripts with a managed solution.
  • Tech Stack Compatibility:
    Component Compatibility
    Laravel 9+/PHP 8.1+ ✅ Full support (Symfony HTTP Cache components).
    AWS CloudFront ✅ Required (package is CloudFront-specific).
    FOSHttpCache 3.x ✅ Direct extension (assumes existing FOSHttpCache setup).
    FOSHttpCache 2.x ❌ Dropped in 1.3.0 — stay on ^1.2 or upgrade.
    Redis/Memcached ⚠️ Partial (can complement but not replace).
    Guzzle/AWS SDK v2 ❌ Conflicts (use async-aws/cloudfront instead).
    Laravel Queues ❌ No native support (requires custom integration).
  • Anti-Patterns:
    • Overkill for Static Assets: If only serving static files, use CloudFront’s built-in cache behaviors.
    • No CloudFront: Avoid if using Fastly, Cloudflare, or self-hosted caches.
    • Real-Time Data: Not suitable for apps requiring sub-second cache invalidation (e.g., financial dashboards).

Migration Path

  1. Phase 0: Dependency Triage for 1.3.0 (2-3 days, new)
    • Run composer why friendsofsymfony/http-cache across all affected services.
    • Confirm none of our packages block 3.x; if blocked, plan the FOSHttpCache upgrade first, or pin ^1.2 and defer.
    • Record the PHP floor and Symfony range for the target Laravel release.
  2. Phase 1: Assessment (1-2 weeks)
    • Audit existing cache invalidation logic (e.g., cron jobs, manual AWS CLI calls).
    • Verify CloudFront distribution settings: DefaultCacheBehavior (ForwardedValues, TTL) and Origin (S3, ALB, or custom origin).
    • Check IAM permissions for the Laravel app’s AWS role.
  3. Phase 2: PoC (1 week)
    • Install the package in staging (corrected client — see 1.3.0 note):
      composer require jean-beru/fos-http-cache-cloudfront:^1.3 async-aws/cloudfront
      
    • Minimal proxy setup:
      // config/cloudfront.php
      'distribution_id' => env('CLOUDFRONT_DISTRIBUTION_ID'),
      'region'          => env('AWS_REGION'),
      
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton('cloudfront.proxy', function ($app) {
              return new \JeanBeru\HttpCacheCloudFront\Proxy\CloudFront(
                  new \AsyncAws\CloudFront\CloudFrontClient([
                      'region' => $app['config']['cloudfront.region'],
                  ]),
                  ['distribution_id' => $app['config']['cloudfront.distribution_id']]
              );
          });
      }
      
    • Test invalidation (strings only — 1.3.0 enforces the type):
      $proxy = app('cloudfront.proxy');
      $proxy->purge('/homepage')->purge('/assets/*')->flush();
      
    • Regression check: verify a second identical purge within the dedup window is suppressed (validates the PR #11 fix).
  4. Phase 3: Laravel Integration (1-2 weeks)
    • Option A: Cache Facade Extension (Recommended): extend Laravel’s Cache facade to delegate invalidations and register via Facade::extend().
    • Option B: Artisan Command: php artisan cache:purge /path/to/invalidate.
    • Option C: Event Listeners: trigger invalidations on Eloquent events (eloquent.updated), dispatching to a queue job to keep request latency flat.
  5. Phase 4: Rollout (1 week, new)
    • Ship behind a config flag; shadow-run against the existing script and diff invalidation counts before cutover.

Operational Impact

Maintenance

  • Version Pinning: Pin ^1.3 and lockfile-pin async-aws/cloudfront. Upstream is pre-2.0, so treat minor bumps as potentially breaking and read changelogs — 1.3.0 itself demonstrates this (a "chore" PR dropped a major dependency).
  • Upstream Cadence: Dependabot and a refreshed CI workflow now give visibility into dependency drift; still expect low release frequency from a single maintainer. Budget a small quarterly review.
  • Fork Readiness: The integration surface is narrow (one proxy class + config). Keep our Laravel binding in app/ rather than forking the package, so a future replacement is a one-file change.

Support

  • Observability Gap Persists: No built-in logging. Add a thin decorator around the proxy that logs invalidation requests, CloudFront Invalidation.Id, and API errors, and emits a metric per purge.
  • Failure Surface: CloudFront createInvalidation errors (auth, throttling, malformed path, InvalidArgument). 1.3.0 removes the caller-reference class of failures; the rest remain caller-handled.
  • Escalation: Single-maintainer upstream means we own workarounds. Maintain an internal runbook covering "invalidation stuck / not applying" and the manual AWS CLI fallback.

Scaling

  • Throughput: CloudFront permits ~1,000 invalidation requests/second but only 1,000 free invalidation paths/month per distribution — cost and quota, not throughput, is the real ceiling. Batch aggressively via flush().
  • Request-Path Latency: Synchronous purges add an AWS round-trip. Beyond low write volume, move invalidations onto Laravel queues.
  • Multi-Distribution: One proxy instance per distribution ID; expect DI wiring per tenant/environment if we run several.

Failure Modes

Mode Symptom Containment
CloudFront API error / throttle Stale content at edge Retry with backoff; log; alert on error rate
Missing/misconfigured IAM All purges fail fast Pre-flight check in deploy; synthetic purge in smoke tests
Wildcard purge over-reach Cache churn, cost spike, origin load Restrict patterns; monitor invalidation path counts
Origin cannot absorb post-purge load Latency spike / 5xx on cold cache Rate-limit purges; stagger; verify origin autoscaling
Dependency drift (composer update) Runtime TypeError / class-not-found Lockfile pinning, CI composer validation, staging gate

Ramp-Up

  • Effort: ~2-3 engineer-days for a Laravel developer familiar with HTTP caching; the package is small and the README (now corrected in 1.3.0) covers the core path.
  • Prerequisites: Working knowledge of Cache-Control/s-maxage, FOSHttpCache proxy semantics, and CloudFront invalidation quotas.
  • Accelerators: The Phase 2 PoC doubles as the reference implementation; publish it internally as a copy-paste service-provider snippet so subsequent teams skip discovery.
  • Friction Points: No Laravel-native docs; the 2.x → 3.x FOSHttpCache upgrade may be the longest single task in the plan for legacy services.
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.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log