-- +goose Up -- One row per Idempotency-Key a user has sent to one chat. The contract scope -- is user + method + chat path + key; only POST /chats/{chat_id}/messages -- accepts keys, so (user_id, chat_id) already fixes the method and the path. -- The primary key is what makes concurrent retries through different -- replicas safe: the second insert of a key waits for the first one's commit. -- The row references the message instead of storing a response: messages -- are immutable, so a replay is answered from the source of truth. -- The table only adds to the schema: the previous API version keeps working -- while a rolling update runs this migration. CREATE TABLE message_idempotency_keys ( user_id uuid NOT NULL, chat_id uuid NOT NULL, key text NOT NULL, message_id uuid NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (user_id, chat_id, key), FOREIGN KEY (chat_id, message_id) REFERENCES messages (chat_id, id) ); -- Serves the periodic removal of keys older than the retention period. CREATE INDEX message_idempotency_keys_created_at_idx ON message_idempotency_keys (created_at); -- +goose Down DROP TABLE message_idempotency_keys;