-- The idempotency reservation is inserted before the message row inside one -- transaction. A deferred foreign key lets both statements commit together -- while still guaranteeing that a committed key always points at a message. ALTER TABLE idempotency_keys DROP CONSTRAINT IF EXISTS idempotency_keys_message_id_fkey; ALTER TABLE idempotency_keys ADD CONSTRAINT idempotency_keys_message_id_fkey FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED;