What is Idempotency?

When describing APIs, idempotence is a property of a particular operation whereby subsequent invocations after the first have no additional effect on the state of the system. Trophy’s event tracking API can be used to enforce idempotency preventing client retries from having unintended side effects such as overcounting user interactions, or awarding points to users multiple times for the same action. This is particularly important where rewards are tied to user actions to prevent users from ‘gaming the system’.

Sending Idempotent Requests

To ensure idempotency is respected when sending events to Trophy, include an Idempotency-Key header when using the event tracking API. Additionally, all client SDKs support idempotency with built-in type safety. You can choose what to use as your idempotency key, but it should reflect the level of ‘uniqueness’ that you want Trophy to respect.
For example, if you use Trophy to reward users for completing lessons, and want to make sure each user can only redeem rewards once for each lesson, use the unique ID of the lesson as your idempotency key.
Here’s an example of what using an idempotency key looks like:
curl -X POST https://app.trophy.so/api/metrics/lessons-completed/event \
     -H "X-API-KEY: <apiKey>" \
     -H "Idempotency-Key: <lesson-123>" \
     -H "Content-Type: application/json" \
     -d '{
  "user": {
    "id": "18",
    "email": "user@example.com",
    "tz": "Europe/London"
  },
  "value": 1
}'

How Idempotency Works

When Trophy detects an idempotency key has been sent with an event, it will first check if the user the event relates to has used it before. It will then proceed to take one of the following actions:
  • If the user has used the idempotency key before, Trophy will not process the event, returning a 202 Accepted response. The response will reflect the current state of the system, but will not increase the users metric total, complete any achievements, award any points, extend the streak, etc.
  • If instead Trophy detects the user hasn’t used the idempotency key before, it will process the event as usual, returning a 201 Created response. Finally Trophy will store the idempotency key for lookup during any subsequent requests.
All Trophy metrics manage idempotency in isolation. Trophy will accept a user using the same idempotency key for events against different metrics as seperate isolated requests.
Additionally, when using an idempotency key the response will contain two properties to help clients manage replayed requests effectively:
{
    ...,
    "idempotentReplayed": true, // true if replayed, false otherwise
    "idempotencyKey": "test" // the original idempotency key
}
By default Trophy uses an infinte time window for detecting duplicate events. If you feel you need different behavoir, please get in touch and we’ll happily set that up for you.

Get Support

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