
Near Real-Time Data Pipelines on AWS: Building a Kappa Architecture with Kinesis and Spark Structured Streaming
Most teams reach for streaming before they've confirmed they actually need it. This article is for when the answer is genuinely under 5 minutes. It's a full AWS walkthrough of Kappa Architecture: one unified streaming pipeline using Kinesis Data Streams, Spark Structured Streaming on EMR, and Delta Lake on S3. Covers the three-job chain, checkpointing, watermark placement, why Glue doesn't work at Gold, and the operational concerns most streaming articles skip.
Somewhere along the way, "real-time" became the default answer to every data problem.
Need faster dashboards? Real-time. Need better alerting? Real-time. Need to impress someone in a design review? Real-time.
But real-time streaming is not free. It's always-on compute, continuous operational overhead, three jobs running simultaneously instead of one scheduled batch. It's a race car, and sometimes you genuinely need a race car. But sometimes you really, really don't.
This article is about the cases where you actually do.
When the latency requirement is under 5 minutes (live operational dashboards, near-real-time clinical alerts, data that needs to be visible within minutes of an event), batch doesn't cut it. And the architecture that fits isn't Lambda with two parallel pipelines and double the complexity. It's Kappa: one unified streaming pipeline that handles everything.
On AWS, that means Kinesis Data Streams, Spark Structured Streaming on EMR, and Delta Lake on S3 working together in a three-job chain from source to serving layer.
Let me walk you through every decision, every trade-off, and the things about building this on AWS that most articles skip entirely.
What Is a Kappa Architecture, and Why Does It Matter?
You've probably heard of Lambda Architecture: two parallel pipelines, a fast "hot" path for speed and a slow "cold" batch path for correctness, both running simultaneously.
Kappa is the simpler, bolder answer to the same problem:
What if we just built one really good streaming pipeline and used it for everything?
Think of it like this. Lambda Architecture is like running two separate postal services: one fast courier for urgent deliveries and one regular mail service for everything else. You need to manage both, coordinate between them, and reconcile when they disagree.
Kappa Architecture is like building one postal service that's fast enough to handle everything. One pipeline, one set of jobs to monitor, one source of truth.
The tradeoff? Building one pipeline that's fast enough AND correct is genuinely harder. But when you get it right, the operational simplicity is worth it.
On AWS, the three components that make this possible are:
- Amazon Kinesis Data Streams for the ingestion backbone
- Apache Spark Structured Streaming on EMR for the processing engine
- Delta Lake on S3 for the table format that handles concurrent streaming reads and writes safely
When Does This Architecture Apply?
Signal | What it tells you |
|---|---|
"Under 5 minutes" latency SLA | Batch is out. This is streaming territory |
"We need live operational dashboards" | Data refreshing every 30 seconds, not every 30 minutes |
"Near-real-time alerting" | Events need to trigger actions within minutes of occurring |
Experienced DE team | Streaming operations are significantly harder than batch. Team maturity matters |
Cost is secondary to freshness | Always-on streaming clusters cost more than scheduled batch jobs |
If the latency requirement is genuinely 15–60 minutes, incremental batch is the smarter call. Streaming triples operational complexity for a latency improvement you may not need. Confirm the real number before committing.
Why Kinesis Data Streams Instead of Firehose?
This is the first architectural decision and it's worth explaining carefully because the answer isn't obvious.
A common pattern for event ingestion on AWS is Kinesis Firehose: it buffers event streams and drops them to S3 automatically. For a 30–60 minute SLA, it's a great low-ops choice. But for near real-time?
Firehose imposes a minimum 60-second buffering window before it writes to S3. For a 5-minute SLA, that 60-second tax is unacceptable. You've used 20% of your entire latency budget just landing data before any processing starts.
Kinesis Data Streams gives you direct, real-time access to events. No buffering floor. Events are available to consumers within milliseconds of being written. That's the foundation for everything downstream.
Key Kinesis Data Streams properties that matter here:
Property | Value | Why it matters |
|---|---|---|
Throughput per shard | 1 MB/s inbound, 2 MB/s outbound | Size shards based on peak event throughput with headroom |
Retention window | 24 hours (extendable to 7 days) | Replay capability if a streaming job fails |
Ordering guarantee | Ordered within a shard | Events from the same source arrive in order |
Consumer model | Shared vs Enhanced Fan-Out (EFO) | EFO is for sub-second use cases; shared throughput is fine for Kappa |
Kinesis vs MSK (Kafka): The question I always get. For this architecture, Kinesis is the right call: fully managed, native AWS integration, no broker management. The trade-off is shard-based scaling is less flexible than Kafka partition rebalancing, and Kinesis has no support for complex fan-out to many independent consumers without Enhanced Fan-Out. If you needed the same stream consumed by ten different downstream services independently, MSK would be worth the operational overhead. For most AWS-native streaming architectures, Kinesis is the right choice.
The Three-Job Streaming Pipeline
This is what makes Kappa different from batch: instead of three scheduled jobs that run sequentially, we have three continuously running Spark Structured Streaming jobs chained together.
Kinesis Data Streams → Job 1: Streaming Bronze writer (30-second micro-batches) → Job 2: Streaming Silver transformer (reads Bronze Delta continuously) → Job 3: Streaming Gold aggregator (reads Silver Delta continuously) → Consumers: Athena, Redshift, SageMaker
Each job is always running. Each job reads from the output of the previous job via Delta Lake. Let's walk through each.
Job 1: Bronze, Continuous Writes with Checkpointing
Why EMR here instead of Firehose?
Firehose's 60-second buffering floor is too expensive for a 5-minute SLA. EMR + Spark Structured Streaming reads from Kinesis directly and gives us full control over the micro-batch trigger interval.
I set a 30-second micro-batch trigger. Regardless of how many events arrived in those 30 seconds (whether it's 100 or 100,000), Spark processes them as a batch and writes to Bronze Delta atomically. Sub-minute Bronze writes, every time.
Two things you absolutely must configure correctly:
1. Checkpointing to S3
This is the mechanism that gives streaming its reliability guarantee. Here's exactly how it works:
- Before processing each micro-batch, Spark records the Kinesis shard offsets (think of these as bookmark positions: "I've read up to sequence number X in shard 0, Y in shard 1") to a small metadata folder on S3
- Spark processes the batch and writes to Bronze Delta atomically
- Once the Delta write is confirmed, Spark marks that batch as complete in the checkpoint
If the EMR cluster crashes mid-batch, the new cluster reads the checkpoint, sees which batch was the last fully committed one, ignores any partial files from the failed batch, and asks Kinesis to resend from exactly where the last good batch ended.
Result: exactly-once delivery. No event processed twice. No event lost. Even across job restarts.
Think of it like a game save point. The checkpoint is the save. If the game crashes, you reload from the save and nothing is permanently lost.
2. Small file compaction in-memory
Kinesis events arrive as individual tiny records. Without compaction, Spark writes thousands of microscopic Parquet files to S3 every 30 seconds. That accumulates into performance-killing file count within days.
The fix: Spark coalesces events in memory before writing, producing optimally sized 128MB Parquet files to Bronze. Combined with Delta's Auto Optimize for background compaction, Bronze file counts stay healthy at scale.
One critical rule at Bronze: NO watermark here.
The Bronze job never drops events. Never. Bronze is the immutable audit trail. Everything that arrives, regardless of how late, lands in Bronze. Watermarks belong at Silver where streaming joins need memory management. More on this below.
Job 2: Silver, Streaming Joins and Watermarks for Late Data
Silver is where the Kappa architecture gets interesting, and where most streaming bugs live.
The same four transforms as batch Silver:
- Deduplication — composite key MERGE collapses duplicate records
- Schema enforcement — violations route to SQS dead-letter queue, never dropped silently
- PII masking — names, SSNs, dates of birth tokenized before any downstream consumer sees them
- Standardization — UTC timestamps, USD currency, internal facility codes
The key difference: this runs continuously, not on a schedule.
Job 2 listens to Bronze Delta using Spark's
readStream API. Every time new data lands in Bronze (every ~30 seconds from Job 1), Job 2 picks it up and processes it.This is where the watermark lives, and why.
To join a vitals event against a medication record across two Kinesis streams, Spark has to keep state in memory for every open join window.
Without a watermark, Spark never closes those windows. State grows unboundedly. The EMR cluster eventually runs out of memory and crashes.
The watermark solves this:
withWatermark("event_time", "10 minutes") tells Spark to close this join window after 10 minutes, and route any events that arrive after the window closes to the dead-letter queue. Events genuinely more than 10 minutes late miss the Silver streaming join but they're already safely in Bronze and can be reprocessed via a batch backfill job if needed.Setting the watermark correctly:
Look at the actual latency distribution of your source systems. If 99% of events arrive within 5 minutes of occurrence, a 10-minute watermark gives you correctness with minimal latency penalty. A 30-minute watermark gives you more accuracy but your "live" dashboard is 30 minutes stale. A 2-minute watermark is aggressive: fast dashboards but some legitimate late events get routed to dead-letter.
There's no universally right answer. Profile your sources first.
Delta MERGE at Silver:
MERGE INTO silver_table AS targetUSING new_micro_batch AS sourceON target.encounter_id = source.encounter_id AND target.facility_id = source.facility_idWHEN MATCHED THEN UPDATE SET *WHEN NOT MATCHED THEN INSERT *
Within the watermark window, slightly out-of-order events are handled cleanly. A late event that still arrives within 10 minutes updates the existing Silver record rather than creating a duplicate.
One important operational note on Delta MERGE in streaming:
MERGE is doing an atomic read-modify-write across potentially millions of rows. Under the hood, Delta rewrites only the affected data files, not the entire table. For high-throughput streaming, file write amplification at Silver is something to monitor closely. If MERGE is rewriting too many files per micro-batch, tune the target file size or batch smaller MERGEs into larger ones to reduce per-batch overhead.
Why not Glue for Silver?
Same reason as batch, plus one more: Spark Structured Streaming jobs need the Spark UI to debug backpressure, consumer lag, and watermark state accumulation. Glue hides all of this. For a continuously running streaming job at Silver, you want direct observability.
Job 3: Gold, Windowed Aggregations at 30-Second Cadence
Gold in a Kappa architecture refreshes on the same micro-batch cycle as Silver, every ~30 seconds for real-time use cases.
Important distinction: no streaming watermark at Gold.
Job 3 reads a bounded snapshot of Silver Delta and computes aggregations using SQL window functions over time ranges. It is NOT holding open streaming join windows in memory. The windows at Gold are SQL time range queries, not streaming state. No unbounded state accumulation, no OOM risk.
-- Per-minute rollups refreshed every 30 secondsSELECT facility_id, window(event_time, '1 minute') as time_window, COUNT(*) as event_count, AVG(processing_latency_ms) as avg_latencyFROM silver_deltaWHERE event_time >= current_timestamp - INTERVAL 1 HOURGROUP BY facility_id, window(event_time, '1 minute')
Two Gold tables, same as batch:
Real-time BI Gold — Pre-aggregated per-minute rollups. Refreshes every 30 seconds. Z-ordered on
event_time and facility_id for fast Athena queries. Feeds live operational dashboards.ML Gold — Patient-level feature tables with rolling aggregates. Refreshes hourly, not every 30 seconds. Model retraining doesn't need per-second freshness, and computing complex feature engineering every 30 seconds is expensive and unnecessary. Keep ML Gold on an hourly batch cadence even within a streaming architecture.
One mistake to avoid: putting too much logic in the Gold streaming job. Complex feature engineering running on every 30-second micro-batch creates backpressure that eventually causes the streaming job to fall behind the Kinesis shard. Keep Gold streaming transforms as simple as possible (aggregations only) and push expensive feature engineering to the hourly ML Gold batch job.
Why not a Glue job at Gold here?
In a batch or incremental architecture, Glue is perfect for Gold: predictable transforms, scheduled, pay-per-runtime. But Gold here needs to refresh every 30 seconds. You cannot schedule a Glue job every 30 seconds. The Gold compute in a Kappa architecture is therefore a continuously running Spark Structured Streaming job on EMR, not a Glue job. That's one of the key differences versus a batch Medallion setup.
Orchestration: What Airflow Does (and Doesn't Do) in a Kappa Pipeline
In a batch architecture, MWAA orchestrates everything: ingestion, Silver transforms, Gold jobs, all chained by DAG dependencies.
In Kappa, the streaming pipeline is self-sustaining. Once deployed, the three Spark Structured Streaming jobs run continuously without Airflow involvement. Job 2 automatically picks up new Bronze data. Job 3 automatically picks up new Silver data. No scheduler needed for the hot path.
What Airflow does in a Kappa pipeline:
- Schedules utility jobs — weekly OPTIMIZE and VACUUM on Bronze, Silver, and Gold Delta tables
- Schedules the hourly ML Gold batch job
- Monitors consumer lag via CloudWatch metrics and triggers alerts
- Handles GDPR deletion jobs and other compliance maintenance
Think of it like the difference between an air traffic controller (batch Airflow directs every flight) and a maintenance crew (streaming Airflow keeps the runway in good condition but the planes fly themselves).
Cross-Cutting Concerns Where Streaming Architectures Actually Break
1. Exactly-once semantics
Spark checkpointing + Delta's atomic writes = end-to-end exactly-once. An event is never processed twice and never lost, even across job restarts. This is non-negotiable in a healthcare data platform where duplicate records or missing events in clinical data has real consequences.
2. Consumer lag monitoring
Set a CloudWatch alarm on Kinesis consumer lag: the gap between the latest event in the stream and what Spark has processed.
- Lag = 0: streaming job is keeping up
- Lag growing: the streaming job is falling behind; add EMR capacity, reduce watermark window, or investigate a slow Silver MERGE
- Lag growing rapidly: something is broken, alert immediately
This is your most important operational metric in a streaming architecture. Check it before anything else when a streaming job behaves unexpectedly.
3. Dead-letter queue (SQS)
Unparseable or schema-invalid events route to an SQS dead-letter queue rather than crashing the streaming job. One malformed event from one hospital doesn't interrupt processing for 2,000 facilities.
Monitor dead-letter queue depth in CloudWatch. A spike means a source system changed its schema without telling you — the same early warning signal as batch, but you see it in near-real-time.
4. Checkpoint management
The checkpoint is what makes streaming safe. Two failure modes to protect against:
- Checkpoint corruption: keep a secondary backup checkpoint in a separate S3 path. If the primary is corrupted on restart, fall back to the backup and replay from the Kinesis retention window
- Schema evolution: if the Silver table schema changes between restarts, Spark may not be able to resume from the checkpoint. Version schemas carefully and test schema changes in a staging environment before production rollout
5. Security
Same controls as batch: IAM + Lake Formation for fine-grained access, KMS customer-managed keys for encryption at rest, TLS in transit. One addition for streaming — stream-level IAM policies on Kinesis. The Bronze Spark job gets read access to Kinesis. Nothing else does. Least privilege on the stream itself.
Disaster Recovery
Hot path recovery via Spark checkpointing:
If the EMR cluster goes down, the new cluster reads the S3 checkpoint and resumes from the last committed Kinesis offset. No data loss. No duplicates. RPO for the streaming path is effectively zero for events within the Kinesis retention window.
Replay window of 24 hours:
Kinesis retains events for 24 hours by default (extendable to 7 days at additional cost). If the streaming job is down for less than 24 hours, every missed event can be replayed by resetting the checkpoint to an earlier offset. For most operational scenarios, 24-hour retention is sufficient.
Cold recovery from Bronze on S3:
For anything older than the Kinesis retention window, Bronze is the recovery source. Bronze is the immutable audit trail. Everything that landed in Bronze can be reprocessed through Silver and Gold via a batch backfill job.
Recovery scenario | Approach |
|---|---|
Job crash, less than 24h downtime | Resume from S3 checkpoint. Kinesis replays missed events. Near-zero RPO |
Job crash, more than 24h downtime | Reprocess from Bronze via Airflow backfill DAG |
EMR cluster loss | Rebuild from IaC. New cluster reads checkpoint and resumes |
Sub-hour RTO | Pre-warm a standby EMR cluster in a secondary region. Validate cost with business first |
Store your EMR cluster configuration as Infrastructure as Code (CloudFormation or CDK). A cluster you can rebuild in minutes from code is categorically better than one you rebuild from memory at 2am.
Key Takeaways for AWS Builders
- Firehose vs Kinesis Data Streams — Firehose's 60-second buffering floor makes it the wrong choice for sub-5-minute SLAs. Use Kinesis Data Streams directly with Spark on EMR
- Checkpointing is the reliability contract — configure it carefully, back it up, test restart behavior before production. The checkpoint is what makes streaming safe
- No watermark at Bronze — Bronze is the immutable audit trail. Watermarks belong at Silver where streaming join state needs to be bounded
- Watermark = latency vs accuracy trade-off — profile your source latency distribution before setting the number. 10 minutes is a reasonable starting point for most event streams
- Gold in Kappa is a streaming job, not Glue — 30-second refresh cadence can't be scheduled. Three continuously running Spark jobs is the architecture
- ML Gold stays hourly — don't run complex feature engineering every 30 seconds. Keep streaming Gold simple; push expensive logic to the scheduled batch job
- Consumer lag is your most important metric — if it grows, something is wrong. Alert on it before anything else
- Dead-letter to SQS, not /dev/null — one bad event should never crash a pipeline serving 2,000 facilities
Final Thought
Kappa architecture gets less attention than Lambda. It's harder to explain in a soundbite. "One pipeline for everything" sounds simple but the implementation requires genuine depth: checkpointing, watermark tuning, streaming join state, file compaction at scale.
But when you get it right? You end up with a system that's operationally simpler than Lambda, easier to reason about, and fully capable of delivering sub-5-minute latency with correctness guarantees most batch systems can't match.
The key is knowing when it's the right tool. Not every use case justifies the complexity. But for live operational dashboards, near-real-time alerting, and continuous data delivery, this is the architecture worth understanding deeply.
If you're building something similar on AWS or have questions about any of the decisions here (Kinesis sizing, watermark tuning, checkpoint configuration), drop a comment. I'm always happy to go deeper.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article