Skip to main content

Stream and Batch Processing

1. Executive Summary​

Stream processing continuously transforms unbounded event streams with low latency; batch processing applies transformations to bounded datasets with high throughput and simpler fault tolerance. Modern data platforms rarely choose one exclusively—they implement unified engines (Apache Flink, Spark Structured Streaming) that expose similar APIs for both, while architectural patterns (Lambda, Kappa) describe how organizations combine speed and correctness layers.

Principal architects must reason about event time vs processing time, watermarks and late data, delivery semantics (at-most-once, at-least-once, exactly-once), and state management at scale. The interview-critical insight: exactly-once end-to-end requires cooperation between the processor, message broker, and sink—not a single checkbox in Flink configuration.

This chapter covers mechanisms, guarantees, failure modes, and production patterns for batch and stream pipelines powering analytics, fraud detection, and real-time features.

2. Why This Topic Matters​

Every principal data architecture interview touches processing semantics:

  • When stream vs batch? — Latency SLO, cost, correctness requirements.
  • How handle late events? — Watermarks, allowed lateness, retractions.
  • Exactly-once reality — Idempotent sinks, transactional commits, Kafka offsets.
  • Lambda vs Kappa — Operational burden vs simplicity.
  • Backpressure — What happens when sink slows.

Teams that confuse processing-time windows with event-time windows ship dashboards that drift from financial truth after outages or clock skew.

3. Problems Being Solved​

ProblemProcessing approach
Daily reports on TB datasetsBatch (Spark, Hive, SQL warehouse)
Real-time fraud scoringStream (Flink, Kafka Streams)
Near-real-time metricsMicro-batch or stream with short windows
Reprocessing historyBatch replay or Kappa re-read from log
Correct aggregations under disorderEvent-time + watermarks
Joining streams to reference dataBroadcast state, temporal joins, lookup tables

Workload fit matrix​

WorkloadBatchStreamHybrid
Monthly regulatory report✓
200 ms fraud alert✓
5-minute sales dashboard✓micro-batch OK
ML training on full history✓
Sessionization✓
Nightly dimension sync✓stream CDC optional

4. Assumptions and System Model​

AssumptionImplication
Events are immutable factsCorrections via compensating events or retractions
Clocks are not synchronizedUse event timestamps, not now() at processor
Brokers retain logsReplay enables recovery and Kappa reprocessing
State fits or spillsRocksDB/state backend sizing for Flink
Sinks may not be transactionalEnd-to-end exactly-once needs idempotent design

Safety: Correct aggregations within declared lateness bounds. Liveness: Progress requires consumer groups advancing; stuck watermarks block window closes.

5. Essential Terminology​

TermDefinition
Event timeTimestamp embedded in event payload
Processing timeWall clock when processor observes event
WatermarkLower bound on unseen event times in stream
WindowBounded slice for aggregation (tumbling, sliding, session)
Allowed latenessGrace period after watermark for late events
CheckpointFlink periodic consistent snapshot of state + offsets
Micro-batchSpark Streaming divides stream into small batch jobs
Side outputRoute late or invalid records to separate stream
RetractionUpdate prior emission when late data changes result
Changelog streamTable represented as insert/update/delete events

6. Core Mechanism​

6.1 Lambda architecture (historical pattern)​

Figure 1: Lambda maintains separate speed (approximate) and batch (correct) paths merged at query time—high operational cost.

6.2 Unified stream processing​

Figure 2: Single engine with durable log, checkpointed state, and transactional or idempotent sink.

6.3 Event-time windows and watermarks​

Figure 3: Watermark advances with observed event times; late events handled per allowed lateness policy.

7. Step-by-Step Walkthrough​

Walkthrough A: Spark batch ETL​

  1. Airflow triggers nightly Spark job reading partitioned Parquet in lake.
  2. Transformations: join dimensions, aggregate daily revenue per region.
  3. Output written to gold table with partition report_date.
  4. Job commits table snapshot; downstream BI refreshes semantic layer.
  5. Failure mid-write: rerun job; idempotent overwrite on partition.
  1. Job consumes payments topic with event timestamp payment_ts.
  2. Assign watermarks: max_event_time - 5 seconds bounded out-of-orderness.
  3. Tumbling 1-minute windows count transactions per merchant.
  4. Checkpoint every 60s to S3; Kafka offsets stored in checkpoint.
  5. Sink writes upserts to JDBC with primary key (merchant_id, window_end).

Walkthrough C: End-to-end exactly-once (conceptual)​

  1. Flink uses Kafka transactional producer per checkpoint epoch.
  2. Two-phase commit sink (e.g., JDBC XA or Iceberg commit) participates in checkpoint.
  3. On failure, restart from last completed checkpoint; uncommitted epoch aborted.
  4. Safety: no duplicate visible records. Cost: latency tied to checkpoint interval.

Walkthrough D: Kappa reprocessing​

  1. Bug in aggregation logic discovered; fix deployed.
  2. Reset consumer offset to T0 or deploy new application version reading compacted topic from beginning.
  3. Rebuild materialized view from immutable log—batch layer unnecessary.
  4. Requires sufficient Kafka retention or tiered storage archive.
  1. CREATE TABLE orders with Kafka source and upsert-kafka sink to compacted topic.
  2. Changelog semantics: +I, -U, +U row kinds from CDC source.
  3. Primary key defined on order_id; state backend stores latest row per key.
  4. Checkpoint aligns Kafka consumer offset with sink transactional write.
  5. Downstream batch job reads compacted topic as silver input—unified log contract.

Walkthrough F: Backpressure during Black Friday spike​

  1. Traffic 8× baseline; Flink operator busyTimeMsPerSecond hits ceiling.
  2. Kafka consumer lag grows; autoscaler adds task managers (if configured).
  3. Gateway applies admission control on non-critical stream consumers.
  4. Batch reconciliation job runs hourly comparing stream aggregates to warehouse truth.
  5. Post-event review tunes parallelism, checkpoint interval, and max lag SLO.

Engine selection matrix (principal decision aid)​

CriterionPrefer FlinkPrefer Spark
Sub-second event-time windows✓
Nightly 50 TB batch✓
Complex CEP patterns✓
Team skill: SQL batch only✓
Exactly-once to Iceberg sink✓ (connector maturity varies)✓
ML feature batch + stream unity✓ (Structured Streaming)

Document the choice in an ADR; revisit when latency SLO tightens or team skills shift.

8. Invariants and Guarantees​

SemanticGuarantee
At-most-onceNo duplicates; may lose messages
At-least-onceNo loss; duplicates possible without dedup
Exactly-once (processor)Checkpoint aligns state and source offsets
Exactly-once (end-to-end)Requires transactional/idempotent sink

Window correctness: Holds only if event timestamps trustworthy and lateness policy matches business rules.

9. Failure Scenarios​

FailureBehaviorMitigation
Task manager crashRestart from checkpointHA Kafka; adequate checkpoint storage
Checkpoint timeoutBackpressure; lag growsScale parallelism; tune interval
Watermark stuckWindows never closeIdle source watermark; processing-time fallback
State backend corruptionJob cannot restoreRemote checkpoints; backup strategy
Sink partial writeDuplicates on retryIdempotent keys; transactional sink
Skewed keyHot task bottleneckKey salting; custom partitioner
Broker outageConsumer pauseMulti-AZ cluster; mirror topics

Scenario narrative​

During network partition, Flink job falls behind; watermarks lag real time. Dashboard shows stale 1-minute counts while batch nightly job still correct. Operations must define which layer is source of truth per metric and alert on stream lag separately from batch SLA.

10. Performance Characteristics​

DimensionBatchStream
LatencyMinutes–hoursSub-second to minutes
ThroughputVery high per dollarHigh with tuning
Fault toleranceRecompute partitionCheckpoint restore
State accessShuffle joins costlyLocal keyed state fast
Operational complexityLowerHigher (watermarks, state)

Micro-batch (Spark) trades latency for simpler fault model—often 100ms–seconds, not true sub-100ms.

