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

Amp Laravel Package

amphp/amp

AMPHP (AMP) accelerates PHP concurrency with fibers, eliminating callbacks and generators. Built on PHP 8.1’s cooperative coroutines, it lets you run async tasks like sync code—ideal for I/O-bound apps. Use Amp\async() for parallel execution and Future::await() to handle results seamlessly. No event...

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven & Non-Blocking Paradigm: amphp/amp aligns perfectly with modern PHP architectures requiring high concurrency (e.g., microservices, real-time APIs, or I/O-bound workloads). Its fiber-based coroutines enable cooperative multitasking without threads, reducing complexity while improving scalability.
  • Laravel Compatibility: Laravel’s synchronous request-response model (e.g., middleware, controllers) clashes with amp’s async primitives. However, amp can be integrated as a background worker (e.g., for async jobs, WebSockets, or long-running tasks) while preserving Laravel’s synchronous core.
  • Revolt Dependency: Requires revolt/event-loop for scheduling, which adds ~100KB to the footprint. This is negligible for dedicated async services but may be overkill for lightweight Laravel apps.

Integration Feasibility

  • Async Job Queues: Replace Laravel’s queue:work with amp-powered workers (e.g., using amphp/parallel for CPU-bound tasks or amphp/http-client for external API calls).
  • WebSockets/Real-Time: Integrate with amphp/http-server for WebSocket endpoints (e.g., Laravel Echo alternatives) or replace pusher-php-server with amp-based solutions.
  • Database Access: Non-blocking amphp/mysql/amphp/postgres drivers can replace Eloquent queries in async contexts (e.g., background data syncs).
  • Hybrid Sync/Async: Use amp only for I/O-bound operations (e.g., HTTP calls, DB queries) while keeping business logic synchronous via Future::await().

Technical Risk

  • Fiber Limitations:
    • PHP fibers are not preemptive; blocking calls (e.g., sleep(), legacy DB drivers) will stall the entire process. Requires strict avoidance of blocking code.
    • No shared state: Fibers cannot share memory directly (use Amp\Future or Amp\Promise for data passing).
  • Laravel Ecosystem Friction:
    • Service Container: amp’s DI is fiber-aware but incompatible with Laravel’s container (e.g., no async singleton resolution).
    • Middleware: Async middleware must use Future wrappers; synchronous middleware will block fibers.
    • Testing: Async code requires amp-aware test runners (e.g., Amp\Test utilities).
  • Performance Overhead:
    • Context switching between fibers has ~10–50µs overhead per operation. Benchmark critical paths (e.g., high-QPS APIs).
    • Revolt’s event loop adds ~5–10% CPU overhead compared to synchronous code.

Key Questions

  1. Use Case Clarity:
    • Is amp needed for user-facing async (e.g., WebSockets) or background tasks (e.g., cron jobs, data pipelines)?
    • Will it replace Laravel’s queue system entirely, or supplement it?
  2. Blocking Code Audit:
    • Are there legacy blocking calls (e.g., file_get_contents(), curl_exec()) that must be rewritten?
  3. Team Expertise:
    • Does the team have experience with fibers, event loops, or async PHP (e.g., Swoole, ReactPHP)?
  4. Deployment Impact:
    • Will amp run in the same process as Laravel (risking fiber leaks) or as a separate service (e.g., via Docker)?
  5. Monitoring:
    • How will fiber leaks/cancellations be detected (e.g., Amp\Cancellation timeouts)?

Integration Approach

Stack Fit

  • Core Laravel: Keep synchronous for HTTP routes, Eloquent, and business logic.
  • Async Layers:
    • Workers: Replace queue:work with amp-based consumers (e.g., Amp\async() + amphp/parallel).
    • APIs: Use amphp/http-server for async endpoints (e.g., GraphQL subscriptions, SSE).
    • External Calls: Replace Guzzle/Symfony HTTP clients with amphp/http-client for non-blocking requests.
    • DB: Use amphp/mysql/amphp/postgres for async queries (e.g., in workers, not controllers).
  • Tooling:
    • Testing: Use Amp\Test\Loop for async tests.
    • Debugging: Integrate Xdebug with fiber-aware extensions (e.g., ext-fiber).
    • Monitoring: Track fiber counts (e.g., Amp\currentFiber()) and cancellation rates.

