Search by

jardisadapter / messaging

jardis

Multi-transport messaging for Redis, Kafka, RabbitMQ, and Database with automatic serialization and consumer groups; a building block of the open-source foundation that Jardis-generated DDD code runs on

v1.3.0 2026-12-03 17:39 UTC

This package is auto-updated.

Last update: 2026-12-03 19:33:12 UTC


README

Build Status License: MIT PHP Version PHPStan Level PSR-12

Part of Jardis — the Domain-Driven Design platform for PHP. You model your domain; Jardis generates the production-ready hexagonal code (DTOs, Command/Query handlers, repositories, persistence). This package is part of the open-source foundation that generated code runs on.

A message queue for PHP with a unified API across Redis, Kafka, RabbitMQ, Database, and InMemory transports. ConnectionFactory creates transport-specific connections; PublisherFactory and ConsumerFactory produce typed publishers and consumers from those connections. MessagePublisher and MessageConsumer are immutable facades that accept one or more transport instances via constructor injection and provide automatic serialization, priority-based failover, and graceful shutdown.

Features

  • 4 Transports + InMemory — Redis (Pub/Sub and Streams), Kafka, RabbitMQ, Database (PDO), InMemory (testing)
  • Unified Publish/Consume API — publish(topic, message) and consume(topic, handler) across all transports
  • Immutable Facades — MessagePublisher and MessageConsumer via variadic constructor injection
  • Automatic Serialization — Arrays and objects encoded to JSON on publish, decoded transparently on consume
  • Consumer Groups — Redis Streams and Kafka for horizontal scaling
  • Priority Failover — Constructor order determines priority; first healthy transport wins
  • Lazy Connection — MessagingService defers publisher and consumer creation until first use
  • Database Transport — PDO-based messaging with Point-to-Point and Fan-Out modes, no external broker required
  • External Connections — Wrap existing Redis, PDO, AMQP, or Kafka clients via ConnectionFactory::from*()
  • Message Validation — Payload validation before transmission via MessageValidator
  • Graceful Shutdown — SIGTERM/SIGINT handling enabled automatically on consume()

Installation

composer require jardisadapter/messaging

Optional extensions (install only what you need):

  • ext-redis — Redis Streams/Pub-Sub transport
  • ext-rdkafka — Apache Kafka transport
  • ext-amqp — RabbitMQ transport

PDO (Database transport) is always available via ext-pdo.

Quick Start

use JardisAdapter\Messaging\MessagePublisher;
use JardisAdapter\Messaging\MessageConsumer;
use JardisAdapter\Messaging\Factory\ConnectionFactory;
use JardisAdapter\Messaging\Factory\PublisherFactory;
use JardisAdapter\Messaging\Factory\ConsumerFactory;
use JardisAdapter\Messaging\Handler\CallbackHandler;

$connFactory = new ConnectionFactory();
$pubFactory  = new PublisherFactory();
$conFactory  = new ConsumerFactory();

// Create and share a Redis connection
$redisConn = $connFactory->redis('localhost', 6379);

// Publish
$publisher = new MessagePublisher($pubFactory->redis($redisConn));
$publisher->publish('orders', ['order_id' => 42, 'total' => 99.99]);

// Consume
$consumer = new MessageConsumer($conFactory->redis($redisConn));
$consumer->consume('orders', new CallbackHandler(function (string|array $message, array $metadata): bool {
    // $message = ['order_id' => 42, 'total' => 99.99]  (auto-deserialized)
    return true; // true = ACK, false = reject/requeue
}));

Priority Failover

Constructor order determines priority — first argument is tried first. On MessageException, the next transport is used automatically.

$primary = $connFactory->redis('redis-primary');
$secondary = $connFactory->redis('redis-secondary');

$publisher = new MessagePublisher(
    $pubFactory->redis($primary),     // tried first
    $pubFactory->redis($secondary),   // fallback if primary fails
);
$publisher->publish('orders', ['order_id' => 42]);

Transports

Redis

Supports both Pub/Sub (default) and Streams mode.

$redisConn = $connFactory->redis('localhost', 6379);

// Pub/Sub (default)
$publisher = new MessagePublisher($pubFactory->redis($redisConn));

// Streams
$publisher = new MessagePublisher($pubFactory->redis($redisConn, useStreams: true));

// Consumer groups (Streams only)
$consumer = new MessageConsumer($conFactory->redis($redisConn, useStreams: true));
$consumer->consume('orders', $handler, [
    'group'    => 'order-processors',  // auto-created if missing
    'consumer' => 'worker-1',
    'block'    => 5000,
    'count'    => 1,
]);

