Events

Relay’s in-memory cache is exceptionally fast and reliable, however some scenarios such as long-running processes or highly concurrent applications can use Relay’s event listeners to avoid race conditions.

After invalidating its in-memory cache, Relay will call any registered event listeners. There is an average delay of 100μs / 0.1ms for Redis to inform Relay about invalidations, plus whatever the network latency is.

Relay has two event types:

  • The flushed event is dispatched when the connection’s database was flushed, right after Relay wiped it’s in-memory cache.
  • The invalidated event is dispatched when a key that the current process previously interacted with was altered in any way, right after Relay removed the key from it’s in-memory cache.

Event listeners can be any callable type and are registered using the listen() method:

$relay->listen(function (\Relay\Event $event) {
    match ($event->type) {
        $event::Flushed => flushCache(),
        $event::Invalidated => deleteFromCache($event->key),
    };
});

It’s worth noting that event listeners are connection specific, which means:

  • a connection must be opened before registering any event listeners
  • switching databases with select() will detach all event listeners
  • opening a divergent connection with connect() will detach all event listeners

Listening for flushes

In some cases the application might want to register a distinct flush listener. This can be accomplished using the onFlushed() method:

$relay->onFlushed($callback);

Listening for invalidations

In some cases the application might want to register one or more distinct invalidation listeners. This can be accomplished using the onInvalidated() method:

$relay->onInvalidated($callback);

However, note that database flushes will not dispatch individual invalidation events and must be handled separately using onFlushed().

Furthermore, invalidation event listeners can be restricted to a wildcard match:

$relay->onInvalidated($callback, 'api:*');

// named arguments for readability
$relay->onInvalidated(
    match: 'api:*',
    callback: fn ($event) => deleteApiCacheKey($event->key)
);

Dispatching events

Because of PHP’s synchronous nature the application must request Relay to dispatch registered event listeners. This can done by calling dispatchEvents(), or automated using ticks.

Be sure to read more about dispatching events and set this up when registering event listeners.