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

Query Bus Laravel Package

averor/query-bus

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • CQRS Alignment: The package is explicitly designed for the Query side of CQRS, making it a strong fit for architectures where read models are decoupled from write models. It abstracts query handling into a message bus pattern, enabling asynchronous query processing, event-driven reads, and eventual consistency.
  • Laravel Ecosystem Synergy: Built for Laravel, it integrates seamlessly with Laravel’s service container, events, and queues, leveraging existing infrastructure (e.g., Illuminate\Bus, Illuminate\Queue). This reduces friction in adoption.
  • Separation of Concerns: Encourages a clean split between commands (write) and queries (read), aligning with DDD principles. Queries are treated as messages, promoting a reactive architecture.
  • Query Composition: Supports query composition (e.g., aggregating results from multiple sources), which is valuable for complex read models (e.g., dashboards, analytics).

Integration Feasibility

  • Low-Coupling Design: The package is dependency-injection friendly, allowing it to slot into existing Laravel applications without major refactoring. Existing query handlers can be incrementally migrated.
  • Queue Backend Agnostic: Works with Laravel’s queue drivers (database, Redis, etc.), enabling flexibility in scaling and persistence.
  • Event-Driven Extensibility: Can integrate with Laravel’s event system to trigger queries in response to domain events (e.g., OrderCreated → CalculateOrderStatsQuery).
  • Middleware Support: Supports query middleware (e.g., logging, authorization, caching), similar to Laravel’s HTTP middleware.

Technical Risk

  • Learning Curve: Developers unfamiliar with message buses or CQRS may require training to adopt the pattern effectively. Misuse (e.g., treating queries as commands) could lead to anti-patterns.
  • Eventual Consistency Trade-offs: Queries may return stale data if not properly synchronized with write operations. Requires discipline in query invalidation or eventual consistency strategies.
  • Debugging Complexity: Asynchronous query processing can make debugging harder (e.g., tracing query failures in distributed systems). Logging and monitoring must be robust.
  • Overhead for Simple Apps: For applications with trivial read models, the abstraction may introduce unnecessary complexity. Best suited for scalable, event-driven architectures.

Key Questions

  1. Use Case Fit:
    • Does the application have complex read models (e.g., real-time dashboards, multi-source aggregations) that justify CQRS?
    • Are there performance bottlenecks in current query handling (e.g., N+1 queries, slow joins) that this could mitigate?
  2. Consistency Requirements:
    • Can the application tolerate eventual consistency for queries, or are strong consistency guarantees needed?
  3. Infrastructure Readiness:
    • Is the team comfortable with asynchronous processing and queue-based workflows?
    • Are there existing event sourcing or CQRS patterns in place, or is this a greenfield adoption?
  4. Migration Strategy:
    • How will existing repository patterns or Eloquent queries be transitioned to the message bus?
    • Will queries be backward-compatible during migration?
  5. Monitoring and Observability:
    • Are there tools in place to track query performance, failure rates, and latency in async workflows?
  6. Team Alignment:
    • Do developers understand the difference between commands and queries in CQRS?
    • Is there buy-in for adopting a message-driven architecture?

Integration Approach

Stack Fit

  • Laravel Native: The package is Laravel-first, leveraging:
    • Service Container: For dependency injection of query handlers.
    • Queues: For async processing (supports database, redis, beanstalkd, etc.).
    • Events: For triggering queries in response to domain events.
    • Bus: For synchronous query dispatch (if needed).
  • PHP Ecosystem: Works with PSR-15 (HTTP message interfaces) and PSR-11 (container), ensuring compatibility with modern PHP libraries.
  • Database Agnostic: Query handlers can interact with any data source (Eloquent, raw SQL, external APIs), making it flexible for heterogeneous read models.

Migration Path

  1. Incremental Adoption:
    • Start with non-critical queries (e.g., analytics, reports) to test the pattern.
    • Gradually migrate high-impact read operations (e.g., dashboard data) to the query bus.
  2. Wrapper Pattern:
    • Create adapters to wrap existing repositories/queries, allowing them to be dispatched via the bus.
    • Example:
      // Old: Direct repository call
      $user = $userRepository->findById($id);
      
      // New: Query bus dispatch
      $query = new FindUserByIdQuery($id);
      $user = bus()->dispatch($query);
      
  3. Event-Driven Queries:
    • Attach query handlers to domain events (e.g., UserUpdated → RefreshUserCacheQuery).
    • Use Laravel’s listen() method or a dedicated event-to-query mapper.
  4. Hybrid Sync/Async:
    • Use synchronous dispatch (bus()->dispatch()) for simple queries.
    • Use queues (bus()->dispatchNow() or dispatchLater()) for async processing.

Compatibility

  • Laravel Versions: Check compatibility with the target Laravel version (e.g., 8.x, 9.x, 10.x). May require minor adjustments for newer features (e.g., Symfony 6+ components).
  • Query Handler Contracts: Handlers must implement Averor\QueryBus\Contracts\Query and return a Result (success/failure). Existing code may need refactoring.
  • Error Handling: The package provides query exceptions, but custom error handling (e.g., retries, dead-letter queues) may need to be implemented.
  • Testing: Query handlers should be unit-tested in isolation, with integration tests for async workflows (e.g., queue consumers).

Sequencing

  1. Phase 1: Setup
    • Install the package (composer require averor/query-bus).
    • Configure the bus in config/app.php and publish configs if needed.
    • Set up queue workers (php artisan queue:work).
  2. Phase 2: Query Definition
    • Define query classes (e.g., GetUserProfileQuery).
    • Implement handlers (e.g., GetUserProfileHandler).
  3. Phase 3: Integration
    • Replace direct query calls with bus dispatch.
    • Integrate with events or HTTP routes (e.g., API endpoints).
  4. Phase 4: Observability
    • Add logging (e.g., query start/end times, payloads).
    • Set up monitoring for failed queries (e.g., Sentry, Laravel Horizon).
  5. Phase 5: Optimization
    • Implement caching for frequent queries.
    • Optimize query composition (e.g., parallel vs. sequential execution).

Operational Impact

Maintenance

  • Handler Management:
    • Query handlers are self-contained, making them easier to maintain than monolithic repositories.
    • Changes to queries require handler updates, but the bus abstraction isolates these changes.
  • Dependency Updates:
    • The package is stable (assuming low churn given its niche focus), but Laravel version upgrades may require testing.
  • Documentation:
    • Limited official docs may require internal runbooks for query design patterns, error handling, and debugging.

Support

  • Debugging Async Queries:
    • Failed queries may require queue inspection (php artisan queue:failed), logging, or distributed tracing.
    • Tools like Laravel Horizon or RedisInsight can help monitor queue backlogs.
  • Performance Tuning:
    • Query handlers may need optimization (e.g., database indexing, batching).
    • Queue workers may require scaling (horizontal scaling with more workers or faster queue backends like Redis).
  • Support Team Skills:
    • Engineers must be comfortable with async systems and eventual consistency.

Scaling

  • Horizontal Scaling:
    • Query handlers are stateless (assuming they don’t rely on in-memory caches), enabling horizontal scaling of workers.
    • Queue backends (e.g., Redis) can be clustered for high throughput.
  • Throughput:
    • Async queries offload read operations from the web tier, reducing latency for HTTP requests.
    • Batching queries (e.g., processing 100 user profiles in one job) can improve efficiency.
  • Cold Starts:
    • If using serverless queues (e.g., AWS SQS), warm-up strategies may be needed to avoid cold starts for query workers.

Failure Modes

Failure Scenario Impact Mitigation
Queue worker crashes
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.
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
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk