CREATE TABLE IF NOT EXISTS idempotency_keys ( user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, idempotency_key varchar(128) NOT NULL, request_hash bytea NOT NULL, message_id uuid REFERENCES messages(id) ON DELETE SET NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (user_id, chat_id, idempotency_key) ); CREATE INDEX IF NOT EXISTS idempotency_keys_expiry ON idempotency_keys (created_at);