000004_outbox.up.sql35 lines, 1.2 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- Events waiting to be published. A service writes them in the same |
| 4 | -- transaction as the change they describe, and a relay publishes them. |
| 5 | CREATE TABLE outbox ( |
| 6 | -- the order events were written in, and the order we publish them in |
| 7 | seq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, |
| 8 | -- the event's own ID, sent as its Nats-Msg-Id |
| 9 | event_id uuid NOT NULL UNIQUE, |
| 10 | subject text NOT NULL, |
| 11 | -- json keeps our bytes exactly as we wrote them; jsonb would reorder keys |
| 12 | payload json NOT NULL, |
| 13 | created_at timestamptz NOT NULL DEFAULT now(), |
| 14 | published_at timestamptz |
| 15 | ); |
| 16 | |
| 17 | -- The relay only looks for events it hasn't published, oldest first. Once |
| 18 | -- published, a row leaves this index, so it stays tiny. |
| 19 | CREATE INDEX outbox_unpublished_idx ON outbox (seq) WHERE published_at IS NULL; |
| 20 | |
| 21 | -- Wake the relay when events are written. NOTIFY is transactional: it's |
| 22 | -- sent at commit, never after a rollback, and once per transaction. |
| 23 | CREATE FUNCTION outbox_notify() RETURNS trigger |
| 24 | LANGUAGE plpgsql AS $$ |
| 25 | BEGIN |
| 26 | PERFORM pg_notify('outbox', ''); |
| 27 | RETURN NULL; |
| 28 | END; |
| 29 | $$; |
| 30 | |
| 31 | CREATE TRIGGER outbox_notify |
| 32 | AFTER INSERT ON outbox |
| 33 | FOR EACH STATEMENT EXECUTE FUNCTION outbox_notify(); |
| 34 | |
| 35 | COMMIT; |