CREATE TABLE idempotency_keys ( chat_id uuid NOT NULL, user_id uuid NOT NULL, key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), fingerprint bytea NOT NULL CHECK (octet_length(fingerprint) = 32), message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, created_at timestamptz NOT NULL, PRIMARY KEY (chat_id, user_id, key), FOREIGN KEY (chat_id, user_id) REFERENCES chat_members (chat_id, user_id) );