Sending Events¶
pgrelay.notify() is how you fire an event. Call it anywhere you would call a regular PostgreSQL function — from a trigger, an application, another function, or directly in psql (PostgreSQL's command-line client). It returns the id of the queued event, so you can hold onto it if you might need to cancel later.
-- Basic usage:
SELECT pgrelay.notify('my_channel', 'payload text');
-- No payload (defaults to an empty string):
SELECT pgrelay.notify('my_channel');
-- Capture the id for later:
SELECT pgrelay.notify('my_channel', 'payload text') AS event_id \gset
The event is written to the queue inside your current transaction. This means:
- If your transaction commits, the event is saved and will be processed.
- If your transaction rolls back, the event is discarded as if it never happened.
Scheduling an event for the future¶
-- Run at 2 AM tomorrow:
SELECT pgrelay.notify('nightly_report', '',
p_run_at := date_trunc('day', now() + interval '1 day') + interval '2 hours');
Setting an expiry¶
If the event has not been processed by the deadline you set, it is discarded rather than run. This is useful for time-sensitive events, where running the action late would be worse than not running it at all.
-- Discard if not processed within 5 minutes:
SELECT pgrelay.notify('flash_sale_open', sale_id::text,
p_expire_at := now() + interval '5 minutes');
Suppressing duplicates¶
If several notifications are fired before the Processor gets to them, you can — optionally — suppress redundant events so only one actually runs.
-- Only one un-processed event per product in the queue at a time:
PERFORM pgrelay.notify('product_changed', NEW.product_id::text,
p_deduplicate := true);
What happens if the channel name is wrong?¶
notify() checks that the channel is registered before writing anything. A mistyped name raises an error immediately:
This catches mistakes at the point you called notify(), rather than silently creating an event that would never be processed.
Cancelling an event¶
If you change your mind about an event before the Processor has picked it up, pgrelay.cancel() cancels it — pass the id notify() returned:
It returns one row: channel, outcome, and log_id. outcome is 'cancelled' if it worked, or 'skipped' if the event was already dispatched (the Processor got to it first) or is being touched by something else right at that instant — either way, nothing is changed. There's no need to check first and no race to worry about: cancel() either wins cleanly or reports that it was too late.
A cancelled event is recorded in the audit log with status cancelled, exactly like any other outcome — see Keeping the Audit Log Tidy.
cancel() isn't granted to everyone by default — see Step 2 in Getting Started.
Now that you can fire events, continue to Managing Channels to learn how to register, update, and monitor the channels those events run against.