Consistency
Keeping data correct when many things read and write at once.
Consistency problems appear with concurrent writes, caches, replicas and distributed systems. Transactions, constraints and idempotency are the main tools. Users notice inconsistency as lost work or numbers that do not add up.
Why it matters for a product engineer
Consistency problems appear when two writes happen at once, when a cache is out of date, or when a request fails halfway and someone tries again. Users see them as lost work, a double charge or numbers that do not add up. Transactions, constraints and idempotency are the main tools, and engineers decide where each one is needed.
How to do it
- List the operations that must never happen twice, such as a payment, an email or an order.
- Make each one idempotent: the client sends a unique key, and the server returns the saved result when the same key comes again.
- Use a transaction when several changes must succeed or fail together.
- Use constraints, such as unique keys, so the database rejects a duplicate even if the code misses it.
- Decide how stale each cached value may be, and show the user when data may be old.
- For two writers, choose a rule: lock, reject the second one, or merge, and write the rule down.
Common mistakes
- Retrying a payment request without an idempotency key.
- A check followed by a write, with no transaction between them, so two requests both pass the check.
- Caches with no plan for when the data changes.
- Assuming that a timeout means the operation did not happen.
Example
Networks fail in ambiguous ways: a request can succeed on the server while the response never
arrives. Stripe’s API lets clients send an Idempotency-Key header with each request that changes
something. Stripe saves the first result for that key, so a retry gets the same answer instead of a
second charge.
A payment retried safely with an idempotency key
The client cannot know whether the first request worked. With the key, retrying is always safe.
ReportedStripe engineering blog, 22 Feb 2017, and the Stripe API reference
Sources: Designing data-intensive applications (Martin Kleppmann) ↗ · Designing robust and predictable APIs with idempotency (Brandur Leach, Stripe) ↗ · Idempotent requests (Stripe API reference) ↗
Resources
1- bookGo deeper · Paid
Designing data-intensive applications ↗
Martin Kleppmann · 600 pagesThe standard book on data systems, consistency and scale. Read it when a product's data starts to hurt.
Tools
1- ToolOpen source