I am trying to set up Postgres NOTIFY messages in a distributed Phoenix app with read replicas. I’m using Postgrex.Notifications
to listen for messages on the desired channel. This was all working when I just had the one writable db instance, but after deploying read replicas and adding fly_postgres
(which is great btw) I am not receiving the messages on the nodes that are connected to the replicas. The nodes in the primary region still receive messages as expected. I think I have executed the proper psql in my migrations, but it’s still not working. It’s my understanding that schema changes should replicate automatically. Any ideas what I might be doing wrong? I’ll post the migrations below, and am happy to share more code and config if it’s helpful. Thanks!
defmodule MyApp.Repo.Migrations.CreateHandoffNotifications do
use Ecto.Migration
def up do
execute("""
CREATE OR REPLACE FUNCTION notify_handoff_insertions()
RETURNS trigger AS $$
BEGIN
PERFORM pg_notify(
'handoff_inserted',
NEW.game_id::text
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
""")
execute("""
CREATE TRIGGER handoff_inserted
AFTER INSERT
ON handoffs
FOR EACH ROW
EXECUTE PROCEDURE notify_handoff_insertions();
""")
end
def down do
execute("DROP FUNCTION notify_handoff_insertions() CASCADE;")
end
end
defmodule MyApp.Repo.Local.Migrations.AlwaysEnableHandoffNotifications do
use Ecto.Migration
def up do
execute("""
ALTER TABLE handoffs ENABLE ALWAYS TRIGGER handoff_inserted;
""")
end
end