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

Message Bus Laravel Package

simple-bus/message-bus

Generic PHP interfaces and utilities for building message buses such as command buses and event buses. Provides reusable components to dispatch messages through middleware and handlers, forming the foundation for CQRS-style messaging in your app.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven & CQRS Alignment: The package excels in systems requiring event-driven architecture (EDA) or Command Query Responsibility Segregation (CQRS). It provides a generic abstraction for message buses (commands, events, queries), making it a strong fit for Laravel applications with:
    • Domain-driven design (DDD) patterns (e.g., aggregates, repositories).
    • Microservices or modular monoliths where decoupled communication is critical.
    • Background jobs (e.g., queues) that need structured message handling.
  • Middleware Support: Built-in middleware (e.g., logging) allows for cross-cutting concerns like auditing, validation, or retries without polluting business logic.
  • Laravel Synergy: Complements Laravel’s queue system (e.g., Illuminate\Queue) but offers higher-level abstractions for message routing, validation, and dispatching.

Integration Feasibility

  • Low Coupling: The package enforces interfaces over implementations, enabling:
    • Custom message buses (e.g., in-memory, Redis, database-backed).
    • Seamless integration with Laravel’s service container (via bind()).
  • PHP 8+ Compatibility: Leverages modern PHP features (e.g., attributes for message metadata), reducing friction in new Laravel projects.
  • Queue Adapter: Can wrap Laravel’s queue system to translate messages into jobs, bridging the gap between EDA and Laravel’s built-in queues.

Technical Risk

  • Learning Curve: Requires understanding of message bus patterns (e.g., handlers, subscribers, middleware). Developers unfamiliar with EDA may need training.
  • Performance Overhead: Middleware and validation layers add latency if not optimized (e.g., excessive logging or sync processing).
  • State Management: No built-in persistence for messages (unlike RabbitMQ/Kafka). Requires external storage (e.g., database, Redis) for durability.
  • Laravel-Specific Quirks:
    • Queue Workers: Messages must be serializable (Laravel’s queue system enforces this).
    • Service Provider Bootstrapping: May need custom providers to integrate with Laravel’s lifecycle.
  • Testing Complexity: Mocking message buses in unit tests requires dependency injection and event simulation, which can be verbose.

Key Questions

  1. Use Case Clarity:
    • Is this for internal event sourcing, cross-service communication, or decoupled workflows?
    • Do we need exactly-once processing (requires external tools like dead-letter queues)?
  2. Performance Requirements:
    • Will messages be synchronous (blocking) or asynchronous (queued)?
    • What’s the expected throughput (e.g., 1000 msg/sec may need Redis instead of DB)?
  3. Error Handling:
    • How should failed messages be retried/recovered (e.g., dead-letter queue, alerts)?
    • Does Laravel’s failed_jobs table suffice, or is a custom solution needed?
  4. Tooling:
    • Will we use Laravel’s queue system as the transport layer, or a dedicated broker (e.g., RabbitMQ)?
    • Do we need message validation (e.g., schema enforcement) beyond Laravel’s request validation?
  5. Team Maturity:
    • Does the team have experience with message-driven architectures?
    • Is there buy-in for new patterns (e.g., handlers vs. controllers)?

Integration Approach

Stack Fit

  • Laravel Core:
    • Service Container: Bind interfaces (MessageBus, CommandBus) to implementations (e.g., queue-backed bus).
    • Queues: Use Illuminate\Queue as the transport layer for async processing.
    • Events: Leverage Laravel’s event system for pub/sub where applicable.
  • Database/Redis:
    • Message Storage: For durability, store messages in a table (e.g., messages) with status (pending/processed/failed).
    • Redis: Use for high-throughput scenarios (e.g., pub/sub for events).
  • Testing:
    • PHPUnit: Mock MessageBus interface for unit tests.
    • Pest/Laravel: Use actingAs() or fake() for integration tests with queues.

