High-Throughput Spark Streaming Deduplication at Scale
Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
An ad-tech telemetry service collects roughly 10 million click events per second from distributed edge collectors. Every incoming record carries four fields: event_id (a UUID), timestamp, user_id, and payload. Because client SDKs and edge collectors retry unacknowledged requests over flaky networks, the ingestion stream frequently contains multiple copies of the same event_id arriving at different wall-clock times.
Architect an Apache Spark Structured Streaming pipeline that removes duplicate records by event_id over a 24-hour retention horizon and lands deduplicated output into an Amazon S3 data lake. In addition to continuous live ingestion, operators periodically replay archived historical logs to repair past outages, and those backfills must not introduce duplicates alongside data already stored in production.
Scope & Expectations
- State sizing and scalable deduplication: Quantify the 24-hour key footprint at 10M events/second and specify how Spark state management, watermarks, partitioning, or external stores keep throughput sustainable without exhausting executor RAM.
- Out-of-window arrivals: Detail a concrete policy and reconciliation path for delayed events whose timestamps fall behind the active 24-hour deduplication cutoff.
- Prefix imbalance vs. hot keys: Analyze how skew in leading
event_idcharacters (as well as repeated identical keys) affects Kafka ingestion, Spark shuffles, and S3 storage layouts, and show how to mitigate true skew safely without breaking uniqueness. - End-to-end sink idempotency and historical replays: Explain how micro-batch retries avoid writing duplicate rows to S3, and how batch backfills merge into historical partitions cleanly without conflicting with live streaming writes.
Step-by-step walkthrough
Size the 24-hour state before picking a tool
Before choosing an architecture, multiply out the volume so the numbers tell us what fits in memory and what does not. Assuming most of the 10 million events per second are distinct clicks, one 24-hour window (
86,400seconds) contains up to:events per day 10,000,000 /s × 86,400 s = 8.64 × 10^11 (864 billion) raw 16-byte binary UUIDs 8.64 × 10^11 × 16 B ≈ 13.8 TB of raw keys raw 36-byte ASCII UUID strings 8.64 × 10^11 × 36 B ≈ 31.1 TB (2.25× larger) state store footprint (~64 B/key 8.64 × 10^11 × 64 B ≈ 55.3 TB across the cluster including timestamp & index overhead)Two design rules jump straight out of this arithmetic:
- Disk-backed partitioned state, not JVM RAM. Holding 55 TB of keys inside Java heap memory would require an absurdly expensive cluster and trigger constant garbage-collection pauses. The deduplication state must be split across thousands of partitions and stored on fast local SSDs (NVMe) with an in-memory cache.
- Convert UUID strings to 16-byte binary immediately. Parsing
"550e8400-e29b-41d4-a716-446655440000"into 16 raw bytes cuts key storage by more than half before anything hits the network shuffle or disk.
Can we shrink the keys further by storing a 64-bit hash or a Bloom filter (a compact bit array that tests set membership with zero false negatives, at the cost of occasional false positives where a brand-new item looks already seen)? Let us check the collision math. With
ndistinct keys mapped intob-bit hashes, there are aboutn² / 2pairs and each pair collides with probability1 / 2^b, givingn² / 2^(b+1)expected collisions:64-bit hash (b = 64): (8.64 × 10^11)^2 / 2^65 ≈ 20,200 colliding pairs/day 128-bit UUIDv4 (b = 122 (8.64 × 10^11)^2 / 2^123 ≈ 7.0 × 10^-14 collisions/day random bits):A 64-bit hash silently drops roughly 20,000 real ad clicks every day. A Bloom filter tuned to a 1% false-positive rate needs about
9.6bits per key (~1.04 TBof RAM) and falsely drops1%of unique events — up to 8.6 billion lost clicks per day — while also lacking a way to expire single keys as the 24-hour window slides. Keep the exact 16-byte (128-bit) binary ID.Deduplicate with an event-time watermark and RocksDB state
Here is the end-to-end streaming architecture:
Click Trackers │ (at-least-once retries; same event_id + event timestamp) ▼ Kafka ("clicks" topic, partitioned for 10M/s throughput) │ ├───────────────────────────────────────────────────────┐ │ (1) Main Structured Streaming job │ (2) Stateless archive / late-capture ▼ ▼ Parse + convert UUID to 16B binary Raw Bronze Table (append-only S3) Quarantine bad IDs & future timestamps (> now + 10m) + Late-Events Staging (> 23h old) │ │ ▼ shuffle by hash(event_id_bin, timestamp) │ RocksDB State Store (4,000 partitions, 24h watermark) │ daily / hourly anti-join MERGE │ │ ▼ atomic batch commit (idempotent transaction log) ▼ Delta Lake / Iceberg "clicks_clean" on S3 (partitioned by event_date)In Spark Structured Streaming, data is processed in small micro-batches (for example, one batch every 60 seconds).
dropDuplicatesremembers seen keys inside a state store partitioned across executors by key hash. Without a watermark — a moving event-time cutoff defined as(largest event timestamp seen so far) - (allowed delay)— Spark keeps every key forever until disk or RAM runs out.We assume
timestampis set by the source tracker when the click happens, so network retries of the same click carry the sameevent_idandtimestamp(only their arrival time differs):from pyspark.sql import functions as F # Store deduplication state on local NVMe SSDs via RocksDB instead of JVM heap, # and upload only incremental batch diffs (changelogs) to S3 checkpoints. spark.conf.set( "spark.sql.streaming.stateStore.providerClass", "org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider", ) spark.conf.set( "spark.sql.streaming.stateStore.rocksdb.changelogCheckpointing.enabled", "true", ) # Fixed for the lifetime of the checkpoint: 55 TB / 4,000 ≈ 14 GB per state partition. spark.conf.set("spark.sql.shuffle.partitions", "4000") events = ( spark.readStream.format("kafka") .option("kafka.bootstrap.servers", "broker-1:9092") .option("subscribe", "clicks") .option("minPartitions", "4000") # split wide Kafka partitions across Spark tasks .load() .select(F.from_json(F.col("value").cast("string"), EVENT_SCHEMA).alias("e")) .select("e.*") ) clean = ( events # Pack 36-char UUID string into 16 raw bytes; malformed IDs go to a quarantine sink. .withColumn("event_id_bin", F.unhex(F.regexp_replace("event_id", "-", ""))) .filter(F.length("event_id_bin") == 16) # Guard the watermark: one buggy device sending a year-2030 timestamp would jump # max_event_time forward and trick Spark into dropping today's real clicks as "late". .filter(F.col("timestamp") <= F.current_timestamp() + F.expr("INTERVAL 10 MINUTES")) .withWatermark("timestamp", "24 hours") .dropDuplicates(["event_id_bin", "timestamp"]) .withColumn("event_date", F.to_date("timestamp")) )Why each line is written this way:
- Why include
"timestamp"indropDuplicates(["event_id_bin", "timestamp"])? Classic SparkdropDuplicatesstores only the deduplication key columns in the state key and checks the watermark against the event-time column inside that key. Since retries share the original creationtimestamp, adding"timestamp"does not let duplicates slip through, and it lets Spark evict every entry as soon as the watermark passes itstimestamp. (If a source instead overwritestimestampon every retry, use Spark 3.5+'sdropDuplicatesWithinWatermark(["event_id_bin"]), which stores an explicit expiry timestamp in the state value.) - Why filter future timestamps instead of clamping them to
current_timestamp()? If you clamped a future-dated event to its arrival time, two retries arriving 3 seconds apart would receive different clamped timestamps and both passdropDuplicates(["event_id_bin", "timestamp"]). Route future-dated records to a quarantine table instead. - Why RocksDB + changelog checkpointing? RocksDB keeps the ~14 GB per-partition state on local SSDs with a bounded off-heap block cache. With 1-minute micro-batches,
6 × 10^8new keys at ~64 B generate ~38 GB/min (~640 MB/scluster-wide) of incremental changelog writes to S3 instead of re-uploading full multi-terabyte snapshots. - Why pick
4000shuffle partitions up front? Spark recordsspark.sql.shuffle.partitionsinside the streaming checkpoint on first start. Changing the config later is silently ignored on restart unless you start a brand-new checkpoint — which wipes the 24-hour state!
- Why include
Compare built-in state vs external stores (Redis or Cassandra)
A common instinct is to keep the 24-hour "seen IDs" set in Redis (
SET event_id 1 NX EX 86400) or Cassandra with a 24-hour TTL. Compare the options across cost, speed, and retry safety:Option 24h storage Per-event cost Behavior when a micro-batch fails & retries ---------------------------- ------------------- ----------------------- -------------------------------------------- Spark RocksDB state store ~55 TB local SSD 1 shuffle + SSD lookup Exact: state rolls back to prior batch version Redis with 24h TTL Tens of TB of RAM Network RPC (pipelined) TRAP: failed batch already marked IDs as seen Cassandra / Scylla with TTL Replicated SSDs Quorum / Paxos RPCs TRAP: same silent data loss unless batch-tagged 15m stream + hourly anti-join ~0.6 TB SSD + S3 Tiny stream + S3 scans Exact after hourly batch finishes (higher lag)Look closely at the external-store retry trap:
Attempt 1 of micro-batch #42: 1. Reads click E1 from Kafka 2. Writes "E1 -> seen" into Redis (succeeds!) 3. Executor crashes BEFORE writing E1 to S3 Retry of micro-batch #42 (same Kafka offsets, same batch_id = 42): 1. Re-reads click E1 from Kafka 2. Checks Redis -> "E1 is already seen!" -> drops E1 3. Commits empty output to S3 --> E1 IS PERMANENTLY LOST!Spark's built-in RocksDB state store avoids this automatically because every micro-batch reads state version
b - 1and commits state versionbatomically with the batch; a failed attempt discards its uncommitted writes. If you ever must use an external key-value store, deduplicate within the micro-batch first, storebatch_idas the value (SET id 42 NX EX 86400), and treat an existing value equal to the currentbatch_id(42) as "inserted by our own earlier attempt, so keep emitting it".Reconcile delayed records arriving behind the 24-hour cutoff
Once the watermark advances past an event's
timestamp(say the watermark is atNov 20 12:00and a delayed tracker uploads an event fromNov 19 10:00), Spark's deduplication operator drops that event because its 24-hour state entry may already have been evicted, and incrementsnumRowsDroppedByWatermarkin the query progress report. You have three ways to handle these late arrivals, depending on business requirements:- Drop, measure, and alert (when the 24h SLA is strict). If click trackers buffer for at most a few hours and events older than 24 hours are <0.001% noise, accept the drop and page on-call whenever
numRowsDroppedByWatermarkspikes. - Side-output capture + batch
MERGEreconciliation (recommended when late clicks are billable). Run a second, stateless streaming query on the same Kafka topic (with its own checkpoint) that captures every event wherecurrent_timestamp() > timestamp + INTERVAL 23 HOURSinto alate_eventsstaging table. The 1-hour overlap (23hinstead of24h) ensures nothing falls into the crack between the moving watermark and wall-clock time. A daily (or hourly) job deduplicateslate_eventsand inserts only IDs missing from the target dates:
MERGE INTO clicks_clean AS target USING late_events_deduped AS source ON target.event_date BETWEEN '2026-11-18' AND '2026-11-20' -- literal dates prune S3 partitions! AND target.event_date = source.event_date AND target.event_id_bin = source.event_id_bin WHEN NOT MATCHED THEN INSERT *Computing the literal
MIN(event_date)andMAX(event_date)fromlate_events_dedupedbefore runningMERGElets the query engine skip every unaffected date partition, and Z-ordering or sorting closed daily Parquet files byevent_id_binduring compaction lets file-level min/max statistics skip most files even within affected dates.- Tag instead of reconciling. Write late events with
is_late = trueinto a separate partition or column so real-time dashboards stay fast while billing queries deduplicate late partitions on read.
- Drop, measure, and alert (when the 24h SLA is strict). If click trackers buffer for at most a few hours and events older than 24 hours are <0.001% noise, accept the drop and page on-call whenever
Separate prefix skew from hot keys (and why naive salting fails)
What happens if 50% of all
event_ids start with the same prefix (for example"0000...", a publisher prefix, or time-based UUIDv7 prefixes)?In Spark's
dropDuplicatesshuffle, rows are routed by hashing the entire key (Murmur3Hash(event_id_bin) % 4000), not by slicing its prefix. Because changing even the last bit of a UUID scrambles its hash completely, popular prefixes spread evenly across Spark executors! We can verify this in 20 lines of Python by routing 100,000 UUIDs (half forced to start with"0000") across 16 buckets:import hashlib import random import uuid random.seed(7) ids = [] for i in range(100_000): raw_id = str(uuid.UUID(int=random.getrandbits(128), version=4)) if i % 2 == 0: raw_id = "0000" + raw_id[4:] # force 50% of IDs to share prefix "0000" ids.append(raw_id) by_prefix = [0] * 16 by_hash = [0] * 16 for event_id in ids: by_prefix[int(event_id[0], 16)] += 1 digest = hashlib.md5(event_id.encode("utf-8")).digest() by_hash[int.from_bytes(digest[:8], "big") % 16] += 1 # Mean load per bucket is 100,000 / 16 = 6,250: # max(by_prefix) == 53,105 (8.5x skew!), whereas max(by_hash) == 6,406 (within 2.5% of mean).So prefix skew only hurts places that do route by prefix or sort order: - Kafka partitions keyed by tracker/publisher prefix: mitigate with
.option("minPartitions", "4000")so Spark splits busy Kafka partitions across multiple reader tasks. - S3 directory paths: partition S3 byevent_date(and let table formats distribute file names), never byevent_idprefix.A true hot key, by contrast, is the exact same
event_idarriving millions of times (a retry storm, or a broken SDK sending"00000000-0000-0000-0000-000000000000"). Hashing sends every identical copy to one executor! First quarantine null, empty, and all-zero sentinel IDs before the shuffle. Second, watch out for the classic key-salting trap:WRONG (single-stage salting): copy 1 of E9 ─► salt=3 ─► key (E9, 3) ─► Executor 3 ─► emits E9 ┐ copy 2 of E9 ─► salt=11 ─► key (E9, 11)─► Executor 11─► emits E9 ┴─► BOTH SURVIVE (duplicate!) RIGHT (two-stage salting with S = 16 buckets): 10,000,000 copies of E9 ─► Stage 1 dedup on (event_id_bin, salt 0..15) ─► at most 16 copies survive (625k rows/executor instead of 10M!) ─► Stage 2 dedup on (event_id_bin) alone ─► exactly 1 copy survives!In code, valid salted deduplication always requires two stages:
salted = batch_df.withColumn("salt", (F.rand(seed=7) * 16).cast("int")) # Stage 1: spread hot duplicates across 16 tasks; at most 16 copies of any ID survive. partially_deduped = salted.dropDuplicates(["event_id_bin", "salt"]) # Stage 2: drop the salt and collapse the <= 16 survivors on the true ID. exact_deduped = partially_deduped.dropDuplicates(["event_id_bin"]).drop("salt")Note that in batch Spark jobs (backfills and late reconciliation), Spark's optimizer automatically inserts a map-side partial hash deduplication before the shuffle, collapsing hot duplicates locally with zero extra configuration. In streaming, adding a second stateful operator would double the 55 TB state store, so pre-shuffle validation + local in-micro-batch deduplication (
foreachBatchor map-side combine) is preferred over two stateful stores.Guarantee idempotent S3 commits across micro-batch retries
Idempotency means applying an operation twice leaves the exact same final data as applying it once. In Structured Streaming, Spark writes a micro-batch's Kafka offset range to its write-ahead offset log before running the batch, and records completion in its commit log after the sink finishes. If the driver crashes right after writing files to S3 but before writing the commit log, Spark replays the exact same micro-batch with the same
batch_idand same Kafka offsets.- Why plain S3 Parquet fails: If a failed attempt wrote
part-0001.parquettos3://lake/clicks_clean/and the retry writespart-0002.parquet, Spark readers consulting_spark_metadataknow which file won, but Presto/Trino/Athena/Snowflake scanning S3 keys see both files and double-count the whole micro-batch! - Solution — Open table format with transaction logs (Delta Lake or Apache Iceberg): Delta Lake's streaming sink embeds
(query_id, batch_id)inside an atomic transaction-log commit (_delta_log/000042.json). On a retry ofbatch_id = 42, Delta checks its log, seesbatch_id = 42is already committed, and skips the write completely:
query = ( clean.writeStream.format("delta") .partitionBy("event_date") .option("checkpointLocation", "s3://lake/_checkpoints/clicks_dedup") .trigger(processingTime="1 minute") .start("s3://lake/clicks_clean") )If you write custom logic inside
foreachBatch(df, batch_id), forwardbatch_idexplicitly using.option("txnAppId", query_id).option("txnVersion", batch_id)so Delta Lake still enforces exact batch-level idempotency.- Why plain S3 Parquet fails: If a failed attempt wrote
Replay historical archives safely alongside live production
Batch-ID idempotency prevents one streaming job from writing the same micro-batch twice, but a historical backfill is a different job reading raw archives — so
clicks_cleanalso needs content-level idempotency during backfills. Follow four rules:- Run as an isolated batch job (no shared checkpoint). Never point a backfill at the live streaming query's checkpoint.
- Stay strictly outside the live 48-hour boundary. Because the live stream's RocksDB state knows nothing about rows inserted directly into S3 by a backfill, backfilling today's date while the stream is also writing today could let the same
event_identer from both paths. Restrict backfills to closedevent_dates older thannow - 48 hours(well behind the 24-hour watermark). - Deduplicate the backfill input first using batch
dropDuplicates(["event_id_bin"])(cheap because Spark collapses duplicates map-side before shuffling). - Write with an insert-only
MERGE(or full-dayreplaceWherewhen rebuilding from complete bronze data):- If you are adding missing records from a recovered tracker log into existing production dates, use
MERGE INTO clicks_clean ... ON target.event_date IN (...) AND target.event_id_bin = source.event_id_bin WHEN NOT MATCHED THEN INSERT *. - If you are recomputing an entire closed day from a complete raw bronze archive, overwrite that exact partition atomically (
option("replaceWhere", "event_date = '2026-11-10'")).
- If you are adding missing records from a recovered tracker log into existing production dates, use
Worked numeric check: Suppose one day (
2026-11-10) lost 1% of traffic from one regional collector, and we replay all8.64 × 10^11raw events for2026-11-10. BatchdropDuplicatesproduces the unique IDs for that day; the partition-scopedMERGEscans only2026-11-10's~13.8 TBof binary IDs (leaving the live stream's current date partition untouched with zero lock conflict), inserts only the missing1%(~8.64 × 10^9rows), and if someone accidentally triggers the same backfill job a second time,WHEN NOT MATCHEDmatches 0 rows and inserts0duplicates.
Intuition & how it works
Imagine managing entry at a giant festival with 4,000 turnstiles scanning 10 million digital wristbands per second. Because mobile networks drop packets, a guest's phone often submits the exact same wristband ID (event_id) two or three times. You cannot hand every gatekeeper a paper list of all 864 billion wristbands scanned today, so instead you route each wristband by the mathematical hash of its ID (a deterministic function that scrambles an ID into a bucket number 0..3999) so every copy of the same wristband always arrives at the exact same turnstile. Each turnstile keeps only the last 24 hours of checked-in IDs on a fast local solid-state drive (SSD), throws out entries older than a moving 24-hour watermark (a timestamp cutoff defined as the latest event time seen minus 24 hours), and records each completed batch of admitted clicks in an atomic transaction log (an append-only ledger file on S3) so replaying a crashed batch never double-writes rows.
The obvious shortcuts fail badly at 10 million events per second (864 billion events per day). Calling Spark's dropDuplicates(["event_id"]) without a watermark keeps every ID in memory forever, consuming roughly 55 TB per day and crashing executors with out-of-memory errors within hours. Trying to shrink keys into 64-bit hashes or a Bloom filter (a compact bit array that never misses a seen item, but occasionally mislabels a brand-new item as a duplicate) backfires too: at 864 billion keys per day, 64-bit hash collisions silently drop ~20,000 real clicks daily, and a 1% Bloom filter drops up to 8.6 billion real clicks daily. Finally, writing plain Parquet files directly into S3 directories leaves behind orphan files from failed Spark retries that downstream SQL engines will double-count.
Walk through four events arriving at our pipeline when the latest event time seen so far is Day 2, 12:00 (so the 24-hour watermark sits at Day 1, 12:00):
E1(event_id = a1...,timestamp = Day 2, 11:58): Passes the future-clock check, hashes to partition#17, is not found in partition#17's local RocksDB store (an embedded disk-backed key-value engine), gets recorded in RocksDB, and is written to Delta Lake inbatch_id = 90.E1retry (sameevent_id = a1...,timestamp = Day 2, 11:58, arrives 40 seconds later): Hashes to the same partition#17, hitsa1...in RocksDB, and is immediately dropped.E2(timestamp = Year 2030from a broken phone clock): Stopped beforewithWatermarkand routed to quarantine; otherwiseYear 2030would jump the watermark forward and cause all ofDay 2's real traffic to look "more than 24 hours late".E3(timestamp = Day 1, 09:00, arriving 27 hours late): Older than theDay 1, 12:00watermark, so the streaming operator drops it (incrementingnumRowsDroppedByWatermark), while our stateless late-event side query captures it for dailyMERGEreconciliation against S3.
Key points
- Back-of-the-envelope sizing dictates the storage tier:
10M/s × 86,400 s = 8.64 × 10^11events/day, which is~13.8 TBof raw 16-byte binary UUIDs and~55 TBof state with row and index overhead. Convert 36-byte UUID strings to 16-byte binary right away (2.25×smaller) and use Spark's disk-backed RocksDB state store with changelog checkpointing rather than JVM heap memory. - Keep full 128-bit IDs: Expected hash collisions scale as
n² / 2^(b+1), giving ~20,200 lost events/day at 64 bits versus~7 × 10^-14at 122 random UUIDv4 bits. - Pair
withWatermarkwithdropDuplicates: When retries preserve the sourcetimestamp,withWatermark("timestamp", "24 hours").dropDuplicates(["event_id_bin", "timestamp"])bounds state to 24 hours; when retries carry new timestamps, Spark 3.5+'sdropDuplicatesWithinWatermark(["event_id_bin"])tracks per-key expiry without puttingtimestampin the key. - State store beat external caches on retry safety: Spark commits RocksDB state versions atomically alongside each micro-batch (a small time-sliced chunk of stream records). External Redis or Cassandra TTL sets mark keys before S3 commits, silently dropping data on retry unless entries are tagged with
batch_id. - Late arrivals need an explicit policy: Events behind the watermark are dropped by the stream; capture records older than 23 hours in a stateless side stream and reconcile them into closed date partitions via an anti-join
MERGE(WHEN NOT MATCHED THEN INSERT, inserting only rows absent from the target). - Prefix skew vs hot keys: Full-key Murmur3 hashing scatters shared prefixes evenly across shuffle partitions, so prefix skew only hurts prefix-routed systems (Kafka partition keys, S3 prefix layouts, range sorts). True hot keys (millions of identical IDs) require pre-shuffle quarantine for bad sentinel IDs or two-stage key salting (appending a random
0..S-1bucket in Stage 1 to collapse load acrossStasks, then deduplicating on the raw key in Stage 2). - Idempotent sink + isolated backfills: Writing to Delta Lake or Apache Iceberg makes micro-batch retries idempotent (producing the exact same result whether run once or replayed) by tracking
(query_id, batch_id)in the S3 transaction log. Backfills run as separate batch jobs on closed dates (> 48hold) usingMERGE ... WHEN NOT MATCHEDor whole-partitionreplaceWhere.
Common mistakes
- Calling
dropDuplicates(["event_id"])on a stream without a watermark (or omitting the event-time column in classic Spark): State never expires, growing by ~55 TB every day until local disks or memory fill up. - Single-stage random key salting (
dropDuplicates(["event_id", "salt"])alone): Two retries of the sameevent_iddraw different random salts (say3and11), land on different executors, and both get written to S3 as "unique". Salting for deduplication only works in two stages where the second stage drops the salt. - Using 64-bit hashes or a standalone Bloom filter to save RAM: At
8.64 × 10^11daily events, birthday-paradox collisions and Bloom false positives silently discard thousands to billions of legitimate billable clicks. - Trusting raw client timestamps: A single buggy device reporting a future timestamp advances
max_event_timeand shifts the watermark forward, causing millions of normal on-time events to be dropped as "late". Filter future timestamps beforewithWatermark(never clamp them to arrival time, which gives retries different timestamps). - Trying to scale out later by editing
spark.sql.shuffle.partitions: Spark bakes the state partition count into the checkpoint directory on first launch and ignores config changes on restart; changing it requires a fresh checkpoint with empty 24-hour state. - Marking IDs in Redis/Cassandra before S3 commits: If the Spark batch fails after updating Redis, the replayed batch sees its own IDs in Redis and drops the entire batch.
- Writing plain S3 Parquet without a table transaction log: Engines like Trino or Athena that list S3 prefixes directly will read uncommitted Parquet files left behind by failed task or batch attempts.
- Backfilling dates inside the active 24-hour streaming window: Because the live stream's RocksDB state does not know what a separate batch job wrote to S3, an event arriving in both paths can be written twice.
Follow-up questions
-
Which operational metrics and audits would alert you when watermark eviction drops legitimate traffic or state memory grows out of bounds? Attach a
StreamingQueryListenerto export four metrics every micro-batch: (1)numRowsDroppedByWatermarkto spot spikes in late-dropped traffic; (2)stateOperators[0].numRowsTotal, which should plateau nearrate × 86,400 ≈ 8.64 × 10^11once warmed up (unbounded linear growth means watermark eviction stalled); (3) the lag(wall_clock_time - current_watermark), which should hover near24 hours(a shrinking gap signals future timestamps leaked through; a growing gap signals stalled partitions or backlog); and (4) executor NVMe disk utilization, RocksDB block-cache/memtable bytes (memoryUsedBytes), and batch processing duration vs the 1-minute trigger interval. Pair runtime metrics with a daily data-quality audit comparing distinctevent_id_bincounts in the append-only raw bronze table againstclicks_clean(using HyperLogLogapprox_count_distincthourly for cheap alerting and exact daily checks on closed partitions). -
Suppose upstream producers introduce a new
event_idencoding; how can you roll out updated parsing and deduplication without resetting streaming state? Keep the state store's key schema fixed as(event_id_bin: BINARY, timestamp: TIMESTAMP)and isolate all parsing inside a stateless normalization UDF/expression upstream ofdropDuplicates. Canonicalize legacy UUID strings (uppercase/lowercase, dashed/undashed) to the exact same 16 bytes, and encode any new ID format into canonical binary prefixed by a 1-byte version tag (for example0x01for UUID,0x02for a 20-byte ULID/Snowflake) so new IDs cannot collide with legacy 16-byte UUIDs. Because the state key's column names and types (BINARY,TIMESTAMP) do not change, you can deploy the updated normalization code with a brief rolling restart from the existing S3 checkpoint — Kafka buffers a few seconds of clicks and all 24 hours of RocksDB state stay intact. Meanwhile, non-key payload changes bypass the state store completely and evolve via Delta Lake'smergeSchemaoption. -
Why does a partitioned Spark
StateStorebehave differently at scale than deduplicating via a broadcast join? A broadcast join copies the entire lookup table into the RAM of every executor so stream tasks can check keys locally with zero network shuffle, which is fast for tiny tables (Spark's default auto-broadcast limit is10 MBand its hard ceiling is8 GB). For 24 hours of ad clicks (~13.8 TBof raw 16-byte keys, or even~576 GBfor a single hour), broadcasting is physically impossible — it would immediately blow up driver and executor memory — and a static broadcast snapshot cannot even catch duplicates arriving within the same or recent micro-batches without rebuilding and re-shipping terabytes every minute. Spark's partitionedStateStoretrades one network shuffle per event (hash(key) % 4000) plus a fast local RocksDB SSD lookup for horizontal scalability (~14 GBper partition), incremental updates, and atomic batch-versioned checkpoints; reserve broadcast joins for small auxiliary tables alongside deduplication, such as a few thousand blacklisted bot publisher IDs.
Follow-up questions
- Which operational metrics and audits would alert you when watermark eviction drops legitimate traffic or state memory grows out of bounds?
- Suppose upstream producers introduce a new `event_id` encoding; how can you roll out updated parsing and deduplication without resetting streaming state?
- Why does a partitioned Spark `StateStore` behave differently at scale than deduplicating via a broadcast join?
Similar questions
- Real-Time ML Feature Platform for Ranking
- Running Median of an Integer Stream
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging