CREATE TABLE idempotency_records ( user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, method varchar(8) NOT NULL, chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, idempotency_key varchar(128) NOT NULL, request_hash bytea NOT NULL, response jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), expires_at timestamptz NOT NULL, PRIMARY KEY (user_id, method, chat_id, idempotency_key), CONSTRAINT idempotency_method_post CHECK (method = 'POST'), CONSTRAINT idempotency_hash_sha256 CHECK (octet_length(request_hash) = 32), CONSTRAINT idempotency_expiry_after_creation CHECK (expires_at > created_at) ); CREATE INDEX idempotency_records_expiry_idx ON idempotency_records (expires_at);