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

Async Laravel Package

php-standard-library/async

Fiber-based async primitives for PHP: structured concurrency with cooperative multitasking. Run tasks concurrently, manage lifecycles, cancellations, and scopes predictably. Part of PHP Standard Library; docs and guides at php-standard-library.dev.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Synergy: The fiber-based structured concurrency model aligns with Laravel’s growing async ecosystem (e.g., Laravel 11’s async features, spatie/async). It bridges the gap between synchronous Laravel defaults (e.g., Eloquent, routes) and async workflows without requiring a full ReactPHP/Swoole overhaul.
  • Hybrid Sync/Async: Ideal for incremental adoption—wrap existing sync code in Async::run() without rewriting entire pipelines. Example:
    // Sync route handler → Async
    Route::get('/data', function () {
        return Async::run(fn() => [
            fetchUserData(),
            fetchOrderData(),
        ]);
    });
    
  • Queue Augmentation: Complements Laravel’s queue system by enabling dynamic task grouping (e.g., fan-out/fan-in patterns for batch jobs) without replacing it. Use case:
    // Fan-out: Dispatch parallel tasks
    $tasks = collect($orders)->map(fn($order) =>
        Async::task(fn() => processOrder($order))
    );
    Async::all($tasks)->await(); // Fan-in
    
  • Event-Driven Extensions: Enables async event listeners (e.g., Async::onEvent()) for real-time workflows (e.g., webhooks, notifications) without blocking the request lifecycle.

Integration Feasibility

  • Laravel-Specific Challenges:
    • Request Lifecycle: Async code in route handlers risks timeouts or memory leaks (e.g., unawaited Promises). Mitigation: Use Async::run() sparingly; prefer queues for long-running tasks.
    • Database Operations: Async DB queries (e.g., Async::task(fn() => User::find(1))) break Laravel’s connection pooling. Workaround: Use raw PDO or queue jobs for DB-bound async tasks.
    • Middleware: Async middleware requires Laravel 11+ or custom middleware to handle await() properly. Example:
      public function handle(Request $request, Closure $next) {
          return Async::run(fn() => $next($request))->await();
      }
      
  • Promise Compatibility: Laravel 8+ includes Illuminate\Support\Facades\Promise, but this package’s implementation may differ in:
    • Error handling: Test if Async::catch() integrates with Laravel’s App\Exceptions\Handler.
    • Chaining: Verify Async::then() works with Laravel’s Promise facades.
  • Testing: Async workflows complicate testing. The package should provide:
    • Mocking utilities (e.g., Async::fake()).
    • Laravel test helpers (e.g., Async::assertAwaited()).

Technical Risk

  • Blocking the Event Loop: In Laravel’s synchronous stack, async operations can starve the main thread. Risks:
    • Timeouts: Async middleware or routes may hit PHP’s max_execution_time.
    • Memory Bloat: Unawaited Promises accumulate until garbage collected.
    • Solution: Reserve async for background tasks (queues) or Laravel 11+ async routes.
  • Error Propagation: Async errors (e.g., rejected Promises) may silently fail or crash the app. Critical to:
    • Centralize error handling (e.g., Async::catch()report()).
    • Test edge cases:
      • A Promise rejecting after the response is sent.
      • Mixed sync/async code paths (e.g., async middleware + sync route).
  • Dependency Conflicts: Potential clashes with:
    • spatie/async or amphp/async (duplicate Promise implementations).
    • Laravel’s illuminate/support (Promise facades).
  • Performance Overhead: Fiber-based concurrency adds context-switching costs. Benchmark against:
    • Native queue workers (for I/O-bound tasks).
    • Swoole/ReactPHP (for CPU-bound tasks).

Key Questions

  1. Adoption Scope:
    • Will this replace Laravel’s queue system, or supplement it? (Avoid mixing async tasks and queue jobs without clear boundaries.)
    • Should async be used in request pipelines (high risk) or background processing (lower risk)?
  2. Error Handling:
    • How will async errors integrate with Laravel’s App\Exceptions\Handler?
    • Are there tools to mock async operations in tests?
  3. Database Safety:
    • Does the package provide safe async DB access (e.g., connection pooling)? If not, how will we enforce queue-based DB operations?
  4. Performance:
    • How does it compare to spatie/async or Swoole for throughput and latency?
    • What’s the memory footprint of concurrent async tasks?
  5. Long-Term Viability:
    • Is the package actively maintained? (MIT license is permissive, but no stars/release history is concerning.)
    • Does it align with Laravel’s async roadmap (e.g., Laravel 11’s async features)?

Integration Approach

Stack Fit

  • Laravel Core:
    • Queues: Use for fire-and-forget tasks (e.g., Async::later()dispatch()).
    • Promises: Hybrid sync/async with illuminate/support (test compatibility).
    • Events: Async listeners (e.g., Async::onEvent() for real-time workflows).
  • Async Runtimes:
    • Swoole: For true concurrency (package may need Swoole adapters).
    • ReactPHP: If using react/promise, ensure compatibility.
    • Native PHP: For cooperative multitasking (e.g., Async::parallel()).
  • Third-Party:
    • Avoid duplication with spatie/async or amphp/async.
    • Complement Laravel Queues for dynamic task orchestration.

Migration Path

  1. Phase 1: Background Tasks
    • Replace simple queue jobs with Async::task() to validate gains.
    • Example:
      // Before: Queue job
      ProcessPayment::dispatch($userId);
      
      // After: Async task (still runs in worker)
      Async::task(fn() => ProcessPayment::run($userId))->await();
      
  2. Phase 2: Composable Workflows
    • Use Async::parallel() for fan-out (e.g., API aggregators):
      $results = Async::parallel([
          fn() => fetchUserData($userId),
          fn() => fetchOrderData($orderId),
      ])->await();
      
    • Replace nested callbacks with Async::then()/Async::catch().
  3. Phase 3: Request Pipeline (Caution)
    • Only for Laravel 11+ or async middleware.
    • Example:
      public function handle(Request $request, Closure $next) {
          return Async::run(fn() => $next($request))->await();
      }
      
  4. Phase 4: Observability
    • Integrate with Laravel’s logging/monitoring:
      • Track Async task durations in Sentry/New Relic.
      • Log rejected Promises via Async::catch()report().

Compatibility

  • Laravel Versions:
    • Test on Laravel 10/11 (Promise support varies).
    • Avoid Laravel <8 (no native Promise facades).
  • PHP Extensions:
    • Requires PHP 8.1+ (fibers, typed properties).
    • Optional: Swoole/ReactPHP for high-performance use cases.
  • Database:
    • Do not use for async DB queries unless wrapped in a queue job (connection leaks).
    • Prefer raw PDO or queue jobs for async DB access.

Sequencing

  1. Dependency Injection:
    • Bind to Laravel’s container:
      $this->app->singleton(Async::class, fn() => new Async());
      
  2. Configuration:
    • Add config/async.php for:
      • Default concurrency limits (Async::setConcurrency(5)).
      • Error reporting (e.g., log rejected Promises).
  3. Testing:
    • Mock Async in unit tests:
      Async::shouldReceive('task')->andReturn(new MockPromise());
      
    • Use Laravel’s refreshDatabase() with async seeders.
  4. Deployment:
    • Queue Workers: No changes needed if using existing workers.
    • Async Middleware: Test under load (risk of timeouts).

Operational Impact

Maintenance

  • Codebase Complexity:
    • Pros: Reduces callback hell; promotes declarative async code.
    • Cons: Adds a new abstraction layer. Document:
      • When to use Async vs. queues.
      • Error handling quirks (e.g., uncaught Promise rejections).
  • Dependency Updates:
    • Monitor for breaking changes in:
      • Laravel’s illuminate/support (
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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