/designing-data-intensive-applications:stream-processing-designerfrom designing-data-intensive-applications
Designs stream processing systems for unbounded data: selects message brokers (Kafka vs RabbitMQ), implements CDC from PostgreSQL/MySQL/MongoDB via Debezium or Maxwell, chooses window types (tumbling, hopping, sliding, session), joins event streams, and configures exactly-once fault tolerance.
Ships in designing-data-intensive-applications. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are building or evaluating a system that processes data continuously as it arrives — not in periodic batch runs — and need to make concrete decisions about message transport, windowed aggregation, stream joins, and fault tolerance.
This skill applies when:
This skill produces architecture decisions, not code. For encoding format selection (Avro vs. Protobuf for event schemas), use encoding-format-advisor first. For batch pipeline design, use batch-pipeline-designer. For overall data integration across multiple systems, use data-integration-architect.
Before applying the frameworks, collect:
WHY: The choice between a log-based and traditional message broker determines whether consumers can replay events, whether multiple consumers can read independently, and what happens when a consumer falls behind. Getting this wrong forces an expensive migration later.
Use the broker selection framework in references/broker-selection-framework.md. Key decision signals:
Choose a log-based broker (Kafka, Amazon Kinesis, Apache Pulsar) when:
Choose a traditional broker (RabbitMQ, ActiveMQ, Amazon SQS, Azure Service Bus) when:
Critical difference in replay behavior: In a log-based broker, consuming a message is a read-only operation — the consumer's offset advances, but the log is unchanged. You can reprocess by resetting the offset. In a traditional broker, acknowledgment deletes the message — reprocessing is impossible unless you saved it elsewhere.
WHY: Two patterns exist for getting events into the stream: direct event production (application code writes to the broker) and change data capture (CDC, where the database's replication log is tapped). Each has different consistency guarantees, and the wrong choice causes the dual-write race condition — a form of data loss where two systems permanently diverge.
Avoid dual writes: Writing to both the database and the broker in application code creates a race condition. Two concurrent writers can reach the database and broker in opposite orders, leaving the systems permanently inconsistent — with no error and no detection. See the race condition in the "Keeping Systems in Sync" section of the source chapter (page 452).
When to use CDC:
Per-database CDC tool mapping:
| Database | Tool | Mechanism | Notes |
|---|---|---|---|
| PostgreSQL | Debezium, Bottled Water | WAL (write-ahead log) parsing | Debezium uses logical replication slots; Bottled Water uses a dedicated API |
| MySQL | Debezium, Maxwell | binlog parsing | Both parse the MySQL binary log; Maxwell is simpler, Debezium has broader ecosystem |
| MongoDB | Debezium, Mongoriver | oplog tailing | MongoDB oplog is a capped collection; must be large enough to survive processing delays |
| Oracle | GoldenGate | LogMiner / proprietary | Requires Oracle licensing; GoldenGate is the standard production choice |
| Any | Kafka Connect | Plugin-based | Kafka Connect wraps CDC tools; use when events need to land in Kafka topics |
CDC bootstrap strategy (initial snapshot): A CDC pipeline that taps the replication log only captures changes from the time it starts. For rebuilding a derived system from scratch, you need the full historical state.
pg_dump with a known log sequence number, or a tool-integrated snapshot)Some CDC tools (Debezium) handle this bootstrap automatically. For others, it is a manual operation. Confirm before assuming automation.
Log compaction as an alternative to periodic snapshots: If using a log-based broker with log compaction enabled, the compacted topic always contains the most recent value for every key. A new derived system can bootstrap by reading the compacted topic from offset 0, then switch to live CDC without taking a database snapshot.
When to use event sourcing instead of CDC:
Key difference: In CDC, the application writes to a mutable database and the log is extracted afterward. In event sourcing, the application writes immutable events to an event log first, and current state is derived from the log. The event log is the system of record.
Commands vs. events in event sourcing: A command is a request that may fail (validation, constraint checks). When accepted, it becomes an immutable event. Validate commands synchronously before committing them as events — once an event is written to the log, downstream consumers cannot reject it.
WHY: Windows bound an otherwise infinite stream so aggregations are computable. The wrong window type either produces results that don't match business intent (tumbling where smoothing is needed), consumes excessive memory (sliding on high-volume streams), or fails to capture session behavior (any fixed window for user activity).
Use the window type reference in references/window-type-selection.md. Decision framework:
Tumbling window — Fixed-length, non-overlapping. Every event belongs to exactly one window.
Hopping window — Fixed-length with overlap (hop size < window size). Events appear in multiple windows.
Sliding window — Variable-length. Groups all events within a fixed time interval of each other.
Session window — No fixed duration. Groups events from the same user/entity with gaps smaller than a timeout.
Event time vs. processing time: Always use event timestamps (event time) for window boundaries when event correctness matters. Processing time (the wall clock of the stream processor) produces artifacts when the processor restarts — a backlog of old events appears as a sudden spike when consumed, producing false anomalies. Use processing time only when event delay is negligibly small and approximate results are acceptable.
Straggler events: When using event-time windows, events can arrive after the window has closed (delayed by network, buffering, or offline clients). Two options:
WHY: Stream joins require the processor to maintain state — buffered events or a local copy of a table — to match events from different inputs. Each join type has different state requirements, ordering sensitivity, and time-dependence. Choosing the wrong type produces nondeterministic results or excessive memory consumption.
See references/join-type-reference.md for detailed implementation patterns.
Stream-stream join (window join):
Stream-table join (stream enrichment):
Table-table join (materialized view maintenance):
SELECT follows.follower_id, array_agg(tweets.*) FROM tweets JOIN follows ON follows.followee_id = tweets.sender_id GROUP BY follows.follower_id)Selecting the right join type:
| Situation | Join Type |
|---|---|
| Two event streams, correlate events within a time window | Stream-stream |
| One event stream + one reference dataset | Stream-table |
| Maintaining a combined read model from two source tables | Table-table |
| Enriching events with slowly changing data | Stream-table with SCD versioning |
WHY: A stream processor runs indefinitely. Unlike a batch job that can be fully restarted from its immutable input, restarting a stream job from scratch means reprocessing potentially years of events. The fault tolerance strategy determines how much reprocessing happens after a failure and whether outputs are produced multiple times.
See references/fault-tolerance-comparison.md for a full comparison.
Microbatching (Spark Streaming, Spark Structured Streaming):
Checkpointing (Apache Flink, Apache Samza):
Idempotent processing:
The end-to-end exactly-once argument: Framework-level exactly-once (microbatching or checkpointing) only governs what happens inside the stream processor. As soon as output leaves the processor — a write to an external database, an email sent, a message published to another broker — the framework cannot discard that output on failure. If the processor restarts, the side effect happens again.
True end-to-end exactly-once requires that all output side effects are either:
Practically: if you send emails or charge payments from a stream processor, microbatching and checkpointing alone are not sufficient. Design the output operation to be idempotent (e.g., deduplicate email sends by event ID), or use atomic commits if available.
WHY: Lambda architecture (separate batch and speed layers with a merge layer) was designed to get the correctness of batch processing with the low latency of stream processing. Kappa architecture challenges whether this complexity is necessary.
Lambda architecture:
Kappa architecture:
Choose Lambda when: You have very large historical datasets (petabytes) where stream reprocessing is too slow; you need the batch layer's correctness guarantees independently; the team already operates separate batch and stream infrastructure.
Choose Kappa when: Your log-based broker retains sufficient history; reprocessing speed is acceptable; you want operational simplicity; the stream processing framework can handle both historical and live data at acceptable throughput.
Scenario: An e-commerce application uses PostgreSQL as its primary database. Product search is powered by Elasticsearch. Currently, the application writes to both PostgreSQL and Elasticsearch directly (dual write). The search index is frequently stale or inconsistent with the database.
Trigger: "How do I keep Elasticsearch in sync with PostgreSQL without dual writes?"
Process:
Output: PostgreSQL → Debezium → Kafka topic (log-compacted) → Elasticsearch Sink Connector → Elasticsearch. No dual writes. Consistent ordering. Replay-safe.
Scenario: A payments platform needs to detect when a user makes more than 5 failed payment attempts within 30 minutes (a pattern suggesting card testing fraud). Events arrive from multiple microservices with occasional delays of up to 2 minutes.
Trigger: "How do I detect rapid failed payment attempts in a stream processor?"
Process:
payment.attempt events directly to Kafka when processing payments. Event sourcing pattern: the event is the record of what happened.Output: Flink job with session window (30-minute gap) on payment.attempt stream → emits fraud.alert event when session count exceeds threshold → downstream alert router deduplicates and notifies.
Scenario: A SaaS analytics platform processes a high-volume stream of user activity events (page views, feature usage). Each event contains a user ID but not user metadata (subscription tier, company, region). Analytics queries always segment by these dimensions. Currently, a nightly batch job denormalizes the data into a data warehouse. The 24-hour delay makes same-day analytics impossible.
Trigger: "How do I enrich activity events with user profile data in real time?"
Process:
Output: Activity stream + User profile CDC stream → stream-table join in Flink → enriched event stream → warehouse and dashboard consumers. Latency reduced from 24 hours to seconds.
references/broker-selection-framework.md — Detailed comparison of log-based vs. traditional brokers with scoring criteriareferences/window-type-selection.md — Window type decision table, implementation notes, and straggler handling patternsreferences/join-type-reference.md — Join type patterns, state management requirements, and time-dependence analysisreferences/fault-tolerance-comparison.md — Microbatching vs. checkpointing vs. idempotent writes comparison, with exactly-once end-to-end argumentRelated skills:
encoding-format-advisor — Choose encoding format (Avro, Protobuf) for events on the broker (dependency)batch-pipeline-designer — For bounded dataset processing; compare Lambda vs. Kappa decisionsdata-integration-architect — Cross-system integration decisions when stream processing is one component of a larger data architectureThis skill is licensed under CC-BY-SA-4.0. Source: BookForge — Designing Data-Intensive Applications by Martin Kleppmann.
Install related skills from ClawhHub:
clawhub install bookforge-encoding-format-advisorOr install the full book set from GitHub: bookforge-skills
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub bookforge-ai/bookforge-skills --plugin designing-data-intensive-applications14 skills in this plugin
/batch-pipeline-designerDesign batch data processing pipelines for large-scale, bounded datasets processed offline. Use when building ETL workflows, processing logs or clickstream data at scale, generating ML feature pipelines or search indexes, or joining two large datasets that cannot fit in memory. Trigger phrases: "design a batch pipeline", "should I use Spark or MapReduce", "how do I join two large datasets", "build an ETL workflow", "process server logs at scale", "how do I handle skewed data in joins", "implement PageRank on a distributed graph", "design an offline processing job". Covers MapReduce vs dataflow engines (Spark, Flink, Tez), three join strategies (sort-merge, broadcast hash, partitioned hash) with selection criteria, graph processing via the Pregel/BSP model, and fault tolerance via materialization vs recomputation. Does not apply to unbounded input streams (see stream-processing-designer) or low-latency OLTP query serving. Produces a pipeline architecture recommendation with engine choice, join strategy, and fault tolerance approach.
/concurrency-anomaly-detectorScan application code, SQL queries, or ORM code for exposure to the 6 database concurrency anomalies and produce a findings report with severity, affected locations, and fix recommendations. Use when: debugging a nondeterministic data corruption or race condition bug under concurrent load; auditing transaction code before deployment or after switching databases (isolation defaults differ across engines); a read-modify-write cycle or check-then-act pattern may be exposed to lost updates or write skew; an aggregate query (COUNT, SUM) guards an INSERT or UPDATE (phantom read exposure); or multiple tables are updated in one transaction without serializable isolation. Distinct from transaction-isolation-selector (which chooses the isolation level) — this skill scans code to find which anomalies existing code is already exposed to. Covers Python, Java, Go, JavaScript, Ruby; raw SQL; ORM code (SQLAlchemy, Hibernate, ActiveRecord, GORM); PostgreSQL, MySQL InnoDB, Oracle, SQL Server, and distributed databases. Maps code patterns (read-modify-write, SELECT/INSERT pairs, cross-table boundaries, snapshot boundary reads) to anomaly type, trigger conditions, and minimum fix (isolation upgrade vs. application-level mitigation).
/consistency-model-selectorChoose the correct consistency model (linearizability, causal consistency, or eventual consistency) for each operation in a distributed system, and select the matching implementation mechanism. Use when designing a new distributed data system, deciding whether ZooKeeper or etcd is needed for coordination, evaluating whether two-phase commit is appropriate for cross-node transactions, debugging correctness violations (stale reads, split-brain, uniqueness constraint failures), or distinguishing linearizability from serializability. Also use when applying the CAP theorem correctly (beyond the "pick 2 of 3" oversimplification), selecting total order broadcast as a consensus primitive, evaluating 2PC failure modes and lock-holding cost, or assessing whether causal consistency is sufficient in place of linearizability. Produces a per-operation consistency recommendation with replication mechanism, ordering guarantee, and — when consensus is needed — protocol selection (Raft, Zab, Paxos) with documented failure modes. Does not cover replication topology or failure recovery strategy (see replication-strategy-selector, distributed-failure-analyzer).
/data-integration-architectDesign the integration architecture for systems with multiple specialized data stores (Postgres, Elasticsearch, Redis, data warehouses) that must stay in sync. Use when deciding how data flows between components, avoiding dual writes, reasoning about correctness across system boundaries (idempotency, end-to-end operation identifiers), choosing between Lambda and Kappa architecture, or applying the "unbundling databases" pattern to compose specialized tools instead of relying on a single monolith. Trigger phrases: "how do I keep Postgres and Elasticsearch in sync?", "should I use CDC or event sourcing to propagate data?", "how do I avoid dual writes across microservices?", "my downstream systems are going out of sync — how do I fix the architecture?", "how do I design derived data pipelines?", "what is the system of record pattern?", "how do I integrate OLTP with a search index and an analytics warehouse?", "how do I design for end-to-end idempotency?". This is the capstone skill for data systems design — it synthesizes batch pipelines, stream integration, consistency, and replication into a single architecture recommendation. Produces a component map (systems of record vs derived views), data flow diagram, and correctness analysis. Does not replace batch-pipeline-designer or stream-processing-designer — delegates to them for pipeline internals.
/data-model-selectorChoose between relational, document, and graph data models for an application by analyzing data shape, relationship complexity, and query patterns. Use when asked "should I use MongoDB or PostgreSQL?", "when does a graph database make sense?", "how do I choose between SQL and NoSQL?", or "what data model fits my access patterns?" Also use for: evaluating impedance mismatch between data model and application code; deciding schema-on-read vs. schema-on-write for heterogeneous data; diagnosing whether many-to-many relationships call for relational or graph model; choosing between property graphs and triple-stores; deciding when polyglot persistence is appropriate. Produces a concrete recommendation with trade-off analysis — not "it depends." Covers relational (PostgreSQL, MySQL), document (MongoDB, CouchDB), and graph (Neo4j, Datomic) models including schema enforcement strategies and data locality trade-offs.
For storage engine internals (LSM-tree vs B-tree), use storage-engine-selector instead. For OLTP vs. analytics routing, use oltp-olap-workload-classifier instead.
/distributed-failure-analyzerDiagnose distributed system failures caused by network faults, unreliable clocks, or process pauses — and map each to its correct mitigation. Use when: a node is intermittently timing out with no clear network outage; a lock-holder or leader keeps acting after being declared dead (zombie leader / split brain via distributed locking, not replication topology — use replication-failure-analyzer for replica split brain); stale reads persist beyond expected replication lag; wall-clock-based lease checks or last-write-wins conflict resolution is producing data loss under clock skew; or cascading node-death declarations are occurring under load. Also use proactively to audit timing assumptions in new system designs (absence of fencing tokens, NTP drift exposure, GC pause risk). Distinct from replication-failure-analyzer (replication lag anomalies, failover pitfalls, quorum edge cases). Produces a structured failure report: symptom → fault category → mechanism → mitigation. Covers: asynchronous network behavior, timeout tuning and cascade risk, NTP drift and clock jump mechanics, process pause causes (GC, VM migration, paging, SIGSTOP), fencing tokens with ZooKeeper zxid/cversion, Byzantine fault scoping, and system model selection (crash-stop vs. crash-recovery vs. Byzantine; synchronous vs. partially synchronous vs. asynchronous).
Other plugins' skills for the same job