VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/4.3-unique-events

⇱ Unique Events | hypervel/broadcasting | DeepWiki


Loading...
Menu

Unique Events

This document explains the UniqueBroadcastEvent system, which provides cache-based locking to prevent duplicate processing of broadcast events in queue workers. It covers the uniqueness configuration options, lock acquisition mechanisms, and integration with the queue system.

For standard broadcast event wrapping without uniqueness constraints, see Standard Broadcast Events. For the contract interfaces that control event behavior, see Event Contracts.


Overview

The UniqueBroadcastEvent class extends the standard BroadcastEvent wrapper to add uniqueness guarantees. When an event implements the ShouldBeUnique interface, the broadcasting system automatically wraps it in UniqueBroadcastEvent and attempts to acquire a cache-based lock before queuing. If the lock cannot be acquired (indicating a duplicate event is already processing), the broadcast is silently skipped.

This mechanism prevents redundant broadcasts when the same logical event is triggered multiple times in rapid succession, such as during burst traffic or race conditions.

Sources: src/UniqueBroadcastEvent.php1-54 src/BroadcastManager.php192-215


Event Uniqueness Architecture


The UniqueBroadcastEvent class sits in the intersection of two uniqueness concepts:

ContractNamespacePurpose
Broadcasting\Contracts\ShouldBeUniqueBroadcasting packageMarker interface indicating event should be unique
Queue\Contracts\ShouldBeUniqueQueue packageProvides locking mechanism for queue jobs

Sources: src/UniqueBroadcastEvent.php11 src/BroadcastManager.php21


Lock Acquisition Flow


The locking mechanism uses the cache driver's atomic add() operation to ensure only one worker processes the event. The lock is held for the duration specified by uniqueFor (in seconds).

Sources: src/BroadcastManager.php192-215 src/UniqueBroadcastEvent.php1-54


Uniqueness Configuration

The UniqueBroadcastEvent constructor extracts three configuration values from the wrapped event:

Unique Identifier (uniqueId)

The lock key is constructed from the event's class name and an optional unique identifier:


Priority order:

  1. Event class name (always included)
  2. uniqueId() method (if exists)
  3. $uniqueId property (if exists and no method)

Example configurations:

Event ImplementationResulting Lock Key
Basic eventApp\Events\UserStatusChanged
With methodApp\Events\UserStatusChanged123
With propertyApp\Events\UserStatusChanged456

Sources: src/UniqueBroadcastEvent.php28-34

Lock Duration (uniqueFor)

The number of seconds the lock should be maintained. After this duration, another instance of the same event can be queued.

Priority order:
1. uniqueFor() method (if exists)
2. $uniqueFor property (if exists and no method)
3. Default from queue configuration (if neither)

Sources: src/UniqueBroadcastEvent.php36-40

Cache Driver (uniqueVia)

The cache implementation used for lock storage:

Priority order:
1. event->uniqueVia() method (if exists)
2. Default Cache factory from container

This allows events to specify alternative cache stores for lock management, useful for distributed systems with dedicated coordination stores.

Sources: src/UniqueBroadcastEvent.php48-53


Implementation in BroadcastManager

The BroadcastManager::queue() method orchestrates unique event handling:


Key code paths:

Line RangePurpose
src/BroadcastManager.php176-181Handle immediate broadcast bypass
src/BroadcastManager.php183-188Extract queue name from event
src/BroadcastManager.php192-198Create UniqueBroadcastEvent and check lock
src/BroadcastManager.php200-203Push to queue if lock acquired
src/BroadcastManager.php208-215Lock acquisition logic using UniqueLock

Sources: src/BroadcastManager.php174-203


Lock Acquisition Details

The mustBeUniqueAndCannotAcquireLock() method implements the locking logic:


Method signature and behavior:

mustBeUniqueAndCannotAcquireLock(UniqueBroadcastEvent $event): bool

Returns:
- true = Lock NOT acquired (duplicate exists) → Skip queuing
- false = Lock acquired successfully → Proceed with queuing

The method name uses negative logic: it returns true when the event "must be unique" AND "cannot acquire lock", which signals to skip queuing.

Sources: src/BroadcastManager.php208-215


Event Implementation Example

To create a unique broadcast event, implement the ShouldBeUnique interface:

Minimal implementation:

  • Implement Broadcasting\Contracts\ShouldBeUnique marker interface
  • Default behavior: class name as lock key, default TTL

Customized implementation:

  • Add uniqueId() method or $uniqueId property for custom lock keys
  • Add uniqueFor() method or $uniqueFor property for custom TTL
  • Add uniqueVia() method for custom cache driver

Sources: src/BroadcastManager.php21 src/UniqueBroadcastEvent.php28-53


Use Cases

ScenarioConfigurationBehavior
User status changesuniqueId = "user-{$userId}"Only latest status broadcasted per user
Burst notificationsuniqueFor = 5Maximum one broadcast per 5 seconds
Distributed eventsuniqueVia = Redis cacheLock shared across multiple servers
Transient eventsuniqueFor = 1Debounce rapid-fire events

The uniqueness guarantee operates at the queue job level, not at the event dispatch level. Multiple calls to queue() with identical events will only result in one queued job if the lock is active.

Sources: src/UniqueBroadcastEvent.php1-54 src/BroadcastManager.php192-215


Class Properties Summary

PropertyTypeSourcePurpose
$uniqueIdstringEvent class + method/propertyCache lock key
$uniqueForintEvent method/propertyLock TTL in seconds
uniqueVia()CacheEvent method or containerCache driver for locking
$eventmixedInherited from BroadcastEventOriginal event being broadcast

Sources: src/UniqueBroadcastEvent.php14-22 src/UniqueBroadcastEvent.php48-53


Integration with Queue System

The UniqueBroadcastEvent implements the queue package's ShouldBeUnique contract, which provides:

  1. Job uniqueness: Queue workers respect the lock before processing
  2. Lock release: Automatic lock release after uniqueFor seconds
  3. Cache-based coordination: Works across distributed queue workers

The broadcasting package leverages the queue system's uniqueness infrastructure rather than implementing its own locking mechanism. This ensures consistency with other unique jobs in the application.

Sources: src/UniqueBroadcastEvent.php11 src/BroadcastManager.php210-214