Skip to main content

What is Idempotency?

In the context of webhooks, idempotence is the property of an endpoint to ensure it processes duplicate events exactly once. Most webhook emitters, including Trophy, operate on an “at least once” delivery guarantee. This means you may eventually receive the same webhook multiple times and your code needs to handle those scenarios without unintended consequences. For example, if your webhook handler is subscribed to leaderboard.finished events and sends users gift cards if they place in the top 10, then your code needs to only send the gift cards once even if your code receives the same event from Trophy multiple times.

Implementing Webhook Idempotency

Making your webhook handlers more robust is trivial in most cases. Let’s take the gift card example above. After sending out a gift card to a user, your code could insert a record into your database that represents that the gift card has been sent to the user.
-- Create a table to store gift card receipts
CREATE TABLE gift_card_receipts (
    id text PRIMARY KEY,
    user_id text NOT NULL,
    gift_card_id text NOT NULL
)

-- Insert a row after sending gift card
INSERT INTO gift_card_receipts (id, user_id, gift_card_id)
VALUES ('webhook_event_id', 'user_123', 'gift_card_abc')

-- Check before sending gift card
SELECT * FROM gift_card_receipts
WHERE user_id = 'user-id'
AND gift_card_id = 'gift-card-id'
LIMIT 1
Then before sending gift cards add an if statement that checks if the gift card has already been sent to the user.
var receipt = await getGiftcardReceipt();

if (!receipt) {
  sendGiftCard();
} else {
  // Duplicate event - do nothing
}
If your code receives a duplicate event, the gift card will not be sent again.

Get Support

Want to get in touch with the Trophy team? Reach out to us via email. We’re here to help!
I