Search by

nuwber / rabbitevents

masterjus

This package is abandoned and no longer maintained. The author suggests using the rabbitevents/rabbitevents package instead.

The RabbitEvents package for Laravel

Package info

github.com/nuwber/rabbitevents

Issues

pkg:composer/nuwber/rabbitevents

Fund package maintenance!

masterjus

Statistics

Installs: 556 346

Dependents: 2

Suggesters: 0

Stars: 119

v10.1.0 2026-10-28 14:36 UTC

README

Tests Status Coverage Status Total Downloads at Nuwber Total Downloads Latest Version License

Important

Repository & Package Migration Announcement

RabbitEvents has moved to its own dedicated organization!

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

rabbit-events-demo

Table of Contents

  1. Installation via Composer
  2. Upgrade from 9.x to 10.x
  3. Quick Start
  4. Reliability & Guarantees (Zero-DB Architecture)
  5. Listeners & Payloads
  6. Custom Serializers
  7. Extensions & Ecosystem
  8. Examples
  9. Speeding up RabbitEvents
  10. Testing
  11. Non-standard use
  12. 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_id and the trace_context property, which 9.x ignores.
  • A message released for retry by one version is handled by the other, with x-attempts preserved.
  • A 9.x message that fails in a 10.x worker is moved to {queue}.failed and gets a message_id there, 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 any use statements 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\Connection requires makeFailedQueue(string $queueName): FailedDestination, declaring the failed queue of $queueName.
  • Contracts\QueueConsumer requires requeue(array $messages), which returns messages to the queue keeping their order.
  • Contracts\TransportMessage requires setRoutingKey(), getMessageId() and setMessageId().
  • 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}.failed and managed with rabbitevents:failed, retry, forget and flush.
  • 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 ShouldPublishAfterCommit or ->afterCommit().
  • Distributed tracing: Laravel Context is propagated from publishers to listeners.
  • Deduplication hook: Listener\Contracts\Deduplicator, implemented by the optional rabbitevents/deduplication package.
  • 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}.failed instead of x-dead-letter-exchange on the main queue? Publishing failed messages directly from the worker records the PHP exception, the failing listener, and x-succeeded-listeners on the message, and leaves the main queue without extra arguments so 9.x and 10.x workers can share it without a 406 PRECONDITION_FAILED migration. RabbitMQ's native dead-letter exchange (DLX + TTL) is used by RabbitMqDlxDelayStrategy for 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 $afterCommit property is declared by the Publishable trait, 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:

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:

  1. 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.happened from the examples above.

  2. 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.