Kafka

Separate connection types for producer and consumer. Consumer group ID is configured on the connection. ConnectionFactory::kafka()/kafkaConsumer() take the broker list (host:port[,host:port,...]) as the host argument — there is no separate port argument or env key; KAFKA_BROKERS is the canonical key in the Kernel bootstrap. Supplying credentials switches the connection to SASL_SSL/SASL_PLAIN automatically.

// Producer
$kafkaConn = $connFactory->kafka('kafka:9092');
$publisher = new MessagePublisher($pubFactory->kafka($kafkaConn));
$publisher->publish('invoices', ['invoice_id' => 7], ['key' => 'partition-key']);

// Consumer (groupId is part of connection)
$kafkaConsumerConn = $connFactory->kafkaConsumer('kafka:9092', 'invoice-processor');
$consumer = new MessageConsumer($conFactory->kafka($kafkaConsumerConn));
$consumer->consume('invoices', $handler);

RabbitMQ

Queue-based messaging with automatic ACK/NACK handling.

$rabbitConn = $connFactory->rabbitMq('localhost', 5672, 'guest', 'guest');

$publisher = new MessagePublisher($pubFactory->rabbitMq($rabbitConn));
$publisher->publish('order.created', ['orderId' => 42]);

$consumer = new MessageConsumer($conFactory->rabbitMq($rabbitConn, 'order-queue'));
$consumer->consume('order.created', $handler);

Database (PDO)

No external broker required — uses the application's existing database. Supports MySQL (incl. MariaDB), PostgreSQL, and SQLite. The consumer determines the SQL dialect from the PDO driver on its first consume(); an unknown driver (any other) throws a ConnectionException there, never in the constructor (behaviour change: formerly an unknown driver ran point-to-point unchecked and used the PostgreSQL/SQLite upsert in fan-out mode). The publisher does the same on its first publish() (behaviour change: formerly it inserted on any driver); the ConnectionException is a MessageException, so a MessagePublisher tries its next layer.

Waking (PostgreSQL: LISTEN/NOTIFY). On PostgreSQL the publisher stores the event and notifies the consumers of its topic with pg_notify in one statement; a consumer with nothing to do waits on its topic's channel (LISTEN before the first fetch, UNLISTEN when consume() ends) and is woken at once — pollingIntervalMs stays the upper bound, so an event stored without a notification (another writer, a raw INSERT) is still found by polling. The channel is jm_ + md5 of table and topic, never the raw topic. MySQL/MariaDB and SQLite poll every pollingIntervalMs as before. Notifications reach a session only outside a transaction: with a transaction of the caller open on the consumer's PDO, the consumer polls. PgBouncer in transaction mode breaks LISTEN (the listening server session is handed to other clients) — the consumer then falls back to the polling bound at best; use session pooling or a direct connection.

use JardisAdapter\Messaging\Config\DatabaseTransportOptions;

$dbConn = $connFactory->database('mysql:host=localhost;dbname=app', 'user', 'pass');

$options = new DatabaseTransportOptions(
    table: 'domain_events',
    deleteAfterProcessing: false,  // soft delete (default)
    pollingIntervalMs: 1000,
    batchSize: 10,
    maxAttempts: 3,
);

$publisher = new MessagePublisher($pubFactory->database($dbConn, $options));
$consumer = new MessageConsumer($conFactory->database($dbConn, $options));

// Point-to-Point (default): one consumer per event
$consumer->consume('OrderCreated', $handler);

// Fan-Out: multiple consumer groups process the same event
$consumer->consume('InvoiceCreated', $handler, ['group' => 'email-service']);
$consumer->consume('InvoiceCreated', $handler, ['group' => 'pdf-service']);

Failure semantics (behaviour change). Earlier versions stopped the consume loop when a handler returned false and re-threw a handler exception, so one broken event halted the whole worker. Now a handler failure concerns only its own event, in Point-to-Point and Fan-Out mode alike:

  • the handler returns false or throws → attempts + 1 and last_error is recorded (Handler returned false or the exception message) on the event row (Point-to-Point) or on the group's subscription row (Fan-Out);
  • the loop does not stop and the exception is not re-thrown — the next event of the batch is processed;
  • the failed event is fetched again on a later poll while attempts < maxAttempts; afterwards it stays unprocessed (processed_at IS NULL, last_error set) and is no longer fetched.

Only a database error ends the loop with a ConsumerException: when the failed attempt itself cannot be recorded (the message names the database error and the handler error — continuing would retry the event without counting it), or when polling or marking an event as processed fails. With handlerInTransaction: true, a PDO without PDO::ERRMODE_EXCEPTION is rejected with a ConsumerException as well.