11. Scalability Limits​

  • Keyed state size per operator—must fit RocksDB + memory or use external store.
  • Kafka partition count bounds consumer parallelism.
  • Shuffle-heavy joins on infinite streams require careful state TTL.
  • Checkpoint duration must stay << interval at scale.
  • Global windows without bounds—unbounded state; prohibited pattern.

12. Operational Considerations​

  • Monitor consumer lag, checkpoint duration, backpressure ratio, late event rate.
  • Version savepoints before incompatible state schema changes.
  • Document event-time field contract with producers; reject missing timestamps.
  • Run chaos tests: kill task managers during peak load.
  • Separate dev/staging topics; never test against production consumer groups.
  • Align retention with reprocessing window for Kappa.

13. Security Considerations​

  • ACLs on Kafka topics per pipeline service account.
  • Encrypt data in transit (TLS) and at rest on state/checkpoint storage.
  • PII handling in stream—mask before wide replication.
  • Secrets for sink credentials via vault, not job configs in git.

14. Cost Considerations​

  • Always-on Flink cluster vs scheduled Spark—stream costs continuous compute.
  • Kafka retention for reprocessing—storage grows with retention × throughput.
  • Checkpoint storage I/O on S3/GCS.
  • Over-provisioned parallelism wastes vCPU; right-size with autoscaler where supported.

Extended failure scenario: Kafka broker rolling restart​

During a planned Kafka broker restart, partition leaders migrate. Flink jobs with aligned checkpoint mode may pause checkpoint barriers until all operators acknowledge the new leader—checkpoint duration spikes from 30s to 4 minutes. Consumer lag appears healthy while checkpoint age breaches SLO. Mitigation: use unaligned checkpoints where supported, increase checkpoint.timeout, schedule broker maintenance during low-traffic windows, and alert on lastCheckpointDuration not just lag. Principal architects document this interaction in runbooks—streaming teams and Kafka admins often operate in silos until an incident connects them.

State backend sizing worked example (illustrative)​

A sessionization job keyed by user_id with 24-hour session window retains ~50 million keys at peak. At 200 bytes per key state entry, RocksDB state ≈ 10 GB plus overhead—fits single task manager with 16 GB heap. At 10× traffic, state grows linearly unless TTL evicts idle sessions. Architecture review should mandate state TTL and managed RocksDB memory before production promotion. Embarrassingly parallel jobs without keyed state scale more predictably than session windows at billion-user scale.

Batch vs stream organizational boundary​

Principal architects often mediate between data engineering (batch-first) and real-time engineering (stream-first) teams. A durable agreement: batch owns authoritative financial reconciliation; stream owns operational alerting and near-real-time features; disputes escalate via shared metric catalog with explicit source_of_truth tags. Without this, executives receive conflicting dashboards and teams optimize locally. Platform standards should include a messaging contract template mandating delivery semantics, schema registry linkage, and DLQ policy for every new topic.

15. Production Implementations​

Case study: Real-time fraud + daily reconciliation (illustrative)​

Business context​

Payment processor needs <500ms fraud scoring and daily audited totals matching ledger.

Architecture​

Flink job: event-time windows, rules + ML model via async I/O. Gold fraud decisions to Kafka decisions. Nightly Spark reconciles stream aggregates vs warehouse ledger; mismatch alerts.

Semantics​

Stream: at-least-once to external API with idempotency keys. Warehouse sink: exactly-once via Iceberg two-phase commit on checkpoint.

Tradeoffs​

ChoiceTradeoff
Flink over Spark StreamingLower latency vs team familiarity
5s watermark boundAccuracy vs window close delay
Separate reconciliationOps burden vs trusting stream alone

Interview lessons​

Never claim exactly-once without naming sink cooperation; separate real-time approximate from batch authoritative when required.

16. Alternatives and Tradeoffs​

PatternProsCons
Pure batchSimple, cheapHigh latency
Pure stream (Kappa)Single pathReplay cost; stream complexity
LambdaSpeed + accuracyDual pipelines; merge bugs
Micro-batchMiddle groundNot lowest latency
Materialized CDCDB → stream without app changesTransformation lag

17. Common Misconceptions​

MisconceptionReality
"Flink exactly-once = end-to-end"Sink must participate
"Processing time is good enough"Out-of-order breaks correctness
"More partitions always faster"Overhead; ordering per key
"Kappa eliminates batch"Historical replay is batch-like
"Windows close at wall clock"Close on watermark in event time

18. Principal Architect Perspective​

  1. Define delivery semantics per sink, not per platform slogan.
  2. Contract event timestamps at producer boundary.
  3. Prefer Kappa when log retention and team skill support it; avoid Lambda unless justified.
  4. Instrument lag and watermark age as first-class SLIs.
  5. Reconciliation jobs remain valuable for money-moving systems.

Operating playbook (first 90 days)​

Days 1–30: Inventory all production topics and jobs; tag each with delivery semantic (at-most/at-least/exactly-once) and source_of_truth flag for downstream metrics. Deploy OpenLineage or equivalent on top three revenue-impacting pipelines first.

Days 31–60: Establish watermark and allowed-lateness policies per stream; document in data contracts. Run chaos test: kill Flink task manager during peak; measure recovery time vs SLO.

Days 61–90: Eliminate duplicate Lambda paths where Kappa replay is viable; or formalize reconciliation SQL with alerting threshold. Present FinOps report: streaming always-on cost vs batch savings realized.

Principal architects use this playbook to show operational maturity, not just diagram fluency.

19. Architecture Review Exercise​

Scenario: Team uses processingTime windows for billing aggregates because "it's simpler."

Findings: Replay after outage double-counts or mis-assigns periods. Mandate event-time, idle watermarks, reconciliation batch, documented allowed lateness.

20. Whiteboard Explanation​

"Batch processing reads a bounded dataset—tonight's partition—and recomputes outputs idempotently. Stream processing treats Kafka as an append-only log, maintaining keyed state and advancing watermarks from event timestamps to know when a time window is complete. Flink checkpoints snapshot operator state and Kafka offsets together so restart is consistent. Exactly-once to a database requires the sink to commit in the same transaction boundary as the checkpoint, or use idempotent upserts. Lambda ran fast and slow paths; most teams now prefer one log and one engine with replay for corrections."

Principal addendum: Draw delivery semantics as a chain: source → processor → sink. Weakest link defines end-to-end guarantee. Interviewers reward naming the sink explicitly—JDBC, Iceberg, HTTP API each differ. Mention reconciliation for money: stream for speed, batch for audit truth.

21. Interview Questions​

  1. Event time vs processing time? — Payload timestamp vs observation time.
  2. What is a watermark? — Progress marker for event-time completeness.
  3. At-least-once vs exactly-once? — Duplicates vs coordinated commit.
  4. Lambda vs Kappa? — Dual path vs single log reprocessing.
  5. Flink checkpoint purpose? — Fault-tolerant consistent snapshot.
  6. Spark Structured Streaming model? — Micro-batch or continuous processing.
  7. Handle late data? — Allowed lateness, side outputs, retractions.
  8. Stateful operator example? — Sessionization, running aggregate.
  9. Backpressure? — Slow sink propagates pressure upstream.
  10. When prefer batch? — High latency tolerance, huge historical scans.
  11. Kafka partition ordering guarantee? — Per-partition order only.
  12. Idempotent sink pattern? — Primary key upsert with deterministic ID.
  13. Session window? — Gap-based dynamic windows.
  14. Reconciliation need? — Financial correctness independent of stream SLI.

Scoring rubric (principal)​

DimensionStrongWeak
SemanticsEnd-to-end sink discussion"Exactly-once enabled"
Time modelWatermarks + latenessProcessing time only
OpsCheckpoints, lag, savepointsIgnores failure
PatternsKappa tradeoffsBuzzwords only

22. Interview Follow-Ups​

  1. Design clickstream aggregation with 1% events 10 min late. — Watermark bound + allowed lateness + side output to correction topic.
  2. Checkpoint interval tradeoff. — Smaller = less replay, more overhead.
  3. Join stream to slowly changing dimension. — Temporal table join or broadcast with versioning.
  4. Prove at-least-once produces duplicates. — Retry after sink success before offset commit.
  5. Scale Flink job 10x. — Increase partitions, parallelism, state backend capacity.

Additional principal scenarios​

Scenario: CFO asks whether stream processing can replace month-end batch close. Answer: Only if you prove byte-for-byte reconciliation over full history, document watermark/lateness bounds for every revenue metric, and accept always-on compute cost. Most regulated orgs keep batch authoritative with stream for operational visibility.

Scenario: Team proposes Flink on every microservice. Answer: Use streams for event backbone and derived views, not per-service stateful Flink unless latency requires it. Operational burden scales with job count.

Scenario: Exactly-once checkbox enabled but HTTP sink duplicates on retry. Answer: Name the gap—sink is at-least-once; add idempotency keys or transactional sink; update architecture diagram weakest-link annotation.

Principal architects should diagram the delivery semantic chain on every architecture review whiteboard—source, processor, sink—with explicit weakest link labeled.

22A. Production Low-Level Design (Interview + Game Day)​

Kafka → Flink → Iceberg pipeline with checkpointed exactly-once. Production LLD and Game Day Standard.

Control vs data plane​

PlaneComponents
ControlFlink JobManager, checkpoint coordinator, savepoint store, schema registry
DataKafka partitions, TaskManagers, state backend, transactional sinks

Step-by-step EOS path:

StepActionSemantic
1Aligned checkpoint barriersConsistent operator state
2Offsets stored in checkpointRestart from consistent point
3Kafka transactional producer epochAbort incomplete txn on failure
4Iceberg two-phase commit sinkVisible only after checkpoint
5HTTP sink (if any)At-least-once + idempotency keys

Pipeline contract​

FieldValue
Checkpoint interval60s (EOS visibility vs overhead)
Parallelism= Kafka partition count (scale unit)
Watermarkevent-time + allowed lateness 10m
Weakest linkDocument per sink

One SLO​

Stream lag: consumer lag p99 < 30s; checkpoint duration p99 < 30s; failed checkpoint alert within 1 interval.


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1TaskManager OOMKill TM mid-checkpointCheckpoint failed metricScale memory; reduce stateCheckpoint succeeds next interval
GD-2Late event floodReplay 10m late eventsSide output volume spikeTune allowed latenessGold metrics within SLA
GD-3Sink duplicate on retryHTTP sink without idempotencyDuplicate rows in DBAdd idempotency keysReconciliation passes

GD-1 — Checkpoint failure loop​

23. Strong Answer Example​

Question: "How do you achieve exactly-once processing with Kafka and Flink?"

Answer this as a 45-minute greenfield design using the PRACTICE framework. Below is how a strong student sounds aloud—separate pipeline EOS from end-to-end EOS, then name the sink as the weakest link.

PRACTICE interview answer map for exactly-once Kafka and Flink

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"We need exactly-once so failures and restarts don't double-apply business effects—fraud scores, ledger updates, order counts. Kafka alone is typically at-least-once to consumers; Flink's 'exactly-once' checkbox is not end-to-end by itself.

I'll design Kafka → Flink → sink and be explicit: exactly-once inside the Flink pipeline via checkpoints, and end-to-end only if the sink participates in the same commit epoch—or we use idempotent upserts.

Non-goals for v1: at-most-once fire-and-forget, and claiming EOS to a raw HTTP API without keys."

R — Requirements​

TypeRequirement
FRConsume Kafka, stateful transforms (windows/keyed state), write results downstream
NFRAfter crash/restart, no duplicate visible effects for EOS sinks; lag within SLO
SemanticsDocument pipeline EOS vs end-to-end EOS per sink
OpsCheckpoint duration/age alerts; savepoints for upgrades; reconciliation for money

"I'll ask: sink is Kafka, Iceberg/JDBC, or external HTTP? Monetary? I'll assume Kafka out + one DB/lake sink, and call out HTTP as at-least-once + idempotency."

A — Assumptions (state aloud)​

AssumptionWhy it matters
Flink checkpointing enabled (aligned or unaligned)Consistent state + offset snapshot
Kafka source offsets stored in the checkpointRestart replays from consistent point
Kafka transactional producer / 2PC sink for Kafka→KafkaEpoch commit/abort
Sink may not be transactionalThen EOS is effective via idempotency, not true 2PC
Checkpoint interval trades latency vs recoveryVisible EOS latency ≈ interval for transactional sinks

"If they say 'enable exactly-once in Flink and Kafka guarantees no duplicates,' I'd correct: broker ≠ application EOS; sink decides."

C — Capacity (back-of-envelope)​

Input rate (say) → 50K events/sec
Checkpoint interval → 30–60s (EOS visibility / commit cadence)
Checkpoint timeout → must exceed barrier alignment under load
State size → keyed state + timers; RocksDB on local SSD
Checkpoint storage → S3; duration grows with state + backpressure
Kafka partitions → bound parallelism (= consumer instances)
Consumer lag SLO → e.g. p99 lag < 30s; checkpoint age separate alert
Failure recovery → restore last complete checkpoint; abort uncommitted epoch

"I'd size for checkpoint duration under peak, not just lag—broker restarts can spike barrier alignment time."

T — Topology (draw this)​

Exactly-once topology Kafka Flink sink chain

Figure B: Kafka source → Flink (state + checkpoints) → transactional/idempotent sink; weakest link labeled when sink can't 2PC.

Two layers of "exactly-once" (say aloud):

LayerWhat it meansMechanism
Pipeline / Flink EOSOperators don't double-apply state after restoreCheckpoint barriers; state + Kafka offsets snapshotted together
End-to-end EOSDownstream never shows duplicates from retriesSink pre-commit / commit with checkpoint epoch, or deterministic idempotent writes

Flink checkpoint two-phase commit epoch

Figure C: Barrier → snapshot state+offsets → sink pre-commit → commit on success; failure aborts epoch and restores last complete checkpoint.

Protocol I'd walk on the whiteboard:

  1. JobManager injects checkpoint barrier into streams.
  2. Operators align (or unaligned mode), flush state to checkpoint storage.
  3. Snapshot includes Kafka consumer offsets for this epoch.
  4. Sink pre-commits transactional writes (Kafka TX producer, Iceberg commit, JDBC XA, …).
  5. Checkpoint completes → sink commits epoch → effects become visible.
  6. Crash before commit → restart from last complete checkpoint; abort uncommitted epoch → no duplicate visible records.

I — Invariants (safety)​

"Non-negotiable:

  1. Offsets and state restore together—never commit Kafka offsets ahead of state.
  2. Uncommitted sink epochs abort on recovery—no partial publish.
  3. Idempotent business keys when sink can't do 2PC (order_id upsert, deterministic doc IDs).
  4. Per-partition Kafka order only—don't assume global order across keys.
  5. Name the weakest link on the architecture diagram every time."

C — Constraints (second C)​

ConstraintDesign response
HTTP / webhook sinkAt-least-once + idempotency keys; not true EOS
Checkpoint interval vs latencySmaller interval → lower EOS lag, more overhead
Aligned checkpoints + Kafka rebalanceDuration spikes; unaligned / tune timeout; maintenance windows
Kafka enable.idempotence aloneProducer EOS ≠ consumer/Flink/sink EOS
Money / ledgersStream approximate + batch reconciliation as authority
Upsert-kafka compacted topicsEffective EOS for keyed tables; understand compaction

E — Evolution (prove + harden)​

Phased delivery:

PhaseDeliverable
M1Flink + Kafka source; checkpointing; at-least-once sink with metrics
M2EOS mode + Kafka transactional sink (or Iceberg 2PC) for critical path
M3Idempotent path for non-TX sinks; document semantic per topic
M4Lag + checkpoint duration/age SLOs; savepoint upgrade runbook
M5Nightly reconciliation vs warehouse for monetary aggregates

Failure modes I'd mention:

FailureMitigation
TaskManager crashRestore last complete checkpoint; abort open TX epoch
Sink commit fails after pre-commitEpoch abort; retry from checkpoint
Duplicate HTTP postsIdempotency-Key / upsert; never claim EOS
Checkpoint too slowBackpressure, state tuning, unaligned checkpoints
"EOS enabled" but wrong sinkArchitecture review: label weakest link

Observability: checkpoint_duration, checkpoint_age, consumer lag, sink commit failures, duplicate rate (where measurable), reconciliation diffs.


Closing line (interview)​

"So: Flink checkpoints give exactly-once inside the pipeline by snapshotting operator state + Kafka offsets together. End-to-end needs the sink in the same 2PC epoch—Kafka transactional producer, Iceberg, JDBC XA—or idempotent upserts if it can't. I never say 'Flink exactly-once' without naming the sink. For money, I still run batch reconciliation."

Scoring signals​

StrongWeak / red flag
Pipeline EOS vs end-to-end EOS"Turn on exactly-once in config"
Checkpoint = state + offsetsIgnores offsets / state coupling
Sink 2PC or idempotency"Kafka guarantees no duplicates"
Abort uncommitted epoch on failureAssumes retries are always safe
Weakest-link calloutNo sink discussion
Reconciliation for ledgersBlind trust in stream totals

Compact outline (if time-boxed to 2 minutes)​

"Flink EOS: checkpoint barriers snapshot state + Kafka offsets. Sink must join the epoch—Kafka TX / Iceberg / XA—or use idempotent upserts. Crash → restore last complete checkpoint, abort open epoch. HTTP sink = at-least-once + keys. Document weakest link; reconcile money in batch."

24. Weak Answer Example​

Question: "How do you achieve exactly-once processing with Kafka and Flink?"

"Enable exactly-once in Flink config and Kafka will guarantee no duplicates."

Why weak / red flags: No checkpoint explanation, ignores the sink, conflates broker producer idempotence with end-to-end application semantics.

25. Hands-On Exercise​

  1. Run Kafka + Flink local; count events per key with event-time windows.
  2. Inject out-of-order events; observe watermark behavior.
  3. Kill task manager; verify recovery from checkpoint.
  4. Compare Spark batch vs Structured Streaming on same topic.
  5. Implement idempotent sink with duplicate inserts.

26. Knowledge Check​

  1. Watermark indicates? (Lower bound on future event times.)
  2. Lambda speed layer role? (Low-latency approximate views.)
  3. Checkpoint contains? (State + source offsets.)
  4. Tumbling window? (Fixed non-overlapping intervals.)
  5. Kappa core idea? (Reprocess log for corrections.)
  6. Backpressure cause? (Downstream slower than upstream.)
  7. Event-time requires? (Trustworthy timestamps in payload.)
  8. At-least-once fix for duplicates? (Idempotent sink.)
  9. Session window defined by? (Inactivity gap.)
  10. Micro-batch engine example? (Spark Structured Streaming.)

27. Flashcards​

FrontBack
Event timeTimestamp in event data
WatermarkEvent-time progress marker
CheckpointFlink consistent state snapshot
Lambda architectureSeparate speed and batch layers
Kappa architectureSingle stream log reprocessing
At-least-onceNo loss; possible duplicates
Exactly-onceCoordinated commit; no duplicates
Allowed latenessGrace for late events
BackpressureFlow control when sink slows
Micro-batchStream as small batch jobs

28. Cheat Sheet​

TIME
Event time + watermarks + allowed lateness

SEMANTICS
At-most / at-least / exactly-once (sink matters!)

ENGINES
Batch: Spark | Stream: Flink, Kafka Streams

PATTERNS
Lambda (dual) | Kappa (replay log) | Hybrid reconciliation

OPS
Lag, checkpoint duration, savepoints, skew

30. References​

Primary sources​

  • Kreps, J. (2014). Questioning the Lambda Architecture. Confluent blog.
  • Carbone, P., et al. (2015). Apache Flink: Stream and Batch Processing in a Single Engine. IEEE Data Eng. Bull.
  • Apache Flink documentation — checkpoints, watermarks, state backends.
  • Kleppmann, M. DDIA — Ch. 11 Stream Processing.
  • Zaharia, M., et al. — Spark Structured Streaming papers and docs.

Distinction​

ClaimType
Checkpoint protocolFlink implementation spec
End-to-end exactly-onceRequires sink—formal in Flink docs per connector
Lambda operational costEngineering experience—anecdotal