04.3.4 · Skill in Data engineering

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.

Your status · Consistency

Saved in this browser. Sign in to keep it on every device.It colours this skill's tile on your map.

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

  1. List the operations that must never happen twice, such as a payment, an email or an order.
  2. Make each one idempotent: the client sends a unique key, and the server returns the saved result when the same key comes again.
  3. Use a transaction when several changes must succeed or fail together.
  4. Use constraints, such as unique keys, so the database rejects a duplicate even if the code misses it.
  5. Decide how stale each cached value may be, and show the user when data may be old.
  6. 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.

Sequence

A payment retried safely with an idempotency key

Your serverStripe API01 Charge, key A102 Charged, but the reply is lost03 Retry: charge, key A104 The saved result, no new chargeYour serverStripe API01 Charge, key A102 Charged, but the reply is lost03 Retry: charge, key A104 The saved result, no new charge

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

Tools

1
Tools for Data engineering