PHPackages                             laravel-parallel/laravel-parallel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. laravel-parallel/laravel-parallel

ActiveLibrary[Queues &amp; Workers](/categories/queues)

laravel-parallel/laravel-parallel
=================================

Simple parallel processing for Laravel - Powered by AMPHP with automatic CPU detection.

v1.2.0(5mo ago)13[5 PRs](https://github.com/giorgospatelis/laravel-parallel/pulls)MITPHPPHP ^8.2CI passing

Since Nov 8Pushed 4mo agoCompare

[ Source](https://github.com/giorgospatelis/laravel-parallel)[ Packagist](https://packagist.org/packages/laravel-parallel/laravel-parallel)[ RSS](/packages/laravel-parallel-laravel-parallel/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelog (4)Dependencies (9)Versions (12)Used By (0)

 [![Laravel Parallel Banner](art/banner.jpg)](art/banner.jpg)

Laravel Parallel
================

[](#laravel-parallel)

 **Simple parallel processing for Laravel - Powered by AMPHP with automatic CPU detection.**

 [![Latest Version](https://camo.githubusercontent.com/e8224a73a6a9e3e0b252a5d3f7f4764dd16077d8e4a05ade2a56d911a2a62e72/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c61726176656c2d706172616c6c656c2f6c61726176656c2d706172616c6c656c)](https://packagist.org/packages/laravel-parallel/laravel-parallel) [![Total Downloads](https://camo.githubusercontent.com/923acf0a0a212dcffd18c7ba220f66f7fe8751c7ecb1594cb04bff0727355b5e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c61726176656c2d706172616c6c656c2f6c61726176656c2d706172616c6c656c)](https://packagist.org/packages/laravel-parallel/laravel-parallel) [![License](https://camo.githubusercontent.com/392c2e4f848492d5a3f18144fe9eb6416c1d1ee73d9f7d341f4f9f3894fbf0e9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6c61726176656c2d706172616c6c656c2f6c61726176656c2d706172616c6c656c)](https://packagist.org/packages/laravel-parallel/laravel-parallel) [![PHP Version](https://camo.githubusercontent.com/1dd3b56a51233fe82bfc91c0f9b566232cef3df6db7436770b6f0cee83fb57bb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6c61726176656c2d706172616c6c656c2f6c61726176656c2d706172616c6c656c)](https://packagist.org/packages/laravel-parallel/laravel-parallel)

---

Laravel Parallel provides an intuitive, Laravel-style API for true parallel processing in your applications. Built on the battle-tested [amphp/parallel](https://github.com/amphp/parallel) library, it enables you to execute CPU-intensive tasks concurrently with automatic CPU core detection and comprehensive error handling.

Features
--------

[](#features)

- **Intuitive API** - Fluent, Laravel-style interface with method chaining
- **Automatic Optimization** - Detects CPU cores for optimal parallelization
- **True Parallelism** - Real multi-process execution, not just async/concurrent
- **Rich Result Handling** - Comprehensive result collection with metrics and filtering
- **Laravel Integration** - Works seamlessly with Octane, Horizon, and other Laravel features
- **Type-Safe** - PHPStan Level 8 compliant with full type coverage
- **Extensible Architecture** - Built on SOLID principles with clear extension points
- **Production Ready** - Comprehensive error handling, logging, and monitoring
- **Event-Driven** - Task lifecycle events for observability and monitoring

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require laravel-parallel/laravel-parallel
```

### Requirements

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.0 or higher

Laravel VersionPackage Version11.x, 12.x^2.0### Configuration (Optional)

[](#configuration-optional)

Publish the configuration file:

```
php artisan vendor:publish --tag=parallel-config
```

This will create a `config/parallel.php` file where you can customize default settings.

Quick Start
-----------

[](#quick-start)

Execute tasks in parallel with a simple, fluent API:

```
use LaravelParallel\Facades\Parallel;

$results = Parallel::run([
    'user_report' => fn() => generateUserReport(),
    'sales_data' => fn() => fetchSalesData(),
    'inventory' => fn() => syncInventory(),
]);

foreach ($results as $key => $result) {
    if ($result->isSuccess()) {
        echo "Task {$key}: " . $result->getValue();
    }
}
```

That's it! Laravel Parallel automatically detects your CPU cores and distributes work efficiently.

Usage Examples
--------------

[](#usage-examples)

### Basic Parallel Execution

[](#basic-parallel-execution)

Execute multiple tasks concurrently:

```
use LaravelParallel\Facades\Parallel;

$results = Parallel::run([
    'task1' => fn() => expensive_operation_1(),
    'task2' => fn() => expensive_operation_2(),
    'task3' => fn() => expensive_operation_3(),
]);

foreach ($results as $key => $result) {
    if ($result->isSuccess()) {
        echo "Task {$key}: {$result->getValue()}\n";
    } else {
        echo "Task {$key} failed: {$result->getException()->getMessage()}\n";
    }
}
```

### Parallel Map Operation

[](#parallel-map-operation)

Process collections in parallel:

```
$users = User::all();

$results = Parallel::map($users, function ($user) {
    return [
        'id' => $user->id,
        'score' => calculateComplexScore($user),
    ];
});

// Extract all values
$scores = collect($results)->map->getValue()->all();
```

### Configuration

[](#configuration)

Customize worker count and timeout:

```
$results = Parallel::workers(4)
    ->timeout(30.0)
    ->run([
        'heavy1' => fn() => processLargeDataset(),
        'heavy2' => fn() => runComplexCalculation(),
    ]);
```

### Real-World Example: Parallel API Requests

[](#real-world-example-parallel-api-requests)

Fetch multiple API endpoints simultaneously:

```
$endpoints = [
    'users' => 'https://api.example.com/users',
    'posts' => 'https://api.example.com/posts',
    'comments' => 'https://api.example.com/comments',
];

$results = Parallel::map($endpoints, function ($url) {
    return Http::get($url)->json();
});

$data = collect($results)
    ->filter->isSuccess()
    ->map->getValue()
    ->all();
```

Configuration
-------------

[](#configuration-1)

The package works out-of-the-box with sensible defaults. You can customize behavior via the config file or environment variables:

Config KeyEnv VariableDefaultDescription`default_workers``PARALLEL_WORKERS``null` (auto-detect)Number of worker processes`default_timeout``PARALLEL_TIMEOUT``30`Timeout in seconds`max_workers``PARALLEL_MAX_WORKERS``128`Maximum workers allowed`max_tasks_per_batch``PARALLEL_MAX_TASKS``10000`Max tasks per batch`auto_chunk``PARALLEL_AUTO_CHUNK``true`Auto-chunk large batches`chunk_size``PARALLEL_CHUNK_SIZE``1000`Size of chunks`events.enabled``PARALLEL_EVENTS_ENABLED``true`Enable task events`logging.enabled``PARALLEL_LOGGING_ENABLED``true`Enable logging`logging.channel``PARALLEL_LOG_CHANNEL``stack`Log channel`logging.level``PARALLEL_LOG_LEVEL``info`Minimum log levelSee the [full configuration file](config/parallel.php) for all options and detailed descriptions.

Advanced Usage
--------------

[](#advanced-usage)

### Working with Results

[](#working-with-results)

The result collection provides powerful methods for handling parallel execution outcomes:

```
use LaravelParallel\Results\ResultCollection;

$results = new ResultCollection(Parallel::run($tasks));

// Filter successful results
$successful = $results->successful();

// Filter failed results
$failed = $results->failed();

// Extract values with default for failures
$values = $results->valuesOr('default_value');

// Get all exceptions
$exceptions = $results->exceptions();

// Check if all succeeded
if ($results->allSuccessful()) {
    echo "All tasks completed successfully!\n";
}
```

### Execution Metrics

[](#execution-metrics)

Track performance with built-in metrics:

```
use LaravelParallel\Results\ExecutionMetrics;

$results = new ResultCollection(Parallel::run($tasks));
$metrics = ExecutionMetrics::fromResults($results);

echo "Total tasks: {$metrics->totalTasks}\n";
echo "Successful: {$metrics->successfulTasks}\n";
echo "Failed: {$metrics->failedTasks}\n";
echo "Success rate: {$metrics->successRate()}%\n";
echo "Total time: {$metrics->totalExecutionTime}s\n";
echo "Average time: {$metrics->averageExecutionTime}s\n";
```

### Error Handling

[](#error-handling)

Handle failures gracefully:

```
$results = Parallel::run($tasks);

foreach ($results as $key => $result) {
    $result
        ->ifSuccess(fn($value) => processValue($value))
        ->ifFailure(fn($exception) => handleError($exception));
}
```

### Event Listeners

[](#event-listeners)

Listen to task lifecycle events:

```
use LaravelParallel\Events\TaskCompleted;
use LaravelParallel\Events\TaskFailed;
use LaravelParallel\Events\TaskStarted;

Event::listen(TaskCompleted::class, function ($event) {
    Log::info("Task {$event->taskKey} completed in {$event->executionTime}s");
});

Event::listen(TaskFailed::class, function ($event) {
    Log::error("Task {$event->taskKey} failed", [
        'error' => $event->exception->getMessage(),
    ]);
});
```

Integrations
------------

[](#integrations)

Laravel Parallel integrates seamlessly with popular Laravel ecosystem tools to enhance monitoring, observability, and developer experience.

### Laravel Horizon Integration

[](#laravel-horizon-integration)

Monitor your parallel tasks in real-time through Laravel Horizon's dashboard. The Horizon integration provides:

- **Automatic metrics recording** for all parallel tasks
- **Real-time statistics** via REST API endpoints
- **Dashboard tagging** for easy filtering and monitoring
- **Event-driven architecture** with zero configuration required

The integration is included with the package and activates automatically when Laravel Horizon is detected. Simply install Horizon and start using Laravel Parallel - metrics will appear in your Horizon dashboard immediately.

**Quick Start:**

```
// Execute parallel tasks as normal
$results = Parallel::run([
    'task1' => fn() => processData(1),
    'task2' => fn() => processData(2),
]);

// View metrics in Horizon dashboard at /horizon
// Filter by tag "parallel" to see all parallel tasks
```

For detailed setup instructions, API documentation, and advanced configuration options, see the [Horizon Integration Guide](docs/horizon-integration.md).

### Laravel Telescope Integration

[](#laravel-telescope-integration)

Debug and profile your parallel tasks with Laravel Telescope's powerful inspection tools. The Telescope integration provides:

- **Task lifecycle tracking** - Monitor when tasks start, complete, or fail
- **Execution metrics** - View execution times, results, and performance data
- **Smart filtering** - Filter tasks by status, exception type, or execution duration
- **Exception debugging** - Detailed stack traces and error information for failed tasks

The integration is included with the package and activates automatically when Laravel Telescope is detected. Task details appear in a dedicated "Parallel Task" section within your Telescope dashboard.

**Quick Start:**

```
// Execute parallel tasks as normal
$results = Parallel::run([
    'user_report' => fn() => generateUserReport(),
    'sales_data' => fn() => fetchSalesData(),
]);

// View in Telescope dashboard at /telescope
// Navigate to "Parallel Task" section
// Filter by tags: parallel, parallel:completed, parallel:failed, task:user_report
```

For detailed setup instructions, configuration options, and debugging workflows, see the [Telescope Integration Guide](docs/telescope-integration.md).

### Future Integrations

[](#future-integrations)

Planned integrations for upcoming releases:

- **Laravel Pulse** - Real-time performance monitoring and alerting
- **Sentry** - Advanced error tracking and performance monitoring

Extending the Package
---------------------

[](#extending-the-package)

Laravel Parallel is built with extensibility in mind. You can create:

- **Custom Tasks**: Implement `TaskContract` for specialized task types
- **Custom Executors**: Implement `ExecutorContract` for alternative execution strategies
- **Custom Result Handlers**: Extend `ResultCollection` for domain-specific operations
- **Middleware**: Intercept task execution for logging, monitoring, etc.

### Creating a Custom Task

[](#creating-a-custom-task)

```
use LaravelParallel\Tasks\AbstractTask;
use Amp\Cancellation;
use Amp\Sync\Channel;

final class DatabaseQueryTask extends AbstractTask
{
    public function __construct(
        private readonly string $query,
        private readonly array $bindings = [],
    ) {
        parent::__construct();
    }

    public function run(Channel $channel, Cancellation $cancellation): mixed
    {
        // This runs in a worker process
        $pdo = new PDO(/* connection details */);
        $stmt = $pdo->prepare($this->query);
        $stmt->execute($this->bindings);

        return $stmt->fetchAll();
    }
}
```

### Best Practices

[](#best-practices)

1. **Keep Tasks Self-Contained**: Tasks should contain all data needed for execution
2. **Handle Serialization**: Ensure all task data is serializable
3. **Resource Management**: Recreate database connections and resources in worker processes
4. **Error Handling**: Always handle exceptions and return meaningful error information

Architecture
------------

[](#architecture)

Laravel Parallel follows **Hexagonal Architecture** (Ports &amp; Adapters) and **SOLID** principles for maximum maintainability and extensibility.

```
┌─────────────────────────────────────────┐
│         Laravel Application             │
└──────────────┬──────────────────────────┘
               │
        ┌──────▼──────┐
        │  Parallel   │  (Facade)
        │  Facade     │
        └──────┬──────┘
               │
        ┌──────▼──────────┐
        │ ParallelManager │  (Core)
        └──────┬──────────┘
               │
        ┌──────▼──────────┐
        │    Executor     │  (Core)
        └──────┬──────────┘
               │
     ┌─────────┴─────────┐
     │                   │
┌────▼────────┐     ┌────▼────────┐
│  Worker     │     │  Worker     │
│  Pool       │ ... │  Pool       │
│  Manager    │     │  Manager    │
└─────────────┘     └─────────────┘

```

### Key Components

[](#key-components)

- **Core**: Domain logic (ParallelManager, Executor, ResultCollector)
- **Contracts**: Interfaces for extensibility (TaskContract, ExecutorContract, etc.)
- **Tasks**: Executable work units with serialization support
- **Workers**: Worker pool management and lifecycle
- **Results**: Result handling with rich metrics

The package wraps the powerful [amphp/parallel](https://github.com/amphp/parallel) library with a Laravel-friendly interface.

### Design Patterns

[](#design-patterns)

- **Facade Pattern**: Static access via `Parallel` facade
- **Factory Pattern**: Worker pool creation with dependency injection
- **Value Object Pattern**: Immutable configuration objects
- **Strategy Pattern**: Different task types via `TaskContract`
- **Dependency Injection**: Constructor injection throughout

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test:coverage
```

Run static analysis:

```
composer phpstan
```

The package maintains:

- PHPStan Level 8 compliance
- 77.5% test coverage (251 tests, 672 assertions)
- Comprehensive unit and feature tests

Performance
-----------

[](#performance)

### When to Use Laravel Parallel

[](#when-to-use-laravel-parallel)

**Ideal For:**

- CPU-bound tasks (data processing, transformations, calculations)
- Task sets with 10 or more tasks
- Tasks taking 100ms or longer each
- Immediate results needed (not background processing)
- Laravel applications prioritizing developer experience

**Better Alternatives:**

- **Micro-tasks (&lt;100ms)**: Use sequential processing
- **I/O-bound operations**: Use Laravel Queues or async HTTP
- **Background jobs**: Use Laravel Queues with horizon
- **Large data payloads (&gt;1MB)**: Consider streaming or chunking

### Overhead Analysis

[](#overhead-analysis)

- **Setup overhead**: ~2-5ms per execution
- **Per-task overhead**: ~0.5-1ms (serialization + IPC)
- **Break-even point**: 10 tasks × 100ms = 1 second total work

### Example Performance

[](#example-performance)

```
// Small Workload (Not Recommended)
// 5 tasks × 100ms = 500ms sequential
// Parallel: ~150ms (3.2x speedup, 3% overhead)

// Medium Workload (Recommended)
// 50 tasks × 1s = 50s sequential
// Parallel (5 cores): ~10s (4.98x speedup, 0.3% overhead)

// Large Workload (Excellent)
// 1000 tasks × 500ms = 500s sequential
// Parallel (8 cores): ~63s (7.94x speedup, 0.8% overhead)
```

### Performance Tips

[](#performance-tips)

**1. Optimal Worker Count**

```
// For CPU-bound tasks, use CPU count
$results = Parallel::workers(CPU_COUNT)->run($cpuTasks);

// For I/O-bound tasks, use 2-3x CPU count
$results = Parallel::workers(CPU_COUNT * 3)->run($ioTasks);
```

**2. Chunk Large Datasets**

```
$items = range(1, 100000);
$chunks = array_chunk($items, 1000);

$results = Parallel::map($chunks, function ($chunk) {
    return array_map(fn($n) => process($n), $chunk);
});
```

**3. Balance Task Size**

```
// Bad: Too many small tasks (high overhead)
$results = Parallel::map(range(1, 100000), fn($n) => $n * 2);

// Good: Reasonable task granularity
$chunks = array_chunk(range(1, 100000), 1000);
$results = Parallel::map($chunks, fn($chunk) => array_map(fn($n) => $n * 2, $chunk));
```

Frequently Asked Questions
--------------------------

[](#frequently-asked-questions)

### Can I use this with Laravel Octane/Swoole?

[](#can-i-use-this-with-laravel-octaneswoole)

**Yes!** Laravel Parallel v2.0+ is fully compatible with Laravel Octane and Swoole. The package uses non-singleton bindings to prevent state leakage between requests.

### How is this different from Laravel Queues?

[](#how-is-this-different-from-laravel-queues)

Laravel Queues are designed for background processing with delayed execution, while Laravel Parallel is for immediate parallel execution:

- **Queues**: Background processing, persistent storage, delayed execution, job retries
- **Parallel**: Immediate execution, in-memory processing, real-time results, CPU-intensive tasks

Use queues for background jobs, use parallel processing for immediate CPU-intensive operations.

### How many workers should I use?

[](#how-many-workers-should-i-use)

The optimal number depends on your task type:

- **CPU-bound tasks**: Number of CPU cores (auto-detected by default)
- **I/O-bound tasks**: 2-3x CPU cores
- **Mixed workloads**: Start with CPU count and adjust based on monitoring

### What happens if a task throws an exception?

[](#what-happens-if-a-task-throws-an-exception)

Exceptions are caught and wrapped in a `ParallelResult` with `isFailure() === true`. Other tasks continue executing independently. You can handle failures gracefully:

```
foreach ($results as $result) {
    if ($result->isFailure()) {
        $exception = $result->getException();
        // Handle the error
    }
}
```

### Can I use database connections in parallel tasks?

[](#can-i-use-database-connections-in-parallel-tasks)

Yes, but you need to be aware that each worker process has its own memory space. Database connections should be recreated within each task:

```
$results = Parallel::map($items, function ($item) {
    // Each worker recreates the connection
    $user = User::find($item['user_id']);
    return processUser($user);
});
```

### How do I retry failed tasks?

[](#how-do-i-retry-failed-tasks)

Extract failed task keys and rerun them:

```
$results = new ResultCollection(Parallel::run($tasks));
$failedTasks = $results->failed()->keys()->all();

if (count($failedTasks) > 0) {
    $retryTasks = collect($tasks)->only($failedTasks)->all();
    $retryResults = Parallel::run($retryTasks);
}
```

### Is this package production-ready?

[](#is-this-package-production-ready)

Yes! Laravel Parallel v2.0+ is built with production in mind:

- PHPStan Level 8 compliance (maximum type safety)
- Comprehensive test coverage (77.5% with 251 tests and 672 assertions)
- Battle-tested amphp/parallel foundation
- Used in production Laravel applications
- Octane/Swoole compatible

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for recent changes and version history.

Contributing
------------

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

If you discover a security vulnerability, please email . All security vulnerabilities will be promptly addressed.

Credits
-------

[](#credits)

- [Giorgos Patelis](https://github.com/giorgospatelis)
- Powered by [amphp/parallel](https://github.com/amphp/parallel)
- All [contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance74

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

4

Last Release

167d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e23d13be27c55c1b5c4d6f5c2ce15b5ab8886039204caafa8667049c8430a295?d=identicon)[giorgospatelis](/maintainers/giorgospatelis)

---

Top Contributors

[![giorgospatelis](https://avatars.githubusercontent.com/u/6917158?v=4)](https://github.com/giorgospatelis "giorgospatelis (35 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (6 commits)")

---

Tags

amphp-syncasyncconcurrentlaravelmulti-processingparallelasynclaravelconcurrentmulti-processingamphpparallel

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/laravel-parallel-laravel-parallel/health.svg)

```
[![Health](https://phpackages.com/badges/laravel-parallel-laravel-parallel/health.svg)](https://phpackages.com/packages/laravel-parallel-laravel-parallel)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[amphp/parallel

Parallel processing component for Amp.

84746.2M74](/packages/amphp-parallel)[illuminate/queue

The Illuminate Queue package.

20331.4M1.2k](/packages/illuminate-queue)[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[amphp/file

Non-blocking access to the filesystem based on Amp and Revolt.

1103.3M94](/packages/amphp-file)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

3786.5k](/packages/harris21-laravel-fuse)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