Several workers — handlerInTransaction. On PostgreSQL and MySQL/MariaDB several consumer processes may poll the same topic (and group): per group exactly one worker processes an event. The option DatabaseTransportOptions::$handlerInTransaction chooses how:

handlerInTransaction How an event is processed (PostgreSQL, MySQL/MariaDB)
false (default) Under a session lock — pg_try_advisory_lock / GET_LOCK(name, 0), not waiting; a locked event is skipped. The consumer opens no transaction; the handler may run its own. The outcome is booked in autocommit, then the lock is released.
true In a worker transaction: the event row (fan-out: the group's subscription row) is locked with FOR UPDATE SKIP LOCKED, the handler runs in a savepoint, its writes and the outcome are committed together. Requires PDO::ERRMODE_EXCEPTION.

With the option, MariaDB ≥ 10.6 or MySQL ≥ 8.0.1 is required — older versions do not know SKIP LOCKED. On SQLite the option is ignored: SQLite allows one writer at a time, so run one worker — no lock, no transaction. No schema change is needed for either way.

Open transaction — what the consumer does with transactions on the PDO it was given:

  • Without the option: the handler may call beginTransaction() … commit() itself. A transaction it leaves open is rolled back (its writes are gone) and counted as a failed attempt (last_error: Handler left its transaction open; rolled back); the next event runs.
  • With the option: the handler already runs inside the worker transaction; its own beginTransaction() would fail on PDO — use savepoints, or a transaction helper that takes a savepoint when a transaction is open. A failed handler is rolled back to its savepoint before the attempt is counted.
  • A transaction opened by the caller before consume() is never committed or rolled back by the consumer; the outcome is booked inside it (see the limits below).
  • Publisher inside an open transaction: publish() writes the event in the caller's transaction (Transactional Outbox). Event and notification become visible only with the COMMIT — PostgreSQL sends the notification at commit; after a ROLLBACK there is neither event nor notification:
use JardisAdapter\Messaging\Publisher\DatabasePublisher;

$pdo = new PDO('pgsql:host=localhost;dbname=app', 'user', 'pass');
$publisher = new DatabasePublisher($connFactory->fromPdo($pdo), new DatabaseTransportOptions());

$pdo->beginTransaction();
$pdo->prepare('INSERT INTO orders (id) VALUES (:id)')->execute(['id' => 42]);
$publisher->publish('OrderCreated', '{"orderId": 42}');  // not visible, no notification yet
$pdo->commit();                                          // event stored, consumers woken
use JardisAdapter\Messaging\Consumer\DatabaseConsumer;

// Default (handlerInTransaction: false): the handler owns its transaction — plain PDO
$pdo = new PDO('pgsql:host=localhost;dbname=app', 'user', 'pass');
$consumer = new DatabaseConsumer($connFactory->fromPdo($pdo), new DatabaseTransportOptions());

// DatabaseConsumer passes the raw payload; only the MessageConsumer facade decodes JSON
$consumer->consume('OrderCreated', function (string $message, array $metadata) use ($pdo): bool {
    $order = json_decode($message, true, 512, JSON_THROW_ON_ERROR);
    $pdo->beginTransaction();
    $pdo->prepare('INSERT INTO invoices (order_id) VALUES (:id)')->execute(['id' => $order['orderId']]);
    $pdo->commit();
    return true;
});

Keep handlers idempotent (without the option). The handler's commit and the booking of the outcome are two statements. If the worker dies between them, the event is still pending and runs again — at-least-once. handlerInTransaction: true closes this gap (handler writes and outcome commit together).

Limits of the session lock (without the option) — the lock belongs to the database session:

  • PgBouncer in transaction mode (or any pooler that hands one server session to several clients) breaks it — the lock may stay on a session another client gets. Use session pooling or a direct connection.
  • Persistent connections (PDO::ATTR_PERSISTENT): a lock not released by a crashed request stays with the reused connection. Do not use them for consumers.
  • Keepalive: a dead client whose TCP connection is not torn down holds its lock until the server notices (TCP keepalive / wait_timeout); a killed process releases it at once.
  • Caller transaction open before consume(): the booking is invisible to other sessions until it ends, so the lock is kept until the session ends (not released after the event). Under REPEATABLE READ the re-read sees the state from the start of that transaction. End such a transaction before consuming.

With the option the worker transaction stays open while the handler runs; for a handler that may hang outside the database (e.g. a remote call), set idle_in_transaction_session_timeout (PostgreSQL) on the consumer's connection.

Schema — create the tables in your application database:

Database File
MySQL / MariaDB resources/sql/mysql.sql
PostgreSQL resources/sql/pgsql.sql
SQLite resources/sql/sqlite.sql

The files follow the Jardis package convention resources/sql/<driver>.sql (driver = PDO driver family), so a project's bin/console db:import picks them up from vendor/jardisadapter/messaging/. All files define the same tables, columns and indexes. The PostgreSQL file is covered by an integration test against a real PostgreSQL (tests/Integration/Consumer/DatabasePostgresConsumerTest.php), the SQLite file by tests/Unit/DatabaseSchemaFilesTest.php.

InMemory (Testing)

Synchronous in-memory transport for unit and integration tests.

use JardisAdapter\Messaging\Transport\InMemoryTransport;

$transport = new InMemoryTransport();

$publisher = new MessagePublisher($pubFactory->inMemory($transport));
$consumer  = new MessageConsumer($conFactory->inMemory($transport));

$publisher->publish('test', ['id' => 1]);
$transport->getMessageCount('test');  // 1

$consumer->consume('test', $handler, ['limit' => 5]);

External Connections

Wrap existing connections from legacy systems, DI containers, or frameworks.

// Existing Redis instance
$redisConn = $connFactory->fromRedis($existingRedis, manageLifecycle: false);
$publisher = new MessagePublisher($pubFactory->redis($redisConn));

// Existing PDO instance
$dbConn = $connFactory->fromPdo($existingPdo, manageLifecycle: false);

// Lazy PDO provider: called on the first getClient(), then reused (shared connection, no own connect())
$dbConn = $connFactory->fromDbConnection(fn (): PDO => $container->get(PDO::class), manageLifecycle: false);

// Existing AMQP connection
$rabbitConn = $connFactory->fromAmqp($amqpConnection, exchangeName: 'custom');

// Existing Kafka producer/consumer
$kafkaProducerConn = $connFactory->fromKafkaProducer($producer, flushOnDisconnect: true);
$kafkaConsumerConn = $connFactory->fromKafkaConsumer($consumer);

When manageLifecycle: false, disconnect() is a no-op — the external system owns the connection lifecycle.

fromDbConnection(Closure(): PDO $provider, bool $manageLifecycle = false) is the lazy variant of fromPdo(): construction, isConnected(), connect() and disconnect() never call the provider; the first getClient() resolves it exactly once and memoizes the PDO (only on success). An exception thrown by the provider is wrapped in a ConnectionException (original as previous) — like every other transport reports open failures — and is not memoized (the next access calls the provider again). It reaches publish()/consume() as ConnectionException; DatabasePublisher/DatabaseConsumer wrap only PDOException (into PublishException/ConsumerException), so the ConnectionException is not re-wrapped. ExternalDatabaseConnection also accepts the Closure directly.

MessagingService (Lazy Loading)

Defers publisher and consumer creation until first use. Ideal for DI containers.

use JardisAdapter\Messaging\MessagingService;

$messaging = new MessagingService(
    publisherFactory: fn() => new MessagePublisher($pubFactory->redis($redisConn)),
    consumerFactory:  fn() => new MessageConsumer($conFactory->redis($redisConn)),
);

$messaging->publish('notifications', ['type' => 'email', 'to' => 'user@example.com']);
$messaging->consume('notifications', $handler);

$messaging->getPublisher();  // MessagePublisherInterface
$messaging->getConsumer();   // MessageConsumerInterface

Error Handling

All exceptions extend MessageException:

Exception When
ConnectionException Connection fails, getClient() called without connect(), a lazy fromDbConnection() provider throws, DatabaseConsumer::consume() or DatabasePublisher::publish() on an unsupported PDO driver
PublishException Publishing fails, serialization error, validation failure
ConsumerException Consumer initialization or polling fails

Publisher fallback only triggers on MessageException — other exceptions propagate immediately.

Consumer state-cleanup is performed before re-throwing: NACK in RabbitMQ, requeue in InMemory. The Database transport records the failed attempt and continues with the next event instead of re-throwing (see Database (PDO)).

Documentation

Full documentation, guides, and API reference:

docs.jardis.io/en/adapter/messaging

License

This package is licensed under the MIT License.

Jardis · Documentation · Headgent

AI-Assisted Development

This package ships with a skill for Claude Code, Cursor, Continue, and Aider. Install it in your consuming project:

composer require --dev jardis/dev-skills

More details: https://docs.jardis.io/en/skills