Migration Path

  1. Phase 1: Proof of Concept (PoC)
    • Implement a single message bus (e.g., command bus) for a non-critical workflow.
    • Compare performance vs. Laravel’s native queues.
    • Example:
      // Register bus in a service provider
      $this->app->bind(MessageBus::class, function ($app) {
          return new QueueMessageBus(
              new LaravelQueueAdapter($app['queue']),
              new InvocationMiddleware(),
              new LoggingMiddleware()
          );
      });
      
  2. Phase 2: Core Integration
    • Replace direct service calls with message dispatching (e.g., bus->dispatch(new CreateUserCommand())).
    • Migrate Laravel events to use the message bus for consistency.
    • Add middleware for validation, retries, or metrics.
  3. Phase 3: Full Adoption
    • Extend to event sourcing or saga patterns if needed.
    • Implement monitoring (e.g., Prometheus metrics for message latency).

Compatibility

  • Laravel Versions: Works with Laravel 8+ (PHP 8.0+). For older versions, may need polyfills (e.g., for attributes).
  • Queue Drivers: Supports all Laravel queue drivers (database, Redis, SQS, etc.).
  • Existing Code:
    • Controllers: Replace direct service calls with message dispatching.
    • Jobs: Wrap existing jobs in message handlers if needed.
    • Events: Convert Event::dispatch() to bus->dispatch(new EventMessage()).

Sequencing

  1. Define Message Contracts:
    • Create interfaces for commands/events (e.g., CreateUserCommand, UserCreatedEvent).
    • Use attributes for metadata (e.g., @TargetQueue('high-priority')).
  2. Implement Handlers:
    • Build classes implementing MessageHandler for each message type.
  3. Configure Bus:
    • Set up middleware (e.g., logging, validation).
    • Bind the bus to Laravel’s container.
  4. Deploy Transport Layer:
    • Configure queues/database for message storage.
  5. Monitor and Optimize:
    • Add health checks for message processing.
    • Tune middleware for performance (e.g., async logging).

Operational Impact

Maintenance

  • Pros:
    • Decoupled Components: Easier to update handlers or buses without affecting other parts.
    • Middleware Reusability: Logging, validation, or retries can be applied globally.
  • Cons:
    • Message Schema Changes: Requires backward-compatible updates (e.g., versioned messages).
    • Handler Maintenance: Each message type needs a dedicated handler, increasing boilerplate.
  • Tooling Needs:
    • Message Catalog: Document all message types (e.g., in a messages/ directory).
    • Migration Scripts: For schema changes (e.g., adding fields to message classes).

Support

  • Debugging:
    • Message Tracing: Log message IDs and lifecycles (e.g., dispatched → processed → failed).
    • Dead-Letter Queues: Redirect failed messages to a table/queue for inspection.
  • Common Issues:
    • Handler Not Found: Ensure all message classes are registered with the bus.
    • Serialization Errors: Validate messages are JSON-serializable (Laravel’s queue system enforces this).
    • Lock Contention: For sync buses, use optimistic locking or distributed locks.
  • Support Team Training:
    • Teach developers to correlate logs using message IDs.
    • Document recovery procedures for stuck messages.

Scaling

  • Horizontal Scaling:
    • Queue Workers: Scale Laravel queue workers based on message volume.
    • Broker Choice: Redis/RabbitMQ scales better than database-backed queues.
  • Performance Bottlenecks:
    • Handler Execution Time: Long-running handlers should be offloaded to jobs.
    • Database Load: Avoid storing large payloads in messages (use IDs + external storage).
  • Monitoring:
    • Track:
      • Message Latency: Time from dispatch to processing.
      • Queue Depth: Avoid backpressure with auto-scaling.
      • Error Rates: Alert on repeated handler failures.

Failure Modes

Failure Scenario Impact Mitigation
Queue worker crashes Messages undelivered Supervisor (e.g., Laravel Forge/Envoyer) + retries.
Handler throws exception Message lost (unless persisted) Dead-letter queue + alerting.
Database/Redis outage Message loss (if not persisted)
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky