« Back to Index

Using ETags in your API

View original Gist on GitHub

Tags: #etag #api

API ETags.md

I like to include ETags (RFC 7232) in an API as a way to distinguish between “Which resource am I targeting?” (e.g. id) and “Which version of the resource am I changing?” (e.g. etag).

The id never changes while the etag changes every time the resource is modified.

The problem I’m trying to solve is both “race conditions” and “lost updates”.

For example, a customer has two employees (or automated systems) both looking to make modifications to API-based data. They get the same data at the same time, then attempt to update that data, but the changes they each attempt to make overlaps with each other (maybe user A changes the name field in the data, while user B deletes the name field). This is a problem because the outcome is non-deterministic and user A’s changes might be applied last which means the name field is put back instead of deleted.

Supporting ETags requires the API user to provide an If-Match request header with the relevant ETag value and if the tag doesn’t match what is currently stored in the database (which the API communicates with to get the data), then the request is rejected with a 412 Precondition Failed (RFC 9110).