In certain scenarios, we need an operation to produce the same result even if it is called multiple times. This property is called idempotency.
For example, in a payment processing system, the call may fail for the client but be submitted successfully on the backend. When the user retries, the request will be submitted again and the user may be charged twice.
In a messaging system, we can enforce idempotency by storing a log of processed message IDs and checking against it for every incoming message.
Each message has a unique messageId. Before processing, we check if the messageId is already in processedMessages. If it is, the message is ignored; otherwise, it is processed and added to the set to avoid duplicates.
Enforce unique constraints on database fields (e.g., unique transaction_id). If a duplicate request tries to insert the same record, the DB rejects it.
Instead of a client-generated key, the server generates a hash of the request payload. If the same hash is detected again, the request is considered a duplicate.
Before processing a request, a lock is acquired. If the same request is received while the lock is active, it is rejected.