nuwber / rabbitevents
The RabbitEvents package for Laravel
Fund package maintenance!
Requires
- php: ^8.2
- ext-json: *
- enqueue/amqp-lib: ^0.10
- illuminate/console: ^11.0|^12.0|^13.0
- illuminate/container: ^11.0|^12.0|^13.0
- illuminate/events: ^11.0|^12.0|^13.0
- illuminate/log: ^11.0|^12.0|^13.0
- illuminate/pipeline: ^11.0|^12.0|^13.0
- illuminate/support: ^11.0|^12.0|^13.0
- ramsey/uuid: ^4.7
Requires (Dev)
- illuminate/queue: ^11.0|^12.0|^13.0
- mockery/mockery: ^1.6.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5|^11.0|^12.0|^13.0
- vlucas/phpdotenv: ^v5.6
Suggests
- ext-amqp: Using this extension makes your app faster. If you're using it you need to install enqueue/amqp-ext.
- ext-pcntl: Required to use all features of the worker.
- enqueue/amqp-ext: This package is necessary if you want to use `ext-amqp`.
- rabbitevents/deduplication: Skips messages redelivered after they were handled, using a Laravel cache store shared by the workers.
- rabbitevents/outbox: Delivers published messages through a database outbox: written in the transaction of the event, retried until sent or expired, coalesced by object key.
- rabbitevents/protobuf: The Protobuf serializer for RabbitEvents.
Provides
None
Conflicts
None
Replaces
- nuwber/rabbitevents: v10.1.0
- rabbitevents/foundation: v10.1.0
- rabbitevents/listener: v10.1.0
- rabbitevents/publisher: v10.1.0
- 10.x-dev
- v10.1.0
- v10.0.1
- v10.0.0
- 9.x-dev
- v9.1.4
- v9.1.3
- v9.1.2
- v9.1.1
- v9.1.0
- v9.0.5
- v9.0.4
- v9.0.3
- v9.0.2
- v9.0.1
- v9.0.0
- v9.0.0-alpha2
- v9.0.0-alpha1
- 8.x-dev
- v8.2.3
- v8.2.2
- v8.2.1
- v8.2.0
- v8.1.5
- v8.1.4
- v8.1.3
- v8.1.2
- v8.1.1
- v8.1.0
- v8.1.0-beta.1
- v8.0.1
- v8.0.0
- 7.x-dev
- v7.3.0
- v7.2.0
- v7.1.1
- v7.1.0
- v7.0.1
- v7.0
- v7.0-rc.1
- v7.0-beta.4
- v7.0-beta.3
- v7.0-beta.2
- v7.0-beta.1
- 6.x-dev
- v6.1.0
- v6.0.6
- v6.0.5
- v6.0.4
- v6.0.3
- v6.0.2
- v6.0.1
- v6.0
- v6.0.0-RC2
- v6.0.0-RC1
- v5.7
- v5.6
- v5.5
- v5.4
- v5.3
- v5.2
- v5.1
- v5.0
- v5.0-beta.1
- v4.3
- v4.2
- v4.1
- v4.0
- v4.0-beta.2
- 4.0-beta.1
- v3.1
- v3.0
- v3.0-beta2
- v3.0-beta1
- v2.0
- v1.4
- v1.3
- v1.2
- v1.1
- v1.0
- v0.1.6
- v0.1.5
- v0.1.4
- v0.1.3
- v0.1.2
- v0.1.1
- v0.1.0
- dev-master
- dev-fix/log-general-handler-payload
- dev-extract-connection-interface
- dev-actions-fix
- dev-manual-testing-fixes
- dev-new-features
- dev-l12-bump
This package is auto-updated.
Last update: 2026-11-20 13:43:27 UTC
README
Important
Repository & Package Migration Announcement
RabbitEvents has moved to its own dedicated organization!
- GitHub Repository: github.com/rabbitevents/rabbitevents (formerly
nuwber/rabbitevents) - Composer Package:
rabbitevents/rabbitevents(starting from version 10.0)
Please update your composer.json to require rabbitevents/rabbitevents:^10.1. All PHP classes and namespaces (RabbitEvents\...) remain identical, so no application code changes are required.
Let's imagine a use case: a User made a payment. You need to handle this payment, register the user, send him emails, send analytics data to your analysis system, and so on. The modern infrastructure requires you to create microservices that do their specific job and only it: one handles payments, one is for user management, one is the mailing system, one is for analysis. How to let all of them know that a payment succeeded and handle this message? The answer is "To use RabbitEvents".
RabbitEvents helps you publish an event and handle it seamlessly in other applications across your microservice ecosystem.
Demo
Table of Contents
- Installation via Composer
- Upgrade from 9.x to 10.x
- Quick Start
- Reliability & Guarantees (Zero-DB Architecture)
- Listeners & Payloads
- Custom Serializers
- Extensions & Ecosystem
- Examples
- Speeding up RabbitEvents
- Testing
- Non-standard use
- License
Installation via Composer
You can use Composer to install RabbitEvents into your Laravel project:
composer require rabbitevents/rabbitevents
Configuration
After installing RabbitEvents, publish its configuration file and service provider using the rabbitevents:install command:
php artisan rabbitevents:install
This installs config/rabbitevents.php and app/Providers/RabbitEventsServiceProvider.php.
<?php use Enqueue\AmqpTools\RabbitMqDlxDelayStrategy; return [ 'default' => env('RABBITEVENTS_CONNECTION', 'rabbitmq'), 'default_serializer' => \RabbitEvents\Foundation\Serialization\JsonSerializer::class, 'connections' => [ 'rabbitmq' => [ 'driver' => 'rabbitmq', 'exchange' => env('RABBITEVENTS_EXCHANGE', 'events'), 'durable' => env('RABBITEVENTS_QUEUE_DURABLE', true), 'host' => env('RABBITEVENTS_HOST', 'localhost'), 'port' => env('RABBITEVENTS_PORT', 5672), 'user' => env('RABBITEVENTS_USER', 'guest'), 'pass' => env('RABBITEVENTS_PASSWORD', 'guest'), 'vhost' => env('RABBITEVENTS_VHOST', 'events'), 'delay_strategy' => env('RABBITEVENTS_DELAY_STRATEGY', RabbitMqDlxDelayStrategy::class), 'ssl' => [ 'is_enabled' => env('RABBITEVENTS_SSL_ENABLED', false), 'verify_peer' => env('RABBITEVENTS_SSL_VERIFY_PEER', true), 'cafile' => env('RABBITEVENTS_SSL_CAFILE'), 'local_cert' => env('RABBITEVENTS_SSL_LOCAL_CERT'), 'local_key' => env('RABBITEVENTS_SSL_LOCAL_KEY'), 'passphrase' => env('RABBITEVENTS_SSL_PASSPHRASE', ''), ], 'read_timeout' => env('RABBITEVENTS_READ_TIMEOUT', 3.0), 'write_timeout' => env('RABBITEVENTS_WRITE_TIMEOUT', 3.0), 'connection_timeout' => env('RABBITEVENTS_CONNECTION_TIMEOUT', 3.0), 'heartbeat' => env('RABBITEVENTS_HEARTBEAT', 0), 'persisted' => env('RABBITEVENTS_PERSISTED', false), 'lazy' => env('RABBITEVENTS_LAZY', true), 'qos' => [ 'global' => env('RABBITEVENTS_QOS_GLOBAL', false), 'prefetch_size' => env('RABBITEVENTS_QOS_PREFETCH_SIZE', 0), 'prefetch_count' => env('RABBITEVENTS_QOS_PREFETCH_COUNT', 1), ], ], ], // Move messages that failed all tries to `{queue}.failed` instead of dropping them. 'failed_queue' => [ 'enabled' => env('RABBITEVENTS_FAILED_QUEUE_ENABLED', true), ], 'logging' => [ 'enabled' => env('RABBITEVENTS_LOG_ENABLED', false), 'level' => env('RABBITEVENTS_LOG_LEVEL', 'info'), 'channel' => env('RABBITEVENTS_LOG_CHANNEL'), ], ];
Upgrade from 9.x to 10.x
Compatibility With 9.x
10.x and 9.x services can run side by side and be upgraded one by one, with no queue migration:
- Exchanges, queues and delay queues are declared exactly as in 9.x, so 9.x and 10.x workers can even consume the same queue.
- Messages keep the 9.x format. 10.x only adds the AMQP
message_idand thetrace_contextproperty, which 9.x ignores. - A message released for retry by one version is handled by the other, with
x-attemptspreserved. - A 9.x message that fails in a 10.x worker is moved to
{queue}.failedand gets amessage_idthere, so it can be retried or deleted by ID.
Breaking Changes & Requirements
1. Composer Package Name Changed
RabbitEvents is now an independent project maintained under rabbitevents/rabbitevents.
To upgrade, replace nuwber/rabbitevents in your composer.json or run:
composer remove nuwber/rabbitevents composer require rabbitevents/rabbitevents:^10.1
Zero Namespace Changes: The PHP namespace remains
RabbitEvents\.... You do not need to change anyusestatements or event classes in your codebase.
2. PHP 8.2+ and Laravel 11+ Required
RabbitEvents 10.x requires PHP 8.2 or greater and Laravel 11.0 or greater. Distributed tracing uses Laravel's native Context facade.
3. Return Value of publish()
publish() and Event::publish() now return the message ID (UUIDv4) instead of void. It is null for an afterCommit event published inside a transaction, because the message is sent only on commit.
$messageId = publish('user.registered', $payload);
4. Failed Messages Are Kept
In 9.x a message that failed all its tries was dropped. 10.x moves it to {queue}.failed. Set RABBITEVENTS_FAILED_QUEUE_ENABLED=false to keep the 9.x behaviour.
5. Contracts for Custom Transports
Contracts\ConnectionrequiresmakeFailedQueue(string $queueName): FailedDestination, declaring the failed queue of$queueName.Contracts\QueueConsumerrequiresrequeue(array $messages), which returns messages to the queue keeping their order.Contracts\TransportMessagerequiressetRoutingKey(),getMessageId()andsetMessageId().- A producer that can delay a delivery implements
Contracts\DelaysDelivery; listener retries of other producers are sent right away.
What's New in 10.x
- Failed message management: Messages that failed all tries are kept in
{queue}.failedand managed withrabbitevents:failed,retry,forgetandflush. - Message IDs: Every published message has a UUID, returned by
publish()and shown in listener logs. - Transactional publishing: Publish events only after the database transaction commits, via
ShouldPublishAfterCommitor->afterCommit(). - Distributed tracing: Laravel
Contextis propagated from publishers to listeners. - Deduplication hook:
Listener\Contracts\Deduplicator, implemented by the optionalrabbitevents/deduplicationpackage. - Onion-style listener middleware with
$next, and new testing assertions (assertPublishedTimes(),assertNothingPublished()).
Quick Start
1. Publishing Events
Method A: Using the publish() helper
The quickest way to dispatch an event from anywhere in your application:
$messageId = publish('user.registered', [ 'user_id' => 123, 'email' => 'alex@example.com', 'created_at' => now()->toIso8601String(), ]); logger()->info("Published event user.registered with ID: {$messageId}");
Method B: Using an Event Class
Define a dedicated event class implementing ShouldPublish:
namespace App\Events; use App\Models\User; use RabbitEvents\Publisher\ShouldPublish; use RabbitEvents\Publisher\Support\Publishable; class UserRegistered implements ShouldPublish { use Publishable; public function __construct(public User $user) { } public function publishEventKey(): string { return 'user.registered'; } public function toPublish(): array { return [ 'user_id' => $this->user->id, 'email' => $this->user->email, ]; } }
Dispatch it just like standard Laravel events:
$messageId = UserRegistered::publish($user);
2. Listening for Events
Method A: Using PHP Attributes (Recommended)
Define a listener and tag it with #[Listener]:
namespace App\Listeners; use RabbitEvents\Listener\Attributes\Listener; #[Listener('user.registered')] class SendWelcomeEmail { public function handle(array $payload): void { $userId = $payload['user_id']; $email = $payload['email']; // Send email or trigger internal processing... } }
Method B: Using RabbitEventsServiceProvider
Register listeners explicitly in app/Providers/RabbitEventsServiceProvider.php:
protected array $listen = [ 'user.registered' => [ \App\Listeners\SendWelcomeEmail::class, ], 'order.*' => [ \App\Listeners\OrderAuditSubscriber::class, ], ];
Start the Worker
Run the listener worker from your terminal or process manager (Supervisor, Docker, Kubernetes):
php artisan rabbitevents:listen user.registered
Or listen to several events, or to all registered events when none are given:
php artisan rabbitevents:listen user.registered,order.completed php artisan rabbitevents:listen
Reliability & Guarantees (Zero-DB Architecture)
RabbitEvents is designed for microservice environments where services should remain isolated and autonomous. It provides enterprise-level reliability without requiring MySQL tables, Redis, or database migrations.
Message IDs & Observability
Every published event automatically receives a unique RFC 4122 UUIDv4 message_id.
$messageId = publish('payment.processed', ['amount' => 99.00]); // $messageId => "3fa85f64-5717-4562-b3fc-2c963f66afa6"
Listener worker console logs display the message ID and execution time in real-time:
[3fa85f64-5717-4562-b3fc-2c963f66afa6] [2026-10-20 12:00:00] Processing: payment.processed:App\Listeners\HandlePayment@handle
[3fa85f64-5717-4562-b3fc-2c963f66afa6] [2026-10-20 12:00:00] Processed: payment.processed:App\Listeners\HandlePayment@handle (14.22ms)
Retries
A listener that throws is tried again after --sleep seconds, up to --tries times. A listener class can set its own limits with properties, tries() / backoff() methods or #[Tries] / #[Backoff] attributes, as Laravel queued listeners do, and each listener of a message counts its own tries:
class SendInvoice { public int $tries = 5; public array $backoff = [1, 5, 30]; // seconds after the 1st, 2nd and every further failed try public function handle(array $payload): void { // ... } }
See the Listener documentation for details.
Failed Messages (Dead Letter Queue)
When a listener exhausts its tries (--tries=3 or its own $tries), times out, or throws FailedException, RabbitEvents moves the message to the {queue}.failed dead letter queue (DLQ) instead of dropping it.
The failed message keeps its payload, message_id and trace_context, and gets the properties x-failed-at, x-original-routing-key, x-original-queue, x-exception-class, x-exception-message, x-exception-trace and x-listener. Listeners that already succeeded are recorded in x-succeeded-listeners and skipped on retry.
Why
{queue}.failedinstead ofx-dead-letter-exchangeon the main queue? Publishing failed messages directly from the worker records the PHP exception, the failing listener, andx-succeeded-listenerson the message, and leaves the main queue without extra arguments so 9.x and 10.x workers can share it without a406 PRECONDITION_FAILEDmigration. RabbitMQ's native dead-letter exchange (DLX+TTL) is used byRabbitMqDlxDelayStrategyfor delayed retries between attempts.
# List failed messages, for all registered events or a given scope php artisan rabbitevents:failed php artisan rabbitevents:failed --events="user.registered,order.*" php artisan rabbitevents:failed --queue=my-custom-queue # Move a failed message, or all of them, back to the original queue php artisan rabbitevents:retry 3fa85f64-5717-4562-b3fc-2c963f66afa6 php artisan rabbitevents:retry --all --events="user.registered" # Delete one failed message, or all of them php artisan rabbitevents:forget 3fa85f64-5717-4562-b3fc-2c963f66afa6 php artisan rabbitevents:flush
See the Listener documentation for details.
Kill Switch
When a dependency of the listeners is down and most messages fail, a worker with the kill switch stops consuming for a while instead of moving the whole queue to {queue}.failed. The untouched messages stay in the queue. It is disabled by default:
RABBITEVENTS_KILL_SWITCH_ENABLED=true
See the Listener documentation for the thresholds and events.
Deduplication
RabbitMQ delivers a message at least once: when the acknowledgement doesn't reach it (lost connection, killed worker), it delivers the message again. RabbitEvents relies on RabbitMQ only and doesn't deduplicate such redeliveries, so listeners should be idempotent. If your service has a cache store shared by its workers, the optional rabbitevents/deduplication package skips messages redelivered after they were handled. See the Listener documentation.
Transactional Publishing (afterCommit)
Prevent race conditions by ensuring events are published only after database transactions commit. You can implement ShouldPublishAfterCommit or call ->afterCommit():
use RabbitEvents\Publisher\ShouldPublish; use RabbitEvents\Publisher\ShouldPublishAfterCommit; use RabbitEvents\Publisher\Support\Publishable; // Option 1: Marker interface class InvoicePaid implements ShouldPublishAfterCommit { use Publishable; } // Option 2: Per publish, via the Publishable trait publish((new OrderShipped($order))->afterCommit());
The
$afterCommitproperty is declared by thePublishabletrait, so don't redeclare it in your event class: PHP rejects a trait property redeclared with a different default.
Outbox
publish() sends the message right away: if the broker can't be reached, the exception reaches your code and the message isn't sent. If your service has a database, the optional rabbitevents/outbox package writes published messages to a table instead (in the transaction of the event, when there is one) and delivers them from there: it retries until a message is sent or its time to live is over, so a stale message is never sent, and it can coalesce the messages of one object. The core only has the hook, Publisher\Contracts\Outbox; it doesn't need a database. See the Publisher documentation.
Distributed Tracing & Context Propagation
Laravel Context data is sent with each message in the trace_context property and added to the listener's Context while the message is handled:
use Illuminate\Support\Facades\Context; // In Service A: Context::add('trace_id', (string) \Illuminate\Support\Str::uuid()); publish('order.created', $orderData); // In Service B (Listener): // Context::get('trace_id') is automatically restored!
Listeners & Payloads
How the payload is passed to your listener depends on the serialization format:
JSON (Default): The payload is decoded as an associative array.
public function handle(array $payload) { // $payload['key'] }
Protobuf: The payload is passed as the Message Object itself.
public function handle(\Google\Protobuf\Internal\Message $message) { // $message->getSomething() }
Custom Serializers
You can implement your own serializer by implementing RabbitEvents\Foundation\Contracts\Serializer and RabbitEvents\Foundation\Contracts\ContentType.
use RabbitEvents\Foundation\Contracts\Serializer; use RabbitEvents\Foundation\Contracts\ContentType; use RabbitEvents\Foundation\Contracts\Payload; use RabbitEvents\Foundation\Contracts\TransportMessage; class MySerializer implements Serializer { public function serialize(mixed $payload): Payload { /* ... */ } public function deserialize(TransportMessage $message): Payload { /* ... */ } public function contentType(): ContentType { return new MyContentType(); } public function canSerialize(mixed $payload): bool { /* ... */ } }
Register your serializer in a ServiceProvider:
$registry = $this->app->make(\RabbitEvents\Foundation\Serialization\SerializerRegistry::class); $registry->register(new MySerializer());
New serializers are prepended to the registry, so they can override default behavior if they claim the payload.
Extensions & Ecosystem
- Redis Streams Transport - Redis Streams transport driver for RabbitEvents.
- Deduplication - Skips redelivered messages using a Laravel cache store shared by the workers.
- Outbox - Delivers published messages through a database outbox, retried until sent or expired.
- Symfony Bundle - Official Symfony integration bundle for RabbitEvents.
- Protobuf Support - Official Google Protobuf serialization support for RabbitEvents. Required for using Protobuf messages.
Examples
Practical implementation examples and ready-to-use boilerplate classes are available in the examples directory:
- Publishers:
UserCreated.php- Standard publishable event with payload mapping and publishing helper.TransactionalEvent.php- Transaction-safe event published only after DB commits (ShouldPublishAfterCommit).ContextTracingEvent.php- Distributed tracing via LaravelContextand capturing the returned message ID.
- Listeners & Subscribers:
AttributeListener.php- Clean attribute-based listener with#[Listener].OrderEventsSubscriber.php- Handling multiple domain events within a single subscriber class.IdempotentPaymentListener.php- Idempotent processing guarded by a business key, and trace ID extraction.WildcardListener.php- Wildcard event pattern matching and conditional propagation.Listener.php- Standard listener with a custom middleware stack.
- Configuration & Providers:
RabbitEventsServiceProvider.php- Explicit listener mapping via the$listenarray.ExampleMiddleware.php- Custom event middleware implementation.
Speeding up RabbitEvents
To enhance the performance of RabbitEvents, consider installing the php-amqp extension along with the enqueue/amqp-ext package.
By doing so, RabbitEvents will utilize the enqueue/amqp-ext package instead of the default enqueue/amqp-lib package.
This substitution is advantageous because the C-written php-amqp package significantly outperforms the PHP-written enqueue/amqp-lib package.
You can install the php-amqp extension using the following command:
pecl install amqp
or use the way you prefer. More about it can be found here.
Next, install the enqueue/amqp-ext package with the following command:
composer require enqueue/amqp-ext
No additional configuration is required.
Testing
We always write tests. Tests in our applications contain many mocks and fakes to test how events are published.
There is the PublishableEventTesting trait that provides assertion methods in an Event class that you want to test.
Event.php
<?php namespace App\RabbitEvents; use RabbitEvents\Publisher\ShouldPublish; use RabbitEvents\Publisher\Support\Publishable; use RabbitEvents\Publisher\Support\PublishableEventTesting; class Event implements ShouldPublish { use Publishable; use PublishableEventTesting; public function __construct(private array $payload) { } public function publishEventKey(): string { return 'something.happened'; } public function toPublish(): array { return $this->payload; } }
Test.php
<?php use \App\RabbitEvents\Event; use \App\RabbitEvents\AnotherEvent; Event::fake(); Event::publish(['key1' => 'value1', 'key2' => 'value2']); // Assert event was published Event::assertPublished(); // Assert with closure Event::assertPublished(function ($event, $payload) { return $payload['key1'] === 'value1'; }); // Assert published exact number of times Event::assertPublishedTimes(1); // Assert an event was not published AnotherEvent::assertNotPublished();
assertNothingPublished() checks that no event was published at all:
Event::fake(); $service->doNothingInteresting(); Event::assertNothingPublished();
fake() records events instead of sending them, returns a message ID from publish() like the real publisher, and keeps the afterCommit behaviour: an event published inside a transaction is recorded only when the transaction commits.
Don't forget to call \Mockery::close() in tearDown or similar methods of your tests.
Non-standard use
If you're using only one part of RabbitEvents, you should know a few things:
-
You remember, we're using RabbitMQ as the transport layer. In the RabbitMQ Documentation, you can find examples of how to publish your messages using a routing key. This routing key is the event name, like
something.happenedfrom the examples above. -
RabbitEvents expects that a message body is a JSON-encoded array. Every element of an array will be passed to a Listener as a separate variable. For example:
[
{
"key": "value"
},
"string",
123
]
There are 3 elements in this array, so 3 variables will be passed to a Listener (an array, a string, and an integer). If an associative array is being passed, the Dispatcher wraps this array by itself.
License
RabbitEvents is open-sourced software licensed under the MIT license.