Migration Path

  1. Phase 1: Isolated Async Components

    • Add amp to a new service (e.g., laravel-async-worker) handling background tasks.
    • Use Amp\async() for non-critical I/O (e.g., logging, analytics).
    • Example: Replace Log::channel()->info() with Amp\async(fn() => Log::info()).
  2. Phase 2: Hybrid Integration

    • Wrap Laravel queues with amp workers:
      // app/Console/Commands/ProcessAsyncJobs.php
      Amp\async(function () {
          while (true) {
              $job = dispatch_fresh_job();
              $job->handle(); // Sync or async, but non-blocking
          }
      });
      
    • Replace synchronous HTTP clients with amphp/http-client in workers.
  3. Phase 3: Async Endpoints

    • Use amphp/http-server for real-time features (e.g., WebSockets):
      $server = new Amp\Http\Server();
      $server->request('GET', '/ws', fn($request) => new Amp\Http\WebSocket($request));
      
    • Proxy Laravel routes to amp via a reverse proxy (e.g., Nginx).
  4. Phase 4: Full Async Rewrite (Optional)

    • Rewrite controllers to return Future objects (e.g., for async responses).
    • Use Amp\Future\await() in middleware for non-blocking auth/validation.

Compatibility

Laravel Component Compatibility Workaround
Eloquent ❌ (Blocking) Use amphp/mysql in workers only.
Queues ✅ (Partial) Replace workers with amp-powered ones.
HTTP (Guzzle) ❌ (Blocking) Migrate to amphp/http-client.
Middleware ⚠️ (Async-only) Use Future-wrapped middleware.
Blade/Templating Render templates synchronously.
Cache (Redis) ✅ (Non-blocking) Use amphp/redis if needed.

Sequencing

  1. Start with Workers:
    • Replace queue:work with amp-based consumers first (lowest risk).
  2. Add Async APIs:
    • Introduce amphp/http-server for WebSockets/SSE alongside Laravel’s HTTP server.
  3. Optimize I/O:
    • Replace blocking HTTP/DB calls in workers with amp equivalents.
  4. Monitor and Iterate:
    • Use Amp\Cancellation timeouts to handle slow operations.
    • Gradually migrate synchronous code to async where beneficial.

Operational Impact

Maintenance

  • Fiber Leaks:
    • Risk: Unhandled exceptions or missing Future::await() calls can leak fibers, causing memory bloat.
    • Mitigation:
      • Use Amp\Cancellation timeouts for all async operations.
      • Implement a fiber leak detector (e.g., Amp\currentFiber() + gc_enabled() checks).
  • Dependency Updates:
    • amp and revolt are actively maintained, but breaking changes may require rewrites (e.g., fiber API shifts).
    • Monitor AMPHP’s changelog for PHP 9+ compatibility.
  • Debugging Complexity:
    • Async stack traces are harder to read. Use Amp\Trace or Xdebug with fiber support.

Support

  • Error Handling:
    • Async exceptions (e.g., Future rejections) must be caught and logged explicitly. Avoid silent failures.
    • Example:
      try {
          $result = $future->await();
      } catch (Throwable $e) {
          Sentry\captureException($e);
          $deferred->error(new RuntimeException("Async failed: {$e->getMessage()}"));
      }
      
  • Team Onboarding:
    • Requires training on fibers, Future combinators, and event loops.
    • Document async patterns (e.g., "always await() futures").
  • Vendor Lock-in:
    • amp’s API is stable, but migrating to other async PHP frameworks (e.g., Swoole) later may be costly.

**

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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle