Module 3 Β· Lecture 13

Apache Flink & True Streaming

Conceptual Β· Decision frameworks Β· No hands-on lab

⏱ 90 minutes πŸ“ Prerequisites: Lecture 12 (Spark) πŸŽ“ Approach: Conceptual β€” no installation required

Contents

  1. Learning Objectives
  2. Session Timeline
  3. Micro-Batch vs True Streaming
  4. Exactly-Once Processing
  5. Latency in Business Context
  6. The Complete Decision Framework
  7. Case Study: UPI Fraud Detection
  8. Group Debate
  9. Module 3 Summary
  10. Key Takeaways

Learning Objectives

Session Timeline

TimeSegmentActivity
0–10 minRecapL12 Spark β€” what is the micro-batch model in one sentence?
10–25 minThe Core DifferenceWhat true streaming actually means
25–40 minExactly-Once SemanticsWhy it exists, why banks care, why most don't need it
40–55 minLatency in Business ContextWhen does 200ms vs 10ms change the outcome?
55–70 minFull Decision FrameworkSpark vs Flink vs ksqlDB vs Python β€” the complete map
70–82 minCase Study: UPI FraudWalk through the real-time fraud architecture decision
82–88 minGroup Debate"Spark is good enough for everything" β€” argue for or against
88–90 minModule 3 Wrap-UpThe streaming landscape + preview of Module 4 (Grafana)

Section 1: Micro-Batch vs True Streaming

The Mental Model

Spark (micro-batch): Imagine a factory where a bell rings every 200 milliseconds. Workers grab everything in front of them, sort it, and send results forward β€” then wait for the next bell. The minimum time from arrival to processing: anywhere from 1ms (just after the bell) to 199ms (just before the next one).

Flink (true streaming): The same factory, but each worker processes an item the instant it arrives β€” no bell, no waiting. Processing time: 1–10 milliseconds from arrival.

Spark: β†’β†’β†’ [--200ms--] [--200ms--] [--200ms--]
                ↓            ↓            ↓
            run batch    run batch    run batch

Flink: β†’β†’β†’ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
           (each event processed individually, within ~10ms)

Why This Architecture Difference Exists

Spark was designed first as a batch processing system β€” streaming was added later as "fast batching." Flink was designed from day one as a streaming system β€” batch processing was added as a special case. Neither is "better" β€” they made different primary trade-offs.

Latency in Business Terms

LatencyRoughly Equivalent ToBusiness Example
1msBlink of an eye Γ· 300High-frequency trading signal
10msBlink of an eye Γ· 30Payment fraud check (Flink typical)
100msJust perceptible as a pauseUser feels slight lag
200msNoticeable delaySpark micro-batch typical
500msClearly slowGoogle reports this hurts search usage
2,000msVery slowUser considers abandoning the page

The key business question is not "what latency does Flink provide?" β€” it is "what latency does my use case require?" For 90% of business applications, anything under 2 seconds is fine. That is Spark's territory. Flink is needed for the remaining 10%.

Section 2: Exactly-Once Processing

The Three Processing Guarantees

GuaranteeRiskAcceptable ForNot Acceptable For
At-most-onceEvents may be lost on crashSocial media likes, page viewsFinancial transactions, medical records
At-least-onceEvents may be double-counted on crash/replayAnalytics approximations, event logsBilling, banking, inventory allocation
Exactly-onceNo loss, no duplication β€” guaranteedAll financial and compliance casesβ€”

Why Exactly-Once Is Hard

When a system crashes mid-processing, it must answer on recovery: "Did I already write this result to the database before I crashed?" Achieving exactly-once requires coordinating the database write AND the Kafka offset confirmation as a single atomic operation.

Who Actually Needs Exactly-Once

SectorUse CaseNeed Exactly-Once?Why
BankingTransaction processingYesDuplicate = double debit
E-commerceOrder revenue totalsYesBilling error = legal liability
TelecomCall data recordsYesOver/under billing customers
MarketingAd impression countingNo~1% error is acceptable
Social mediaLike/view countsNoApproximate is fine
LogisticsDelivery ETANoSmall error has no consequences

Practical reality: Most companies use at-least-once processing and manage the "duplicate" problem through idempotent writes β€” designing database operations so that processing the same event twice produces the same result as processing it once. This is simpler than exactly-once and works for most cases.

Spark vs Flink on Exactly-Once

Section 3: When Latency Actually Matters

Scenario A β€” Online Payment Fraud Detection

With Spark (~200ms fraud check): user taps "Pay" and experiences essentially zero perceptible delay. With Flink (~10ms): same user experience. Business verdict: Spark is fine.

Scenario B β€” Payment Gateway at Very High Throughput

At 50,000 TPS, if the fraud pipeline becomes a bottleneck (batch takes longer than its trigger interval), transactions start queuing. Flink's consistent per-event processing avoids this queuing effect under load. Business verdict: At very high volume, Flink's consistency matters more than raw latency.

Scenario C β€” Financial Market Trading Alert

A 200ms delay means a competitor has already acted on the same signal. Flink at 10ms is competitive. For high-frequency trading, even Flink is often "too slow" β€” those systems use custom hardware. Business verdict: Spark is not appropriate here.

Section 4: The Complete Decision Framework

DimensionPython ConsumerApache SparkksqlDBApache Flink
Latency< 100ms~200ms–2s~50ms< 10ms
Scale limit~1K events/secMillions/secHundreds K/secMillions/sec
Exactly-onceNoYes (batch)YesYes (per-event)
Infrastructure costNoneMedium–HighLowHigh
Talent costLowMediumLowVery High
Best forLearning, prototypesBatch + streaming teamsSQL-native teamsPayments, trading

Organisational Cost Comparison

FactorApache SparkApache Flink
Monthly infra costβ‚Ή30K–₹3L (Databricks/EMR)β‚Ή50K–₹5L (self-managed or Confluent)
Time to first production job2–4 weeks6–12 weeks
Hiring difficultyModerateVery Hard
Salary premium40–60% over general engineer80–120% over general engineer

Section 5: Case Study β€” UPI Fraud Detection

The Problem

NPCI processes ~5 billion UPI transactions/month (~1,900 TPS average, much higher at peak). Fraud must be detected and flagged before clearing: <300ms SLA.

Each transaction must be checked for:

  1. New device/account combination
  2. Unusual amount for this user's history
  3. Mule account pattern (many small transactions to same payee today)
  4. Location consistency with recent transactions
  5. Active fraud alert on beneficiary VPA

Architecture Options

OptionAssessment
Manual Python ConsumerSingle-threaded, ~1K events/sec. ❌ Cannot handle 1,900 TPS peak.
Apache Spark StreamingHandles 1,900 TPS across distributed cluster. Micro-batch 200ms β†’ within 300ms SLA. βœ… Scale sufficient, latency acceptable.
Apache Flink~10ms per-transaction latency. Stateful per-user history in-memory (no database roundtrip for checks 1–4). βœ… Better latency margin, better for stateful checks. Higher cost.

Discussion Questions

  1. The 300ms SLA: Spark processes in ~200ms, leaving 100ms buffer. Is that enough margin on peak days when transaction volume is 3Γ— normal?
  2. The stateful problem: Check 3 (mule account pattern) requires knowing all transactions to a payee in the last 24 hours. How do you query 24 hours of UPI history in <10ms?
  3. Build vs buy: Custom streaming fraud pipeline vs licensed SaaS (SAS, NICE Actimize, Featurespace). What are the trade-offs?

Group Debate: "Spark Is Good Enough for Everything"

Group A β€” Argue FOR

"Spark's micro-batch is sufficient for 95% of real business use cases. The additional complexity and cost of Flink is rarely justified."

Group B β€” Argue AGAINST

"As data volumes and latency expectations grow, Flink's true streaming model will become the standard. Companies that invest now will have a competitive advantage."

Time: 5 minutes to prepare arguments, 5 minutes of structured debate, 2 minutes for faculty summary.

Faculty debrief: Both positions have merit β€” context determines correctness. The question is always "what does the business need?" not "what's the best technology?"

Module 3 Summary

The Streaming Technology Landscape β€” Module 3

L11: WindowingL12: SparkL13: Flink
Core conceptSlicing infinite streams into measurable chunksDistributed micro-batch processingTrue per-event stream processing
What you builtconsumer_window.py (tumbling + sliding)Observed spark_consumer.py (demo)Conceptual understanding
Best forAny consumer needing time-based aggregationsLarge-scale batch+streaming, SQL teamsSub-100ms latency, financial exactly-once
Business skillChoose the right window typeKnow when to invest in distributed processingKnow when latency justifies the cost
Module 2: We made Kafka work β€” producers, consumers, MongoDB, alert routing
Module 3: We learned to aggregate intelligently (windows), and understand the
          frameworks that handle this at scale (Spark, Flink)

Module 4: We stop building backends and focus on the output β€” dashboards.
          All of this data you've been streaming? Now we make it visible.

Key Takeaways

βœ“ Key Takeaways β€” Lecture 13

  1. True streaming vs micro-batch: Flink processes each event immediately (<10ms); Spark batches every ~200ms. Neither is universally "better."
  2. Exactly-once matters for money β€” financial transactions, billing, and inventory allocation require it. Analytics and approximations do not.
  3. 200ms vs 10ms in business terms β€” Spark's latency is invisible to users for 90% of applications. Flink's advantage only materialises in high-frequency trading, payment auth under load, and real-time bidding.
  4. Decision order: Python consumer β†’ ksqlDB β†’ Spark β†’ Flink (increasing complexity, cost, and latency capability).
  5. Organisational cost is the real constraint β€” Flink engineers are rare and expensive. The best technical choice your team cannot operate is the wrong choice.
  6. Most companies use Spark. A small number β€” banks, payment networks, trading firms β€” need Flink. Know which kind of company you're in.

Preview β€” Module 4: Grafana Dashboards & Alerts

Starting Lecture 14, we shift from building pipelines to making them visible. You will use the same data you have been streaming in Module 2 (transactions, INFY/TCS prices) and turn it into dashboards a business manager can actually use.