Designing Data-Intensive ApplicationsParts I-III (complete book) · condensed, chapter by chapter
Chapter 12

The Future of Data Systems

The final chapter turns from how systems are to how they should be: the author's openly first-person proposals for applications that are robust, correct, evolvable and good for people, built from the ideas of all earlier chapters.

Key takeaways

  • No one tool fits every access pattern, so apps compose several systems; keeping them in sync is the hard part.
  • Choose a system of record, fix a total order of writes in a log, and derive indexes, caches and models from it (CDC or event sourcing).
  • Across heterogeneous systems, an async log with idempotent consumers beats XA distributed transactions: faults stay local.
  • Reprocessing history lets schemas evolve gradually and reversibly; one engine for batch and stream avoids the lambda architecture's duplication.
  • "Unbundling the database": org-wide dataflow is one big database; caches, indexes and views just move the boundary between the write path and the read path.
  • Correctness needs end-to-end measures, e.g. a client-generated request ID carried to the database.
  • Split consistency into timeliness (may lag) and integrity (must hold). Dataflow keeps integrity without coordination; many constraints can be checked late and fixed by apology.
  • Trust, but verify: audit data end to end. Engineers must also weigh the ethics of predictive analytics and tracking.

Data Integration

  • Every problem has several solutions with different trade-offs (log-structured vs B-tree vs column storage; single-leader vs multi-leader vs leaderless).
  • One product doing everything is likely poor at all of it; even "general-purpose" databases target a usage pattern.
  • Two challenges: map products to the circumstances they fit, and, since one dataset is used in many ways, stitch several tools together.

Combining Specialized Tools by Deriving Data

  • Typical pair: OLTP database + full-text search index. PostgreSQL's built-in search suits simple apps; serious search needs specialist tools, which make poor systems of record.
  • More copies follow: warehouses, batch/stream systems, caches, denormalized objects, ML and recommendation pipelines, change notifications.
  • "99% of people only need X" says more about the speaker than the tool; integration needs appear when you look at dataflow across the whole organization.

Reasoning about dataflows

  • Be explicit: where is data written first, and which representation derives from which?
  • Write to the system of record, capture changes with change data capture (CDC), apply them to the index in the same order. If CDC is the index's only input, the index is consistent with the source (barring bugs).
  • Dual writes from the app to both systems let concurrent writes land in different orders; nobody is in charge of ordering, so the systems can diverge permanently.
  • Funnel all input through one system that fixes a total order (state machine replication via total order broadcast). CDC vs event sourcing matters less than having one order.
  • Log-driven updates can be deterministic and idempotent, so fault recovery is easy.
Application Database system of record CDC log Search index Cache Warehouse writes one total order derived systems apply changes in log order; no dual writes
Derive every other representation from one ordered log of the system of record.

Derived data versus distributed transactions

Distributed transactionsLog-based derived data
OrderingLocks (2PL)Log order
Exactly-once effectAtomic commitDeterministic retry + idempotence
TimingUsually linearizable (read your own writes)Asynchronous; no such guarantee by default
  • XA works where people pay its cost, but has poor fault tolerance and performance; a better protocol is unlikely to be widely adopted soon.
  • Author's view: log-based derived data is the most promising integration approach, but "eventual consistency, deal with it" is not enough guidance. A middle ground comes in "Aiming for Correctness".

The limits of total ordering

  • Throughput: a total order needs one leader; partition the log beyond one machine and cross-partition order is ambiguous.
  • Geography: a leader per datacenter (sync cross-DC coordination is slow) leaves cross-DC events unordered.
  • Microservices: each service owns its state, so events from different services have no defined order.
  • Offline clients: local state updated immediately means clients and servers see different orders.
  • Total ordering is total order broadcast = consensus. Most algorithms assume one node handles the whole stream; scaling beyond one node and across regions is open research.

Ordering events to capture causality

  • Unrelated concurrent events can be ordered arbitrarily; updates to one object can be ordered by routing its ID to one partition.
  • Subtle case: a user unfriends their ex, then messages friends about the ex. With friends and messages stored separately, a notifier may see the message first and notify the ex. The notification is a join, with the timing problems of joins.
  • No simple fix. Starting points: logical timestamps (order without coordination, but recipients handle out-of-order events and extra metadata); log what the user saw with an ID that later events reference; conflict resolution (fine for state, useless for external side effects like notifications).
User Friends store 1. unfriend Message store 2. send message Notifier Ex arrives late arrives first wrong notify
Causal order lost across two stores: the notification is a join that sees the events in the wrong order.

Batch and Stream Processing

  • Integration means getting data into the right form in the right places; batch and stream processors do it, producing search indexes, materialized views, recommendations and metrics.
  • Core difference: unbounded vs finite input. Engines are converging: Spark does streams as microbatches; Apache Flink does batch on a stream engine. Performance differs (microbatching may do poorly on hopping or sliding windows).

Maintaining derived state

  • Batch is functional in flavor: deterministic pure functions, immutable inputs, append-only outputs. Streams add managed, fault-tolerant state.
  • Clear inputs and outputs aid fault tolerance and make org-wide dataflows easier to reason about.
  • Derived systems could update synchronously, but asynchrony is what makes log-based systems robust: faults stay local, whereas distributed transactions abort on any participant failure and spread it.
  • Cross-partition secondary indexes (term- or document-partitioned) are also most reliable and scalable when maintained asynchronously.

Reprocessing data for application evolution

  • Streams give low-delay updates; batch reprocesses history into new views.
  • Without reprocessing, schema evolution is limited to simple additions (optional field, new record type); with it, you can restructure into a completely different model.
  • Railways: after England standardized gauge in 1846, lines were converted by adding a third rail so both train types could run during the transition. It is costly, so odd gauges survive (BART).
  • Derived views allow gradual evolution: run old and new schemas as two views on the same data, shift a few users, grow the share, drop the old view. Each step is reversible, so you can move faster.
Event log Old view old schema New view reprocessed Users 95% 5%, growing each step reversible; drop old view at the end
Gradual migration: two views derived from the same data, traffic shifted step by step (percentages illustrative).

The lambda architecture

  • Append immutable events (like event sourcing) and derive read-optimized views, using two systems in parallel: batch (Hadoop MapReduce) for a corrected view and stream (Storm) for a fast approximate one.
  • Rationale: batch is simpler and less buggy; stream processors were seen as less reliable; streams can use approximate algorithms, batch exact ones.
  • It popularized views derived from immutable events and reprocessing. Problems:
    • Same logic in two frameworks; tools like Summingbird help with code, not with operating two systems.
    • Outputs must be merged at read time: easy for tumbling-window aggregates, hard for joins, sessionization or non-time-series.
    • Full reprocessing is costly, so batch runs incrementally (e.g. hourly), reintroducing stragglers and cross-batch windows and making it as complex as the stream layer.

Unifying batch and stream processing

One system for both, which needs:

  • Replay of history through the live engine (log-based brokers; stream processors reading HDFS).
  • Exactly-once semantics: output as if no faults, discarding failed tasks' partial output.
  • Event-time windowing, since processing time is meaningless on replay (Apache Beam's API, run on Flink or Google Cloud Dataflow).
Lambda Events Batch (exact, slow) Stream (approx) Merge Reads Unified History + live One engine replay, exactly-once, event time One view
Lambda runs two pipelines and merges them; a unified engine handles reprocessing and live events with one codebase.

Unbundling Databases

  • Databases, Hadoop and operating systems all store, process and query data ("information management"); Hadoop is somewhat like a distributed Unix. Differences remain: filesystems struggle with 10 million small files; databases handle 10 million records easily.
  • Unix: thin, low-level hardware abstraction (pipes, byte files). Relational databases: high-level abstraction (SQL, transactions) hiding disk structures, concurrency and recovery; a short query draws on optimizers, indexes and replication.
  • The tension dates to the early 1970s; the author reads NoSQL as Unix-style low-level abstraction applied to distributed OLTP. This section tries to combine both.

Composing Data Storage Technologies

  • Database features seen in the book: secondary indexes, materialized views (precomputed query cache), replication logs, full-text indexes.
  • Chapters 10 and 11 built the same things outside databases: batch-built search indexes, view maintenance, CDC to derived systems.

Creating an index

  • CREATE INDEX scans a consistent snapshot, sorts the indexed values, writes the index, applies the backlog of writes since the snapshot, then keeps it current.
  • That is like bootstrapping a follower replica or CDC with an initial snapshot: the database reprocesses existing data into a new derived view.

The meta-database of everything

  • An organization's dataflow looks like one huge database: batch, stream and ETL jobs act as index and view maintenance; processors are elaborate triggers and stored procedures; derived systems are index types run by different teams on different machines.
Federated database (polystore): unify readsUnbundled database: unify writes
IdeaOne query interface over many enginesPlug stores together (CDC, event logs) so every change reaches every place
ExamplePostgreSQL foreign data wrapperIndex maintenance unbundled across technologies
TraditionRelational: integrated, high-level, complex insideUnix: small tools, uniform low-level API (pipes), composed by a shell
GapNo answer for syncing writesNo high-level composition language yet
Federated: unify reads Unbundled: unify writes Query interface Store A Store B Store C Event log Database Index Cache reads flow up writes flow down
Federation and unbundling are two sides of composing diverse stores into one system.

Making unbundling work

  • Federated reads mean mapping data models: manageable. Syncing writes is harder, so that is the focus.
  • Distributed transactions across heterogeneous stores are, in the author's view, the wrong tool. Inside one system transactions are fine (some stream processors use them for exactly-once); across technologies with no standard protocol, an ordered log with idempotent consumers is simpler and more robust.
  • Loose coupling, twice over: (1) system level: a slow or failed consumer is buffered by the log and catches up later, while synchronous transactions escalate local faults; (2) human level: teams build and run components independently behind clear interfaces, and logs are strong enough (durable, ordered) yet general.

Unbundled versus integrated systems

  • Databases remain necessary: processor state, serving outputs, and specialized engines such as MPP warehouses.
  • Every extra system brings a learning curve and operational quirks; an integrated product may perform better and more predictably on its workload. Building for scale you don't need is premature optimization.
  • Unbundling is about breadth, not depth. If one product meets all requirements, use it.

What's missing?

  • No unbundled equivalent of the Unix shell: a declarative language for composing stores and processors.
  • Wish: mysql | elasticsearch as the unbundled CREATE INDEX, indexing everything and applying all future changes with no custom code. Also declarative materialized views as caches (even recursive graph queries); early research like differential dataflow.

Designing Applications Around Dataflow

  • Also called "database inside-out" (after the author's 2014 talk): a design pattern, not a grand architecture, drawing on Oz, Juttle, Elm (FRP), Bloom; "unbundling" is Jay Kreps's term.
  • Spreadsheets recompute dependent cells when inputs change; data systems should likewise refresh indexes, views and aggregates automatically. VisiCalc did this in 1979; data systems must add fault tolerance, scale, durability and integration across teams and technologies.

Application code as a derivation function

  • Each derived dataset has a transformation: secondary index (pick and sort values); full-text index (language detection, segmentation, stemming, spelling, synonyms, inverted index); ML model (features and statistics from training data); cache (data shaped for the UI, rebuilt when the UI changes).
  • Indexes are built in (CREATE INDEX); full-text needs tuning; ML feature engineering is very app-specific. Custom derivations need custom code, where triggers, stored procedures and UDFs have been an afterthought.

Separation of application code and state

  • Databases are poor hosts for app code: weak dependency management, version control, rolling upgrades, monitoring, network calls. Mesos, YARN, Docker and Kubernetes do that job better. Let some parts specialize in storage, others in running code.
  • Stateless services keep logic out of the database and state out of the app ("separation of Church and state", a joke about Alonzo Church's lambda calculus having no mutable state).
  • The database then acts as a shared mutable variable you can read but not subscribe to; observing changes means polling (the observer pattern is hand-built). Change streams are only emerging.

Dataflow: Interplay between state changes and application code

  • Code reacts to state changes in one place by producing state changes elsewhere (like change-log subscriptions, actors, 1980s tuple spaces). Unbundling applies trigger- and index-style updates to caches, search, ML and analytics via stream processing.
  • This is not async job queuing: order matters (views from one log must agree; many brokers reorder on redelivery; dual writes are out) and no message may be lost (one loss desyncs a view forever; in-memory actor state dies with the machine).
  • Stable ordering and fault-tolerant processing are demanding but far cheaper than distributed transactions. Operators compose like piped Unix tools: streams of state changes in, streams out.

Stream processors and services

  • Microservices (synchronous REST) win on organizational scalability. Stream operators share that, but communicate through one-way async streams, with better fault tolerance and performance.
  • Exchange-rate example: microservices query a rate service per purchase; dataflow subscribes to rate updates in advance and stores them locally, so a purchase does a local lookup. Faster, and survives the rate service failing: the most reliable network request is none. RPC becomes a stream-table join. (A local cache in a microservice must be kept fresh by polling or subscribing, which is dataflow.)
  • The join is time-dependent: reprocessing later needs the historical rate either way.
Microservices (RPC) Purchase service Rate service request per purchase down = fail Dataflow (stream-table join) Rate updates Local rates DB Purchase processor Purchase events local no network
Replacing a synchronous call with a subscription: the rate is joined from a local copy.

Observing Derived State

  • Write path: eager, precomputed work that updates every derived dataset as data arrives (like eager evaluation). Read path: work done only when a user asks (like lazy evaluation).
  • The derived dataset is where they meet (Figure 12-1), trading write-time work against read-time work.
Document updates Log Search index User queries write path (eager) read path (lazy) paths meet here
Figure 12-1, simplified: in a search index, writes (document updates) meet reads (queries).

Materialized views and caching

  • Search index: writes update entries for every term; reads look up terms and apply AND/OR logic.
  • No index: cheap writes, grep-style full scans on read. Precompute all queries: trivial reads but infinite work and storage (finite but exponential in terms for a finite corpus). Cache common queries: a materialized view that must update when new documents match.
  • Caches, indexes and materialized views shift the boundary between write and read paths. This is the Chapter 1 Twitter timeline example, where celebrities got a different boundary: full circle.
more read work more write work No index grep all docs Index work on both Cache common materialized view Precompute all infinite where the derived dataset sits = the write/read boundary
Indexes, caches and materialized views move the boundary between write-time and read-time work.

Stateful, offline-capable clients

  • The stateless-client, authoritative-server model is so common it feels inevitable, but single-page apps and mobile apps now hold local state and storage.
  • Offline-first apps work against an on-device database and sync in the background, a big win on slow cellular links.
  • On-device state is a cache of server state: pixels are a materialized view of client model objects, which replicate remote state.

Pushing state changes to clients

  • A loaded page is a stale cache until reload or polling (RSS is basic polling). Server-sent events and WebSockets let servers push changes.
  • This extends the write path to the end user: initial state via the read path, then a change stream. Offline gaps are handled like log consumer offsets; each device subscribes to a small stream.

End-to-end event streams

  • Elm and React/Flux/Redux already manage client state from event streams, like event sourcing. Let servers push events into that pipeline and changes flow from one device to another's UI in under about a second.
  • Messaging and games already work this way. Others don't because request/response is baked into databases, libraries and protocols; few stores offer subscriptions.
  • The author argues for moving to publish/subscribe dataflow for responsiveness and offline support: design for subscribing to changes, not only querying.
Device A user action Event log Stream processors Derived state Device B UI updates push (WebSocket / SSE) end-to-end write path, about 1 s
Extending the write path to end-user devices: subscribe, don't just query.

Reads are events too

  • Usually writes go via the log and reads hit the store directly. Some processors expose queryable state, becoming simple databases.
  • Go further: send reads as events through the same processor, which emits results to an output stream. That is a stream-table join; reads route to the right partition as joins copartition by key.
  • A one-off read joins and is forgotten; a subscription is a persistent join with past and future events.
  • Logging reads records what users saw (e.g. a shop's shipping estimate and stock status before a purchase), aiding causality and provenance, at extra storage and I/O cost (open research). If reads are already logged for operations, it's a small step.
Write events Read events Stream operator state partition stream-table join Read results one-off read: join then forget; subscribe: persistent join
Reads as events: queries are joined against state inside the stream processor, and can be logged for provenance.

Multi-partition data processing

  • Overkill for single-partition reads, but useful for queries spanning partitions, reusing stream routing and joins. Storm distributed RPC counted who saw a URL on Twitter (union of tweeters' follower sets).
  • Fraud checks join a purchase with reputation scores for IP, email, billing and shipping addresses, each partitioned differently.
  • MPP databases do this internally and are simpler if they fit; queries-as-streams helps beyond off-the-shelf limits.

Aiming for Correctness

  • Stateless services recover by fix-and-restart; stateful systems remember mistakes (more or less) forever.
  • Transactions (atomicity, isolation, durability) have been the correctness tool for about four decades, but are weaker than they look (weak-isolation confusion). Some systems drop them for messier models (leaderless replication); "consistency" is poorly defined.
  • It is hard to know if an app is safe at a given isolation level or replication config; simple designs pass at low concurrency and fail under faults. Kyle Kingsbury's Jepsen tests found big gaps between claimed and actual guarantees.
  • Serializability and atomic commit work but usually cost single-datacenter deployment and limited scale and fault tolerance. Transactions stay, but are not the last word.

The End-to-End Argument for Databases

  • Serializable transactions don't stop an app bug from writing wrong data or deleting data. This is why the book favors immutable, append-only data, though immutability alone is not a cure-all.

Exactly-once execution of an operation

  • On failure you drop the message (loss) or retry (possible duplicate). Processing twice is corruption: double charges, double counts.
  • Exactly-once (effectively-once): the final effect equals a fault-free run despite retries. Best tool: idempotence, which may need extra metadata (operation IDs applied) and fencing on failover.

Duplicate suppression

  • TCP sequence numbers dedupe and reorder packets, but only within one connection. If the network fails after COMMIT is sent but before the reply, the client can't tell if it committed.

Example 12-1, a non-idempotent transfer:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance + 11.00 WHERE account_id = 1234;
UPDATE accounts SET balance = balance - 11.00 WHERE account_id = 4321;
COMMIT;
  • A retry on a new connection can move $22 instead of $11. The textbook atomicity example is not actually correct; real banks don't work this way.
  • 2PC lets a coordinator reconnect and resolve in-doubt transactions, but the browser-to-server hop remains: a POST succeeds, the reply is lost on a weak link, the user resubmits. Post/Redirect/Get doesn't help on timeout. To server and database it's a new request.
Browser POST, retry App server Database UNIQUE(id) HTTP hop TCP / txn hop dedupe here only dedupe here only request ID carried end to end
Per-hop duplicate suppression misses user retries; only an end-to-end operation ID catches them.

Operation identifiers

  • Generate a unique ID (UUID in a hidden form field, or a hash of the form fields) and pass it down to the database, allowing at most one operation per ID.

Example 12-2, deduplicating with a unique request ID:

ALTER TABLE requests ADD UNIQUE (request_id);
BEGIN TRANSACTION;
INSERT INTO requests
  (request_id, from_account, to_account, amount)
  VALUES('0286FDB8-D7E1-423F-B40B-792B3608036C', 4321, 1234, 11.00);
UPDATE accounts SET balance = balance + 11.00 WHERE account_id = 1234;
UPDATE accounts SET balance = balance - 11.00 WHERE account_id = 4321;
COMMIT;
  • A duplicate ID fails the INSERT and aborts the transaction. Uniqueness constraints hold even at weak isolation, unlike app-level check-then-insert.
  • The requests table is an event log: balance updates could be derived downstream, exactly once, again keyed by request ID.

The end-to-end argument

  • Saltzer, Reed and Clark (1984), paraphrased: some functions can only be done fully and correctly by the applications at the endpoints; a lower layer can offer only a partial version, useful for performance.
  • Duplicate suppression: TCP and stream-processor exactly-once can't stop a user resubmitting; an ID passed from client to database can.
  • Checksums: Ethernet, TCP and TLS miss software bugs and disk corruption; you need end-to-end checksums. Encryption: WiFi passwords and TLS each cover one segment; only end-to-end encryption and authentication cover all.
  • Low-level features still reduce higher-level problems (HTTP needs TCP ordering); they just aren't sufficient.

Applying end-to-end thinking in data systems

  • Apps need their own end-to-end measures such as duplicate suppression, and no good abstraction yet hides them.
  • Transactions collapse many failures into commit or abort, a big simplification but not enough. They are expensive across heterogeneous systems, and skipping them means hand-rolled fault tolerance that, the author suspects, is usually wrong, losing or corrupting data.
  • Wanted: abstractions for app-specific end-to-end correctness that also perform and operate well at scale.

Enforcing Constraints

  • Focus on uniqueness: usernames, emails, file names, seat bookings. Similar: non-negative balances, no overselling stock, no overlapping room bookings.

Uniqueness constraints require consensus

  • Choosing among concurrent conflicting requests is consensus. Usually a single leader decides; tolerating its failure brings consensus back.
  • Scale by partitioning on the unique value (request ID; hash of username).
  • Async multi-master replication can accept conflicting writes, so it's out. Rejecting violations immediately requires synchronous coordination.

Uniqueness in log-based messaging

  • A log is total order broadcast; one partition is consumed by a single thread, so with the log partitioned by the unique value the processor decides deterministically who came first:
  1. Each username claim is appended to the partition for hash(username).
  2. The processor checks a local table of taken names, then emits success or rejection to an output stream.
  3. The client waits on the output stream for its answer.
  • Same as linearizable storage via total order broadcast; scales by adding partitions. General rule: route potentially conflicting writes to the same partition and process them sequentially, with arbitrary validation logic (like Bayou in the 1990s).
Client 1: "ann" Client 2: "ann" Partition hash("ann") Processor single thread local: taken names 1: success 2: rejected clients watch the output stream
Uniqueness via a partitioned log: all claims on one name go to one partition and are decided in order.

Multi-partition request processing

  • Example 12-2 may touch three partitions (request ID, payee, payer). Atomic commit across them forces a total order with all their other transactions and hurts throughput.
  • Same correctness without atomic commit:
  1. The client assigns a request ID; the transfer is appended to a partition chosen by that ID.
  2. A processor emits a debit for payer A (partitioned by A) and a credit for payee B (partitioned by B), both carrying the request ID.
  3. Downstream processors dedupe by request ID and apply the balance changes.
  • Logging the request as one message avoids a two-partition atomic commit: single-object writes are atomic almost everywhere.
  • A crashed step-2 processor resumes from its checkpoint, may re-emit, but deterministically emits the same instructions, which step 3 dedupes.
  • To block overdrafts, add a processor partitioned by payer that validates before requests enter the log.
Client req ID Request log by req ID Processor deterministic Debit A part. by A Credit B part. by B Acct A dedupe Acct B dedupe 1 atomic write no atomic commit across partitions; req ID makes retries harmless
A multi-partition transfer as two differently partitioned stages instead of a distributed transaction.

Timeliness and Integrity

  • Transactions are typically linearizable; async stream stages are not. A client may wait on an output stream, but correctness doesn't depend on waiting; waiting only reports the outcome.
  • "Consistency" conflates two things:
TimelinessIntegrity
MeaningUsers see up-to-date stateNo loss, no contradictory or false data; derived views correct
If violatedTemporary; wait and retryPermanent; needs explicit check and repair
ExamplesLinearizability (CAP), read-after-writeIndex matches table; ACID "consistency"
Slogan"Eventual consistency""Perpetual inconsistency"
  • Integrity usually matters far more. A card purchase missing from the last 24 hours is normal lag; a statement that doesn't add up, or money charged but never paid to the merchant, is an integrity failure.
"Consistency" Timeliness up-to-date reads violated: eventual Integrity no loss, no false data violated: perpetual can relax must keep
Dataflow systems decouple the two: weak timeliness, strong integrity.

Correctness of dataflow systems

  • ACID bundles timeliness and integrity; event dataflow decouples them: no timeliness unless consumers wait, but integrity is central, preserved by exactly-once delivery and dedup.
  • Integrity without distributed transactions comes from: (1) the write as a single atomic message (event sourcing); (2) all other updates via deterministic derivation; (3) a client request ID through every stage; (4) immutable messages and periodic reprocessing to recover from bugs.

Loosely interpreted constraints

  • Strict uniqueness needs consensus on one node per partition, but many apps accept weaker forms:
    • Duplicate username or seat: apologize and ask one party to choose again: a compensating transaction.
    • Oversold stock: reorder, apologize, discount; you need this already for, say, forklift damage.
    • Airlines and hotels overbook deliberately and compensate; weather and strikes need apology processes anyway.
    • Overdrafts: fee and repayment; daily withdrawal limits bound risk.
  • Apologies are often cheap (correction email, refund); ATM cash is not. Accepting that cost is a business decision. If acceptable, write optimistically and check afterwards, but validate before hard-to-undo actions.
  • These apps need integrity (no lost bookings, matching credits and debits), not timely constraint enforcement, much like write-conflict resolution.

Coordination-avoiding data systems

  • Since dataflow keeps integrity without atomic commit or cross-partition coordination, and many constraints can be loose, systems can avoid coordination yet keep strong integrity, with better performance and fault tolerance.
  • Example: multi-leader across datacenters with async replication; each region runs independently; weak timeliness, strong integrity.
  • Serializable transactions still help at small scope for derived state; XA isn't needed. Add coordination only where required (strict constraints before unrecoverable actions).
  • Coordination cuts inconsistency apologies but can add outage apologies; you can't reach zero, so find the sweet spot.

Trust, but Verify

  • Reasoning rests on a system model: crashes, power loss and network faults happen; lost fsynced data, corrupted memory or a wrong CPU multiply are assumed not to. Reality is probabilistic, not binary.
  • Disks rot; network corruption can slip past TCP checksums. The author saw crash reports explainable only by memory bit-flips; rowhammer flips bits in healthy memory via access patterns. Rare, but possible.

Maintaining integrity in the face of software bugs

  • Bugs evade low-level checksums. The author has seen MySQL fail a uniqueness constraint and PostgreSQL's serializable level allow write skew; less mature software is worse.
  • App code gets far less testing than databases and often misuses foreign keys and uniqueness constraints. ACID consistency assumes bug-free transactions; misuse (unsafe weak isolation) voids it.

Don't just blindly trust what they promise

  • Corruption is eventually inevitable, so detect it: checking integrity is auditing, prized in finance because mistakes are expected.
  • HDFS and Amazon S3 continually read back files, compare replicas and move files between disks to catch silent corruption. Read your data to know it's there; test restoring backups.

A culture of verification

  • Few systems continually audit themselves; the author hopes for self-validating systems.
  • ACID culture bred blind trust. When NoSQL normalized weaker guarantees and less mature storage spread, blind trust continued, now more dangerous.

Designing for auditability

  • Transaction logs show what changed, not why; the deciding app logic was transient.
  • Event sourcing records input as one immutable event and derives state deterministically: same log + same code = same state.
  • Explicit dataflow gives clear provenance: hash the event log, rerun derivations (or a redundant one in parallel) and compare. It also enables reproducing exact circumstances: time-travel debugging.
Event log immutable hash check Derivation Rerun derivation Derived state Fresh result Equal?
Auditing a dataflow system: hash the log, re-derive the state, compare.

The end-to-end argument again

  • Without full trust in components, check integrity periodically, or corruption surfaces only after costly downstream damage.
  • Check end to end: verifying a whole pipeline implicitly covers every disk, network, service and algorithm on it.
  • Like automated tests, continuous audits catch bugs early and let you change systems and adopt new storage with confidence, so you move faster.

Tools for auditable data systems

  • Few systems prioritize auditability. Audit tables are hard to keep trustworthy; signing a log with a hardware security module proves no tampering, not that the right transactions went in.
  • Cryptocurrencies, blockchains and ledgers (Bitcoin, Ethereum, Ripple, Stellar) are, from a data view, distributed databases whose replicas, run by mutually untrusting parties, check each other and agree via consensus.
  • The author doubts their Byzantine fault tolerance claims, finds proof of work extraordinarily wasteful, and notes Bitcoin's low throughput (mostly political and economic causes), but finds the integrity checking interesting.
  • Merkle trees (trees of hashes) efficiently prove a record is in a dataset; certificate transparency uses them for TLS certificates. Such auditing may spread if made scalable with low overhead.

Doing the Right Thing

  • Every system has a purpose and consequences beyond it; engineers must consider them and choose what world to build.
  • Many datasets are about people; treat them with humanity, respect and dignity.
  • Ethics codes (the ACM Software Engineering Code of Ethics) exist but are rarely applied, so privacy is often handled cavalierly. Technology is not good or bad in itself; its use is, and the responsibility is ours.

Predictive Analytics

  • Forecasting weather or disease differs from predicting whether a person reoffends, defaults or files costly claims: these hit individuals directly.
  • Organizations default to "no" when in doubt, since a missed opportunity is cheap. Someone labeled risky (rightly or wrongly) may then be shut out of jobs, travel, insurance, housing and finance: "algorithmic prison", without proof of guilt or real appeal.

Bias and discrimination

  • Algorithms aren't inherently fairer or worse than people, but they infer rules from data; the patterns are opaque, and biased input is learned and amplified.
  • Laws bar using protected traits (ethnicity, age, gender, sexuality, disability, beliefs), yet proxies leak them: in segregated areas, postal code or IP address predicts race.
  • Expecting fair output from biased data is unrealistic ("money laundering for bias"). Prediction extrapolates the past; a better future needs human moral imagination. Data and models should be tools, not masters.

Responsibility and accountability

  • Who is accountable when an algorithm errs: a self-driving car crash, discriminatory credit scoring? Can you explain your model to a judge?
  • Credit scores use relevant facts (your borrowing history) and allow corrections; ML scoring uses wider, opaque inputs. A score asks "how did you behave?"; prediction asks "how did people like you behave?", which stereotypes (location as a proxy for race and class) and leaves misbucketed people little recourse.
  • Statistics can be right overall and wrong for individuals (an 80-year average life expectancy doesn't mean you die at 80).
  • Blind faith in data is dangerous. We need accountable, transparent algorithms that don't reinforce bias, and ways to fix mistakes. Analytics can target aid to those in need, or help predatory firms sell high-cost loans and worthless degrees.

Feedback loops

  • Recommenders can create echo chambers breeding stereotypes, misinformation and polarization, already seen in elections.
  • Self-reinforcing loops: employers using credit scores in hiring push a worker hit by misfortune into a spiral: missed payments, lower score, no job, deeper poverty, lower score.
  • Systems thinking (the whole system, people included) predicts many such effects: does it amplify inequality or counter injustice? Beware unintended consequences.
Misfortune Missed payments Lower score Fewer job offers Poverty score used in hiring
The book's credit-score-in-hiring example of a self-reinforcing feedback loop.

Privacy and Tracking

  • Data the user explicitly enters for a service makes the user the customer. Tracking as a side effect gives the service interests that may conflict with the user's.
  • Some tracking helps users: click data for ranking, "people who liked X also liked Y", A/B tests.
  • In ad-funded services, advertisers are the customers: tracking deepens, retention lengthens, profiles grow. The author calls this surveillance.

Surveillance

  • Try replacing "data" with "surveillance" in common phrases ("surveillance warehouse", "surveillance scientists"); the book jokes about its own title too.
  • We have built the largest mass-surveillance infrastructure ever; IoT puts internet-connected microphones (phones, TVs, assistants, baby monitors, toys) in nearly every room, often with terrible security. Repressive regimes could only dream of this; here corporations collect it.
  • "Nothing to hide" works only for those aligned with power. Benign-seeming uses blur with predictive analytics: car insurance tied to trackers, health cover tied to fitness devices. Smartwatch motion data can even reveal typed passwords.

Consent and freedom of choice

  • "Users agreed to the terms" fails: they barely understand what is collected, policies obscure it, and derived datasets merging everyone's data are beyond understanding. Data about one user also exposes non-users.
  • The exchange is one-way and non-negotiable; the service sets the terms.
  • Opting out is costly when a service is essential to social life (smartphones, Facebook, Google) and network effects apply. Only the privileged can afford to decline; for others surveillance is inescapable.

Privacy and use of data

  • "Privacy is dead" is false: privacy is a decision right, the freedom to choose what to reveal to whom.
  • Surveillance transfers that right to the collector ("trust us"). Companies keep findings secret to avoid seeming creepy; intimate facts surface indirectly, e.g. ad targeting by illness, so users lose agency even without reidentification.
  • Firms manage perceptions rather than intrusiveness, often poorly (a true fact can still trigger painful memories). Expect data to be wrong or inappropriate and build ways to handle that; such judgment is human.
  • Privacy settings govern what other users see, not what the service does internally. This mass transfer of privacy rights is historically unprecedented: surveillance used to be manual and costly, and trusted relationships (doctor, attorney) are legally constrained.

Data as assets and power

  • Behavioral "data exhaust" is really the core asset of ad-funded services; the app is a lure. Data brokers secretly buy, infer and resell personal data; startups are valued by "eyeballs".
  • Governments obtain it through deals, coercion, compulsion or theft; bankrupt firms sell it; breaches are frequent. Critics call it a "toxic asset".
  • Weigh benefits against misuse by criminals, foreign intelligence, insiders, future management or future governments; installing tools that could enable a police state is poor civic hygiene.
  • Watching others while avoiding scrutiny is power; tech firms gain much covert power outside public oversight.
Users Free service the lure Behavioral data (asset) Advertisers tracked breaches governments bankruptcy sale "data exhaust" is really the core asset, and a toxic one
In an ad-funded service the behavioral data is the asset, and it carries risks if it leaks or is compelled.

Remembering the Industrial Revolution

  • Data defines the information age as industry defined the Industrial Revolution, which brought growth but also pollution, harsh labor and child labor until safeguards (environmental, workplace, food rules) arrived. Costs rose; society gained.
  • The book cites Bruce Schneier likening data to the information age's pollution and privacy to its environmental challenge, on which future generations will judge us. The author: we should make them proud.

Legislation and self-regulation

  • The 1995 European Data Protection Directive limits collection to specified, explicit, legitimate purposes and to data adequate, relevant and not excessive for them.
  • That clashes with Big Data's collect-everything, explore-for-new-uses philosophy, so its effectiveness is doubtful; new rules are in development.
  • Companies call regulation a drag on innovation, partly fairly (medical data could save lives); balance is hard.
  • Needed: a culture shift. Treat users as humans, not metrics; self-regulate; educate users. Individual control of data is like a national park: unprotected, it suffers a tragedy of the commons. Surveillance is not inevitable.
  • Concrete starts: purge data once it is no longer needed (solvable despite immutability) and enforce access with cryptographic protocols, not just policy.

Summary

  • No single tool serves every use case, so apps compose systems, integrated by batch processing and event streams that carry changes between them.
  • Some systems are systems of record; indexes, views, ML models and summaries are derived through transformations.
  • Asynchronous, loosely coupled derivation keeps a fault in one area from spreading.
  • Expressing dataflow as transformations aids evolution and recovery: change or fix the code, rerun it over the full input.
  • This mirrors database internals, hence unbundling: compose loosely coupled components into an application.
  • Derived state can be observed downstream, all the way to end-user devices, for live-updating, offline-capable UIs.
  • Strong integrity scales with async processing: end-to-end operation IDs for idempotence, asynchronous constraint checks; clients wait or risk an apology. More scalable and robust than distributed transactions, and closer to real business processes.
  • Dataflow plus async checks avoids most coordination, keeping integrity and performance across regions and faults. Audits verify integrity.
  • Data can also harm: hard-to-appeal decisions, discrimination, exploitation, normalized surveillance, exposed intimate details, breaches, unintended consequences.
  • Engineers are responsible for working toward a world that treats people with humanity and respect.

Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.