CREATE TABLE message_idempotency ( user_id uuid NOT NULL, chat_id uuid NOT NULL, idempotency_key text NOT NULL CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'), request_hash text NOT NULL, message_id uuid REFERENCES messages (id), expires_at timestamptz(3) NOT NULL, PRIMARY KEY (user_id, chat_id, idempotency_key), FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id) );