Markdown Editor

Stream Processing Engine System Design Template

Stream processing engine: event time, watermarks, windows and triggers, late data, keyed state, barrier checkpoints, exactly-once sinks, backpressure, rescaling

Cómo usar: Use it when designing or reviewing a stateful streaming platform or a large streaming job. Fill the capacity inputs (event rate, keys, lateness, checkpoint interval) first, because state size and recovery time decide the cluster shape. The main pitfall is promising exactly-once end to end when only the state is exactly-once; choose idempotent upserts or transactional sinks per output.

Vista previa

System Design: [Stream processing engine name]

Reference design for a distributed stream processing engine that runs long-lived, stateful jobs over unbounded event streams. It covers event time versus processing time, windows, watermarks, triggers and late data, keyed state with periodic checkpoints, exactly-once state with transactional sinks, backpressure and rescaling. The concepts follow the Dataflow model (Akidau et al., PVLDB vol. 8 no. 12, 2015) and asynchronous barrier snapshots (Carbone et al., 2015); the text and the worked design are original. It follows the structure of the System Design Document template. Replace every [bracketed] value and every row marked Example.

Document control

FieldValue
Document ID[SDD-SPE-001]
System / feature[Stream processing engine for real-time aggregation]
Version[0.1]
Status[Draft / In review / Approved / Implemented / Superseded]
Owner[@owner]
Author(s)[@author]
Reviewers[@reviewer-1], [@reviewer-2]
Last updatedYYYY-MM-DD
Classification[Internal]
Delivery guarantee[Exactly-once state; exactly-once or idempotent output per sink]
RelatedMessage Queue System Design (system-design/design-message-queue), CDC Pipeline System Design (system-design/design-cdc-pipeline), Data Pipeline Specification (ai-data/data-pipeline-spec)

Approvals

RoleNameDecisionDate
Tech lead[@name][Approved / Changes requested]YYYY-MM-DD
Staff / principal engineer[@name][Decision]YYYY-MM-DD
SRE / operations[@name][Decision]YYYY-MM-DD
Data platform owner[@name][Decision]YYYY-MM-DD
Security[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft for design review
0.2YYYY-MM-DD[@name]Example: Moved from processing-time to event-time windows after the replay incident
0.3YYYY-MM-DD[@name]Example: Added unaligned checkpoints for jobs under sustained backpressure
1.0YYYY-MM-DD[@name]Example: Approved

Contents

1. Overview

1.1 Problem statement

[Example: Product teams compute campaign metrics (impressions, clicks, spend per campaign and country per minute) with a nightly batch job and a fragile set of consumers that count in memory. Dashboards are 12 hours stale, counts change after every consumer restart, and mobile events that arrive late (devices offline, then reconnecting) are either dropped or counted in the wrong minute. Advertisers dispute numbers that do not match the batch reports.]

1.2 Proposed solution

[Example: A shared stream processing engine runs declarative jobs that read partitioned event logs, assign each event to event-time windows, keep per-key state in an embedded log-structured store on local SSD, and take a consistent distributed snapshot every 30 s by injecting barriers into the streams. Watermarks track event-time progress per source partition; triggers emit early speculative results every 10 s, an on-time result when the watermark passes the window end, and corrections for late events for up to 10 minutes. Sinks either commit transactionally on checkpoint completion or write idempotent upserts keyed by window. Jobs rescale by restoring a savepoint with a different parallelism; state moves in key groups.]

1.3 Decisions requested from reviewers

IDQuestionRecommended optionSection
Q-01Example: Event time or processing time for business metrics?Event time with heuristic watermarks7.1
Q-02Example: How long do we accept late events?10 minutes allowed lateness; later events to a side output7.2
Q-03Example: Checkpoint mechanism?Aligned barrier snapshots, unaligned when backpressured7.3
Q-04Example: Exactly-once to sinks?Two-phase commit for log sinks, idempotent upsert for databases7.4
Q-05Example: Checkpoint interval?30 s, bounded by freshness for transactional readers3.4, 7.4
[Q-nn][Question][Option][Section]

1.4 45-minute interview path

MinutesCoverOutput on the whiteboard
0 to 5Clarify the use case: what is aggregated, freshness target, how late events can be, correctness expectationCore requirements FR-01 to FR-05, NFR-01 to NFR-04
5 to 10Estimate ingest, state size and recovery timeParallelism 64, ~25 GB state, recovery of a few minutes
10 to 20Draw sources, coordinator, workers, state backend, checkpoint storage, sinksDiagram in section 6
20 to 35Deep dive: pick event time and watermarks (7.1) plus checkpoints and exactly-once (7.3, 7.4); if the interviewer leans on correctness of late data, use 7.2 insteadBarrier and two-phase commit sequence
35 to 42Backpressure, rescaling, hot keysKey groups, credit-based flow control
42 to 45Trade-offs and what changes at 10xTable in section 10

2. Requirements

2.1 Core functional requirements

IDRequirementPriority
FR-01Example: Read events from partitioned logs and write results to logs, key-value stores and an analytical storeMust
FR-02Example: Group events by key and assign them to tumbling, sliding and session windows by event timeMust
FR-03Example: Emit early, on-time and late results per window as configured by a triggerMust
FR-04Example: Keep per-key state across restarts with no loss and no double countingMust
FR-05Example: Stop a job with a savepoint and restart a new version or parallelism from itMust
FR-06Example: Route events later than the allowed lateness to a side output for auditShould
FR-07Example: Join two streams by key within an event-time intervalShould
[FR-nn][Requirement][Must / Should / Could]

2.2 Non-functional requirements

IDQualityTargetMeasured as
NFR-01ThroughputExample: 2 million events/s per job at peakSource lag stays flat during load test
NFR-02FreshnessExample: p99 of 60 s from event arrival to visible on-time resultEnd-to-end marker events
NFR-03CorrectnessExample: Final window values equal a batch recomputation over the same inputDaily reconciliation job
NFR-04RecoveryExample: Output fresh again within 5 minutes after a worker loss at peakChaos drill
NFR-05IsolationExample: One job's backpressure does not slow another jobMulti-tenant load test
[NFR-nn][Quality][Target][Measurement]

2.3 Below the line (out of scope)

  • [Example: A SQL interface for ad-hoc queries; jobs are defined in code or the pipeline format in 4.2 for this release]
  • [Example: Ingestion from devices; the engine reads from the existing message logs (system-design/design-message-queue)]
  • [Example: Machine-learning feature serving; results land in stores that a feature service reads]
  • [Example: Exactly-once delivery to external HTTP endpoints that offer no idempotency key]
  • [Item deferred, with the release that will take it]

3. Capacity estimation

3.1 Assumptions

InputSymbolValueSource
Peak events per second (one large job)RRExample: 2 000 000Source log metrics x growth
Average event sizeeeExample: 1 KBSampled payloads
Events per second one stateful task handlesccExample: 40 000Benchmark of the window operator
Active keys (campaign x country)KKExample: 5 millionLast 30 days
Window size and allowed latenessww, LLExample: 1 min, 10 minProduct requirement
Window state per key and windowsws_wExample: 100 BMeasured
Deduplication horizon and ID sizehh, sds_dExample: 600 s, 16 BSource retry behaviour
Checkpoint intervalTcT_cExample: 30 s7.3

3.2 Ingest and parallelism

B=R×e=2×106×1 KB=2 GB/sB = R \times e = 2 \times 10^{6} \times 1\ \text{KB} = 2\ \text{GB/s}
P=Rc×1.25=2×1064×104×1.25=62.5⇒64 tasksP = \frac{R}{c} \times 1.25 = \frac{2 \times 10^{6}}{4 \times 10^{4}} \times 1.25 = 62.5 \Rightarrow 64\ \text{tasks}

Consequence: the keyed shuffle moves roughly the same 2 GB/s (16 Gbit/s aggregate) across the network on top of ingest, so worker network interfaces (Example: 25 Gbit/s) are sized for ingest, shuffle and checkpoint upload together, and the job is split into at least 64 parallel tasks from day one. The maximum parallelism (number of key groups) is fixed at 1 024 so the job can grow 16 times without rehashing state.

3.3 State size

Open windows per key are one current window plus the lateness horizon:

Swin=K×(1+Lw)×sw=5×106×11×100 B=5.5 GBS_{win} = K \times \left(1 + \frac{L}{w}\right) \times s_w = 5 \times 10^{6} \times 11 \times 100\ \text{B} = 5.5\ \text{GB}
Sdedup=R×h×sd=2×106×600×16 B=19.2 GBS_{dedup} = R \times h \times s_d = 2 \times 10^{6} \times 600 \times 16\ \text{B} = 19.2\ \text{GB}

Total keyed state is about 25 GB, or about 0.39 GB per task at parallelism 64. Consequence: deduplication, not the windows, dominates state, so it gets its own TTL and is the first thing to shrink (shorter horizon or idempotent producers upstream). State lives in an embedded log-structured store on local SSD rather than on the heap, which keeps garbage collection pauses away from the watermark path and enables incremental checkpoints.

3.4 Checkpoints and recovery

With Example 20% of state changing per interval, each incremental checkpoint uploads 5 GB, or about 167 MB/s sustained to object storage. Consequence: checkpoint upload is a steady background load that must be budgeted in network capacity, not an occasional burst.

After a worker loss the job rewinds to the last checkpoint. Worst-case backlog is one interval plus detection and restore time:

backlog=R×(Tc+tdetect+trestore)=2×106×(30+10+4) s=88×106 events\text{backlog} = R \times (T_c + t_{detect} + t_{restore}) = 2 \times 10^{6} \times (30 + 10 + 4)\ \text{s} = 88 \times 10^{6}\ \text{events}

Spare capacity is 64×40 000−2×106=560 00064 \times 40\,000 - 2 \times 10^{6} = 560\,000 events/s, so catching up takes about 88×106/5.6×105≈15788 \times 10^{6} / 5.6 \times 10^{5} \approx 157 s. Consequence: recovery to fresh output is under 3 minutes at peak, which meets NFR-04 but not a 60 s freshness promise during incidents; raising headroom to 1.5x or shortening the interval are the two levers.

3.5 Output

Each of the 5 million keys emits one on-time row per minute, about 83 000 rows/s, plus early firings every 10 s (up to 500 000 rows/s if every key is active). Consequence: sinks must accept batched upserts, and early firings are enabled only for keys a dashboard actually reads.

3.6 Summary

QuantityEstimateDesign consequence
Ingest2 GB/s (16 Gbit/s aggregate)Worker NICs sized for ingest + shuffle + checkpoints; shuffle sized like ingest
Parallelism64 tasks, 1 024 key groupsRescale up to 16x without rehashing
Keyed state~25 GB (dedup 19.2 GB)Embedded LSM store on SSD; TTL on dedup state
Checkpoint upload~167 MB/sIncremental checkpoints; network budget
Recovery~3 min to fresh at peakMeets NFR-04; more headroom if freshness tightens
Output83 000 to 500 000 rows/sBatched upserts; early firings opt-in

4. API design

4.1 Control plane API

Method and pathPurposeNotes
POST /v1/jobsSubmit a job definition and artifactIdempotency key header; returns job ID
GET /v1/jobs/{id}Status, parallelism, last checkpoint, lag
POST /v1/jobs/{id}/savepointsTake a savepoint, optionally stop the jobReturns savepoint URI
POST /v1/jobs/{id}/rescaleRestart from a savepoint with new parallelismBounded by max parallelism
POST /v1/jobs/{id}/upgradeDeploy a new version from a savepointState compatibility checked first
DELETE /v1/jobs/{id}Cancel a jobSavepoint taken unless force=true

4.2 Pipeline definition

A job declares what is computed, where in event time, when results are emitted and how refinements relate (the four questions of the Dataflow model, paraphrased):

job: campaign-metrics
version: 14
source:
  log: ad-events
  timestamp_field: event_time
  watermark:
    strategy: bounded_out_of_orderness
    max_delay: 30s
    idle_partition_timeout: 60s
key_by: [campaign_id, country]
window:
  type: tumbling
  size: 1m
  allowed_lateness: 10m
trigger:
  early: every 10s processing_time
  on_time: at_watermark
  late: every_element
accumulation: accumulating   # each firing carries the full value so far
aggregate: {impressions: count, clicks: count, spend_micros: sum}
dedup: {field: event_id, horizon: 10m}
late_side_output: ad-events-too-late
sink:
  type: upsert_store
  table: campaign_minute
  key: [campaign_id, country, window_start]
checkpoint: {interval: 30s, mode: aligned, unaligned_after: 60s}

4.3 Output record

Every emitted result states which firing it is, so consumers can tell a speculative value from a final one:

{"campaign_id": "c-7781", "country": "VN", "window_start": "2026-10-22T09:41:00Z", "window_end": "2026-10-22T09:42:00Z", "impressions": 18240, "clicks": 311, "spend_micros": 9120000, "pane": {"timing": "LATE", "index": 3, "is_last": false}, "watermark": "2026-10-22T09:42:31Z"}

4.4 Errors

StatusProblem typeWhen
409state-incompatibleUpgrade changes a stateful operator's ID or state schema without migration
409rescale-out-of-boundsRequested parallelism exceeds max parallelism
422invalid-pipelineWindow, trigger or watermark settings contradict each other
503checkpoint-in-progressSavepoint requested while the previous one is still running

5. Data model

5.1 Entities

A key maps to a key group by hash modulo max parallelism; key groups map to tasks in contiguous ranges. Rescaling moves whole key groups, never single keys, which keeps state handles coarse.

5.2 Storage choices

DataStoreKeyWhy
Job and version metadataExample: Relational databasejob_id, versionSmall, audited, transactional
Leader and checkpoint pointerCoordination service (system-design/design-distributed-lock-coordination)jobs/{id}/leader, jobs/{id}/latest-checkpointLeader election and an atomic pointer swap
Live keyed stateEmbedded LSM store on local SSD per task(key_group, key, namespace)Fast local reads and writes; large state
Checkpoint filesObject storage/{job}/{checkpoint_id}/{operator}/{handle}Durable, cheap, shared files across incremental checkpoints
Input and output streamsPartitioned logPartition by keyReplayable from offsets

5.3 Access patterns

Access patternServed byPartition key and rationale
Update window state for one eventLocal LSM, key (key_group, campaign_id, country, window_start)Key group from the business key, so all events for a key reach one task
Fire all windows ending before the watermarkEvent-time timer queue per task, ordered by timestampTimers stored with the key group, so they move with state on rescale
Check duplicate event_idLocal LSM, key (key_group, campaign_id, country, event_id) with TTL 10 minKey group from the business key, so deduplication runs in the same task as the window; it inherits that key's skew (7.5)
Find the latest completed checkpointCoordination service pointerOne small value per job, updated atomically
Restore state for key groups 0 to 15Checkpoint metadata lists handles per key-group rangeRange layout lets a task fetch only its ranges
Read results for a dashboardSink table keyed (campaign_id, country, window_start)Upsert target; idempotent by construction

6. High-level design

ComponentResponsibilityScales by
Job coordinatorSchedules tasks on workers, restarts on failure, one active per jobLeader election; one per job
Checkpoint coordinatorTriggers checkpoints, collects acknowledgements, publishes the completed pointerPart of the coordinator
Source tasksRead partitions, extract timestamps, generate watermarksSource partitions
Window and dedup tasksKeyed state, timers, triggersKey groups
Sink tasksBuffer output, pre-commit and commit per checkpointOutput partitions
Object storageCheckpoint and savepoint filesManaged service

7. Detailed design

7.1 Deep dive: time, watermarks and progress

Processing time is when a worker sees an event; event time is when it happened. Mobile and retried events arrive minutes late, and a replay after an outage delivers hours of events in minutes, so grouping by processing time puts events in the wrong window and makes results depend on when the job ran.

OptionHow it worksStrengthWeakness
A. Processing-time windowsWindow by arrival clockSimple; no lateness logicWrong under replay and delay; not reproducible
B. Event time with perfect watermarksSource guarantees order (for example a single ordered log)Exact completenessRarely available for real sources
C. Event time with heuristic watermarksWatermark = max event time seen minus a bound, per source partitionWorks on real data; tunableSome events arrive behind the watermark (late)
D. Event time, no watermarks, fire on processing-time triggers onlyPeriodic emissions of running totalsFreshNever knows when a window is complete

Choice: C, with per-partition watermarks combined by taking the minimum across inputs at every operator. Reason: it produces reproducible results under replay and a clear point at which a window is considered complete, while triggers (7.2) cover freshness before that point and corrections after.

Rules that keep watermarks honest:

  • Generate watermarks per source partition, not per task, so a slow partition holds back the watermark instead of producing late data.
  • Mark a partition idle after idle_partition_timeout so an empty partition does not stall all windows; un-idle it on the next event.
  • Never let the watermark move backwards; on restore, start from the checkpointed watermark.
  • Track watermark lag (processing time minus watermark) as the main freshness signal; it is the number a dashboard should show.

7.2 Deep dive: windows, triggers and late data

Windows decide where in event time results are computed; triggers decide when in processing time results are emitted; accumulation decides how successive results for the same window relate.

Window typeUseState cost
Tumbling (fixed)Per-minute metricsOne open window per key plus lateness
Sliding (hopping)Moving averages, for example 10 min every 1 minOne copy per overlapping window, or panes combined at firing
SessionUser activity separated by a gapWindows merge as events arrive; state per active session
Global with custom triggerCount-based or per-key batchingUnbounded unless a trigger clears it
Accumulation modeEach firing carriesConsumer must
DiscardingOnly new data since last firingSum firings itself
AccumulatingFull value so farOverwrite (upsert by window key)
Accumulating and retractingNew full value plus a retraction of the previous oneApply retraction, then the new value (needed when results are regrouped downstream)

Options for late data: drop silently; keep windows open forever; keep windows for an allowed lateness then send later events to a side output. Choice: allowed lateness of 10 minutes with accumulating firings and a side output. Reason: state cost is bounded (3.3), dashboards stay correct through ordinary device delays, and nothing is dropped silently: the side output feeds the daily reconciliation that compares stream totals with the batch recomputation (NFR-03).

7.3 Deep dive: keyed state and checkpoints

OptionHow it worksStrengthWeakness
A. Write every state change to an external databaseState lives remotelySimple recoveryOne remote write per event; 2 million writes/s
B. Periodic stop-the-world snapshotPause all tasks, snapshot, resumeSimple consistencyPauses the whole job; long at 25 GB
C. Aligned barrier snapshotsCoordinator injects numbered barriers at sources; an operator snapshots when barriers from all inputs arrivedConsistent without global pause; small checkpoints with incremental uploadAlignment waits under backpressure
D. Unaligned barrier snapshotsBarriers overtake buffered records; in-flight buffers are stored in the checkpointCheckpoint time independent of backpressureLarger checkpoints; more restore work
E. Changelog per state updateEvery update appended to a changelog logFast recovery with standby replicasDoubles write traffic

Choice: C by default, switching a checkpoint to D when alignment exceeds 60 s. Reason: aligned barriers give a consistent cut of all operator state and source offsets with no global pause and small checkpoints; the fallback keeps checkpoints completing under sustained backpressure, which is exactly when a recovery point matters most.

State snapshots are asynchronous: the task flushes its memtable, records the list of immutable files and continues processing while files upload. Files already uploaded by earlier checkpoints are referenced, not copied. Retain the last 3 completed checkpoints and delete unreferenced files with a reference count, never by age alone.

7.4 Deep dive: exactly-once state and output

Checkpoints make state exactly-once: after a failure, state and source offsets rewind together, so each event affects state once. Output is a separate problem because records emitted after the last checkpoint are emitted again on replay.

OptionHow it worksFitsCost
A. At-least-once outputEmit immediately; duplicates on replayMetrics consumers that tolerate duplicatesConsumers deduplicate
B. Idempotent upsertOutput key is deterministic (campaign_id, country, window_start) and the value is a full accumulating resultKey-value and analytical storesNeeds accumulating mode and deterministic keys
C. Two-phase commit sinkWrite into a transaction per checkpoint, pre-commit at the barrier, commit when the checkpoint completesTransactional logs read with read-committed isolationOutput visible only after commit, so latency is at least the checkpoint interval
D. Write-ahead then publishBuffer output in state, publish after checkpointSinks without transactionsDuplicates possible if publish fails mid-way

Choice: B for databases and C for the output log. Reason: B gives exactly-once effect with no extra latency because replays overwrite the same rows with the same values; C is the only way to give downstream stream consumers exactly-once records, and the 30 s interval fits the 60 s freshness target (NFR-02). Record the pre-committed transaction IDs in the checkpoint so a restarted sink can commit or abort them; set the transaction timeout well above the longest expected recovery, or a commit after recovery fails and data is lost.

7.5 Backpressure, hot keys and rescaling

  • Backpressure: use credit-based flow control between tasks: a receiver grants buffer credits and a sender sends only with credit, so a slow sink slows its upstream tasks instead of growing unbounded queues. Expose the share of time each task is backpressured and the source lag.
  • Hot keys: a campaign that gets 10% of all traffic overloads one task. Pre-aggregate before the shuffle (each source task combines events per key for a short interval), then merge partial results after it. For non-mergeable logic, salt the key and add a second merge stage.
  • Rescaling: take a savepoint, restart with the new parallelism, assign key-group ranges to tasks and restore only those ranges. Source partitions are reassigned; the source offsets in the savepoint keep reads exact.
  • Upgrades: give every stateful operator a stable ID; refuse an upgrade whose operator IDs or state schemas cannot be matched (error 409 in 4.4).

7.6 How real systems do it

How real systems do it (paraphrased, not copied). Akidau and colleagues at Google described the Dataflow model in "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing" (PVLDB vol. 8 no. 12, 2015). They argue that pipelines should stop assuming data will ever be complete and should instead let authors choose explicitly among correctness, latency and cost. The model separates what is computed (transformations), where in event time (windowing, including merging session windows), when results are materialised (watermarks and triggers) and how later results relate to earlier ones (discarding, accumulating, or accumulating with retractions). Separately, Carbone and colleagues described lightweight asynchronous barrier snapshots for dataflows (arXiv 1506.08603, 2015), the basis of the aligned checkpoint approach in 7.3. Read both papers for the reasoning; this template only reuses the concepts.

8. Scalability and performance

ConcernApproachLimit before redesign
IngestSource parallelism equals partitionsExample: 128 partitions per topic; add partitions with a planned rescale
ShufflePre-aggregation before keyed exchangeNetwork per worker
State growthTTL on dedup and session state; LSM compaction tuningExample: about 50 GB per task before restore time breaks NFR-04
Checkpoint durationIncremental, asynchronous, unaligned fallbackUpload bandwidth to object storage
Many small jobsShared session cluster for small jobs, dedicated cluster for largeCoordinator memory per job
Hot keysTwo-stage aggregationOne key above one task's capacity after combining

Latency budget for an on-time result (NFR-02, Example):

StepBudget
Producer to log2 s
Watermark delay (bounded out-of-orderness)30 s
Processing and shuffle2 s
Commit wait for transactional sinks (half an interval on average, up to 30 s)15 s typical
Headroom11 s

9. Reliability, security and operations

9.1 Failure-mode table

ComponentFailureDetectionBlast radiusMitigationRTO
WorkerProcess or host lostHeartbeat timeout 10 sTasks of the jobs on that worker; whole job rewindsRestart from last checkpoint; spare slots reservedExample: under 3 min to fresh output
Job coordinatorLeader lostCoordination-service lease expiryScheduling and checkpoints of one jobStandby takes leadership, reads latest pointerExample: under 1 min
Object storageSlow or unavailableCheckpoint duration and failuresNew checkpoints fail; processing continuesTolerate N failed checkpoints, then alert; never delete the last good oneDepends on provider
Source partitionStalled or idlePer-partition watermark lagWindows for all keys stallIdle timeout; alert on stuck partitionExample: 60 s
SinkTransaction commit fails after recoveryCommit error with expired transactionLost output for one intervalTransaction timeout well above recovery time; alertManual replay from savepoint
Late data surgeDevice backlog arrives hours lateSide-output rateResults for old windowsReconciliation job; optional backfill jobNext reconciliation
Poison eventDeserialisation or logic errorTask restarts in a loopWhole jobDead-letter route for bad records; restart backoffExample: 5 min
[Component][Failure][Signal][Scope][Mitigation][Time]

9.2 Security

ThreatControl
Job code runs with broad data accessPer-job service identity; source and sink permissions scoped per job
Sensitive fields in state and checkpointsEncrypt object storage and local disks; drop or tokenise personal fields at the source operator
Tampered artifactsSigned job artifacts verified at submission
Data retention in checkpointsCheckpoint retention aligned with the data retention policy; savepoints catalogued and expired
[Threat][Control]

9.3 Observability

SignalMetricAlert threshold
FreshnessWatermark lag per jobExample: above 120 s for 5 min
Input healthSource lag in records and timeGrowing for 10 min
CheckpointsDuration, size, failures, alignment time3 consecutive failures
BackpressureShare of time backpressured per taskAbove 50% for 15 min
Late dataSide-output events/sAbove baseline x 5
CorrectnessDaily diff versus batch recomputationAny window above 0.1% difference

10. Trade-offs and alternatives

DecisionOptionsChosenWhyWhat we give up
Time domainProcessing time; event timeEvent time with heuristic watermarksReproducible results under replay and delayWatermark delay adds latency
Late dataDrop; keep forever; allowed lateness + side outputAllowed lateness + side outputBounded state, nothing dropped silentlyCorrections after the on-time result
State locationRemote database; embedded LSM; heapEmbedded LSM on SSDLarge state, incremental checkpointsLocal disk management
CheckpointStop the world; aligned; unaligned; changelogAligned with unaligned fallbackConsistent cut, small checkpointsComplexity of two modes
Output guaranteeAt-least-once; idempotent upsert; two-phase commitUpsert for stores, 2PC for logsExactly-once effect where neededCommit latency for log readers
EngineBuild; adopt an open-source engine; managed service[Choice][Reason][Cost]
At 10x load20 million events/s, 250 GB statePartition sources further, raise parallelism within 1 024 key groups, add a standby-replica option to cut restore timeRestore of larger state dominates recoveryMore hardware; checkpoint bandwidth becomes the bottleneck
At 0.1x load200 000 events/s, 2.5 GB stateRun on a shared session cluster with 8 tasks; heap state may sufficeLower operating costLess isolation between jobs

11. Delivery plan and risks

11.1 Milestones

MilestoneScopeExit criterionTarget date
M1One job, event-time windows, upsert sink, shadow run next to the batch jobDaily diff below 0.1% for 14 daysYYYY-MM-DD
M2Checkpoints with failure drillsKill-worker drill meets NFR-04 three timesYYYY-MM-DD
M3Transactional log sink; downstream consumers switchConsumers read committed output onlyYYYY-MM-DD
M4Rescaling and upgrades via savepointsRescale 64 to 128 at peak without data lossYYYY-MM-DD

11.2 Rollout and rollback

[Example: Run the stream job in parallel with the batch job for one month; dashboards switch per team behind a flag. Rollback restores the previous job version from its last savepoint and points dashboards back to batch results.]

11.3 Risks

IDRiskLikelihoodImpactMitigationOwner
R-01Example: Watermark bound too tight, many events lateMediumMediumMeasure the lateness distribution; tune max_delay per source[@name]
R-02Example: State grows without bound in session windowsMediumHighSession gap maximum; state TTL; alert on state size[@name]
R-03Example: Transaction timeouts lose output after long recoveryLowHighTimeout above worst-case recovery; drill[@name]
R-04Example: Teams misread early firings as final numbersHighMediumpane.timing in every record; dashboards label speculative values[@name]
[R-nn][Risk][L / M / H][L / M / H][Mitigation][@name]

12. Appendices

12.1 Open questions

IDQuestionOwnerDue
OQ-01Example: Do finance reports read early firings or only final values?[@name]YYYY-MM-DD
OQ-02Example: Is a standby state replica worth the doubled write traffic?[@name]YYYY-MM-DD
[OQ-nn][Question][@name]YYYY-MM-DD

12.2 Glossary

TermMeaning
Event timeWhen the event happened, carried in the record
Processing timeWhen the engine processes the event
WatermarkThe engine's estimate that no more events older than a timestamp will arrive
TriggerRule that decides when a window emits a result
PaneOne emission of a window; early, on-time or late
Allowed latenessHow long a window's state is kept after the watermark passes its end
Key groupThe unit of keyed state that moves between tasks on rescale
BarrierMarker injected into streams that separates records of two checkpoints
SavepointA user-triggered, retained checkpoint used for upgrades and rescaling
[Term][Meaning]

12.3 Related templates

  • Message Queue System Design (system-design/design-message-queue): the partitioned logs this engine reads and writes.
  • CDC Pipeline System Design (system-design/design-cdc-pipeline): database changes as an input stream.
  • Distributed Lock and Coordination Service System Design (system-design/design-distributed-lock-coordination): coordinator leader election and checkpoint pointer.
  • Data Pipeline Specification (ai-data/data-pipeline-spec): contracts, quality checks and ownership for each job.
  • Event Sourcing and CQRS (architecture/event-sourcing-cqrs): read models fed by stream jobs.

12.4 References

ReferenceUse
Akidau T. et al., "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing", PVLDB vol. 8 no. 12, 2015Windows, watermarks, triggers, accumulation (7.1, 7.2, 7.6)
Carbone P. et al., "Lightweight Asynchronous Snapshots for Distributed Dataflows", arXiv 1506.08603, 2015Barrier snapshots (7.3)
Kleppmann M., Riccomini C., Designing Data-Intensive Applications, 2nd ed., 2026 (inspiration only)Stream processing background
RFC 9457 Problem Details for HTTP APIsError bodies (4.4)

Standard and licence note

Based on the publicly described Dataflow model and asynchronous barrier snapshot technique cited in 12.4; no standard governs stream processing engines. This is a reference design to adapt, with illustrative numbers marked Example. Original text written for this collection; the cited papers and books were used as inspiration only and no text, figures or diagrams were copied. Check the current versions of the papers and of any engine you adopt. Template licence: MIT.

Plantillas relacionadas