JSON User Profile Pipeline: Batch vs. Streaming
Easy · System Design · Data Engineer · Technical Screen
Prompt
An upstream service exports customer profile records in JSON format. Every record contains personal identity details, a nested postal address object, and a list of saved payment instruments, following this illustrative shape:
{
"id": "usr-8042",
"name": "Clara Chen",
"address": {
"street": "480 Harbor View Rd",
"city": "Seattle",
"postal_code": "98101"
},
"payment_methods": [
{
"type": "card",
"brand": "mastercard",
"last4": "7392",
"expires": "2030-11"
}
]
}
Give a concise, well-structured high-level design for ingesting and serving these records under two different upstream delivery models:
- Scheduled Batch Extracts: The producer periodically drops files of JSON user records into storage. Walk through raw landing, completeness checks, validation and bad-row isolation, relational modeling of the nested
addressandpayment_methodsstructures, and how the loader stays safe across mid-run crashes or duplicate deliveries. - Real-Time Change Stream: Instead of periodic files, the producer publishes an event whenever a profile is created, edited, or deleted. Explain how your architecture adapts to preserve per-user ordering, absorb duplicate or late/out-of-order messages, checkpoint progress across consumer restarts, and isolate malformed events.
Scope & Expectations
- Up-Front Clarifications: Pin down downstream readers and freshness SLOs, data volume and growth, full-snapshot versus delta semantics, and access/erasure rules for sensitive personal fields.
- Batch Pipeline Correctness: Ensure raw deliveries remain replayable, half-uploaded batches are never ingested early, nested 1:1 and 1:N fields map cleanly to tables, and reruns or duplicate files are strictly idempotent.
- Streaming State & Ordering: Explain partition keying, monotonic version or timestamp guards (including account deletions), offset commit ordering, and dead-letter handling.
- Privacy & Trade-Offs: Separate personally identifiable fields from broad analyst tables and summarize the operational trade-offs between scheduled batches and continuous streams.
Step-by-step walkthrough
Clarify requirements and assumptions
The interviewer expects a crisp, structured comparison rather than a sprawling deep dive. Lead with a single five-step mental model—land raw, validate and quarantine, flatten nested JSON, load idempotently, and isolate sensitive fields—and then contrast how each stage works for scheduled batch files (Part 1) versus a live event stream (Part 2).
Answers assumed for the clarifying questions
- Consumers and freshness: In Part 1 (batch), data analysts query a cloud data warehouse where tables must be fresh by 06:00 UTC each morning. In Part 2 (streaming), both analysts (fresh within 15 minutes) and a live product profile service (reading one user's record within seconds) consume the data.
- Volume and growth: Roughly 10 million total users, growing ~20% per year. A daily batch is either a full 10M-row snapshot or ~500k daily changes; a live stream carries ~500k–2M user events per day.
- Snapshots vs. changes: A batch upstream may send full daily snapshots (every active user) or delta files (only users created, updated, or deleted today)—we cover both because they change the load step. For streaming, we ask the upstream team to emit full user records with a per-user
versionnumber, rather than partial field diffs, because full records stay safe even if events arrive out of order. - Sensitive fields and erasure: Full
name,street,postal_code, and cardlast4are PII (Personally Identifiable Information)—data that can identify or locate a real person and must be restricted to authorized services. Full 13–19 digit card numbers (PANs) are strictly forbidden from entering this pipeline. Account deletion requests must remove a user's personal data across raw storage, processed tables, and streaming state.
Core engineering goal — end-to-end idempotency
An operation is idempotent if running it two or three times leaves the stored data in the exact same state as running it once. Designing every pipeline stage to be idempotent makes task retries, crash recoveries, and duplicate file uploads completely harmless.
Back-of-the-envelope numbers
Scale assumptions Total users 10,000,000 Average JSON record size ~1 KB (name, address object, 1-3 payment methods) Daily full snapshot 10M x 1 KB = ~10 GB/day uncompressed (~2 GB/day compressed ~5x with gzip) Daily change batch ~500k records x 1 KB = ~500 MB/day uncompressed (~100 MB gzip) Live event stream ~2M events/day / 86,400 s = ~23 events/s avg 10x peak traffic = ~230 events/s Single-worker throughput (line-by-line Python parser) Streaming parse + validate ~20,000 records/s per Python process (conservative) 10M-record daily snapshot 10,000,000 / 20,000 = 500 s (~8.3 minutes on 1 core)What these numbers tell us:
- Volume fits comfortably on modest hardware. As long as our batch worker streams gzipped JSON Lines (
jsonl)—a text format with one complete JSON object per line so we iterate line by line instead of callingjson.load()on a 10 GB blob in RAM—one process finishes a full snapshot in ~8 minutes. Splitting across 8 files cuts that to ~1 minute without needing a Spark cluster until 10–100x scale. - 230 events/s is tiny for a message log like Kafka, which easily handles tens of thousands of messages per second per broker. We pick partition counts for ordering and parallelism, not raw bandwidth.
- Correctness is the real engineering problem: partial uploads, duplicate files, out-of-order events, schema changes, and PII protection.
- Volume fits comfortably on modest hardware. As long as our batch worker streams gzipped JSON Lines (
Input contracts and output tables
In a data pipeline, our "API" consists of the delivery contract with the upstream producer and the table schemas exposed to downstream readers.
Part 1: Batch input contract. The producer writes compressed
jsonlpart files first and uploads a small_manifest.jsonfile last. A manifest is a digital packing slip listing every file in the delivery, its exact record count, and its SHA-256 checksum so our pipeline never reads a half-uploaded batch:s3://raw-zone/users/delivery_date=2026-11-26/delivery_id=d-7781/ part-00001.jsonl.gz part-00002.jsonl.gz _manifest.json _manifest.json: { "delivery_id": "d-7781", "kind": "snapshot", // "snapshot" or "delta" "as_of": "2026-11-26T00:00:00Z", "files": [ {"name": "part-00001.jsonl.gz", "records": 5000000, "sha256": "9f2c..."}, {"name": "part-00002.jsonl.gz", "records": 5000000, "sha256": "41ab..."} ] }Part 2: Stream input contract. Each create, update, or delete publishes an event to a
user-eventstopic keyed byuser_id:Topic: user-events Partition key: user_id { "event_id": "evt-0b9e...", "user_id": "usr-8042", "op": "upsert", // "upsert" or "delete" "version": 42, // monotonically increasing integer per user "updated_at": "2026-11-26T10:15:03Z", "record": { ...full JSON user record (null when op == "delete")... } }Output tables (split by sensitivity):
Warehouse (for analysts — no raw PII): analytics.users user_id, city, country, postal_prefix, payment_method_count, ... analytics.user_payment_methods user_id, method_key, type, brand, expires, ... Warehouse (restricted access — PII Vault): pii.users_identity user_id, name, street, postal_code, source_version pii.user_payment_last4 user_id, method_key, last4, source_version Operational Serving Store (Part 2 streaming only): Postgres: users_current & user_payment_methods_current (indexed by user_id)Data model and flattening nested fields
A JSON user record mixes two kinds of nesting that require two different relational patterns:
addressis a 1-to-1 nested object (at most one mailing address per user), so its fields flatten directly into columns on the user tables (city,postal_prefixinanalytics.users;street,postal_codeinpii.users_identity).payment_methodsis a 1-to-many array (zero, one, or several cards per user), so flattening it intocard_1_brand,card_2_brandcolumns would break as soon as a user adds a fourth card. Instead, it becomes a child table (user_payment_methods) with one row per payment method and composite primary key(user_id, method_key).
Input JSON (1 user with 2 cards) {"id": "usr-8042", "name": "Clara Chen", "address": {"street": "480 Harbor View Rd", "city": "Seattle", "postal_code": "98101"}, "payment_methods": [ {"type": "card", "brand": "mastercard", "last4": "7392", "expires": "2030-11"}, {"type": "card", "brand": "discover", "last4": "5160", "expires": "2029-05"} ]} | v flatten_user() analytics.users (1 row): pii.users_identity (1 row): usr-8042 | Seattle | 981 | count=2 usr-8042 | Clara Chen | 480 Harbor View Rd | 98101 analytics.user_payment_methods (2 rows): pii.user_payment_last4 (2 rows): usr-8042 | k_4d2a | card | mastercard | 2030-11 usr-8042 | k_4d2a | 7392 usr-8042 | k_8b19 | card | discover | 2029-05 usr-8042 | k_8b19 | 5160Two rules prevent subtle data bugs:
- Replace a user's child rows as a complete set. JSON arrays do not have stable positions: if a user deletes their first card, card
[1]shifts into[0]. Updating by array index would mix attributes across cards. Instead,method_keyis computed from an upstreamidif provided, or a deterministic hash of(type, brand, last4, expires). Whenever a newer version of"usr-8042"arrives, we delete old child rows for"usr-8042"and insert the new set inside the same database transaction. - Turn every bad type or format into a
ValueError. Both batch and streaming workers call the exact same pure Python function below. If the upstream unexpectedly changes a string field into a nested object or number,flatten_userraisesValueErrorso the record is routed cleanly to quarantine instead of crashing the worker with an unhandledTypeError.
import hashlib def optional_str(mapping, key): """Read an optional string field; raise ValueError if present with a non-string type.""" value = mapping.get(key) if value is None: return None if not isinstance(value, str): raise ValueError(f"field '{key}' must be a string") return value def valid_expiry_month(expires): """Check 'YYYY-MM' format with month between 01 and 12.""" if not isinstance(expires, str) or len(expires) != 7 or expires[4] != "-": return False year_str, month_str = expires[:4], expires[5:] return year_str.isdigit() and month_str.isdigit() and 1 <= int(month_str) <= 12 def compute_method_key(method): """Build a deterministic ID for one payment method.""" explicit_id = optional_str(method, "id") if explicit_id: return explicit_id # Hash the defining attributes when the upstream sends no explicit card ID parts = [ optional_str(method, "type") or "", optional_str(method, "brand") or "", optional_str(method, "last4") or "", optional_str(method, "expires") or "", ] raw_fingerprint = "|".join(parts).encode("utf-8") return hashlib.sha256(raw_fingerprint).hexdigest()[:16] def flatten_user(record): """Validate one raw JSON dict and return (user_row, payment_rows). Raises ValueError on any schema, type, or format violation so callers can quarantine or dead-letter the bad record without stopping healthy records. """ if not isinstance(record, dict): raise ValueError("record must be a JSON object") user_id = optional_str(record, "id") if not user_id: raise ValueError("missing or non-string user id") address = record.get("address") if address is None: address = {} elif not isinstance(address, dict): raise ValueError("address must be a JSON object") methods = record.get("payment_methods") if methods is None: methods = [] elif not isinstance(methods, list): raise ValueError("payment_methods must be a JSON list") payment_rows = [] seen_keys = set() for method in methods: if not isinstance(method, dict): raise ValueError("each payment method must be a JSON object") last4 = optional_str(method, "last4") if last4 is None or len(last4) != 4 or not last4.isdigit(): raise ValueError("last4 must be a 4-digit string") expires = optional_str(method, "expires") if not valid_expiry_month(expires): raise ValueError("expires must match YYYY-MM") key = compute_method_key(method) # Deduplicate identical cards listed twice in the same array so PK (user_id, method_key) holds if key in seen_keys: continue seen_keys.add(key) payment_rows.append({ "user_id": user_id, "method_key": key, "type": optional_str(method, "type"), "brand": optional_str(method, "brand"), "last4": last4, "expires": expires, }) postal_code = optional_str(address, "postal_code") user_row = { "user_id": user_id, "name": optional_str(record, "name"), "street": optional_str(address, "street"), "city": optional_str(address, "city"), "country": optional_str(address, "country"), "postal_code": postal_code, "postal_prefix": postal_code[:3] if postal_code else None, "payment_method_count": len(payment_rows), } return user_row, payment_rowsHigh-level architecture: batch vs. streaming
PART 1: BATCH PIPELINE Upstream files + _manifest.json | v [ Raw Object Storage ] (write-once S3/GCS bucket, encrypted, 30-day TTL) | | Airflow sensor sees _manifest.json, verifies SHA-256 + row counts v [ Batch Worker ] (streams .jsonl.gz line by line -> flatten_user() + PAN check) | | | bad rows (< 0.5% threshold) | valid flattened rows v v [ Quarantine Table ] [ Staging Tables (per delivery_id) ] | | Quality gate: counts match, PK unique, null rate OK v [ Atomic Publish ] (Snapshot: overwrite dt partition | Delta: version-guarded MERGE) | v [ Warehouse: analytics.* & pii.* ] PART 2: STREAMING PIPELINE Upstream user changes (key = user_id) | v [ Kafka Topic: user-events (6 partitions, 7-day retention) ] | | v v [ Stream Consumer Group ] [ Raw Event Archiver ] (flatten_user() + version-guarded upsert) (flushes .jsonl.gz to raw/ every 5 min) | | | | invalid event | valid event | every 15 min v v v [ Dead-Letter Topic ] [ Postgres: users_current ] [ Warehouse: version-guarded MERGE ] (commits Kafka offset ONLY after DB transaction commits)Sharing
flatten_user()and the version-comparison rule across both architectures guarantees that a record produces the exact same columns whether it arrived in a nightly file or a live Kafka event.Part 1 deep dive: replayable landing and idempotent batch loads
Let's walk through Part 1 stage by stage and verify what happens when a worker crashes midway, an orchestrator retries a task, or the producer uploads the exact same delivery twice:
- Replayable raw landing. Files land untouched in an immutable object-storage prefix (
delivery_date=.../delivery_id=.../) with overwrites disabled. Because we never mutate raw files in place, we can fix a parser bug tomorrow and replay yesterday's exact input. Retention is capped at 30 days so old copies of PII expire automatically. - Complete-delivery detection. Never trigger a job the instant
part-00001.jsonl.gzappears—the producer might still be uploadingpart-00002.jsonl.gz. Instead, an orchestrator sensor (such as Airflow) waits for_manifest.json, then verifies that every listed file exists and matches its declared SHA-256 hash and line count. (If an external vendor cannot write a manifest, require an.EOFsentinel file or a 15-minute quiet window with unchanged file sizes, though a manifest is much stronger.) - Validation, PAN scanning, and quarantine. Every line is checked by
flatten_user()plus a regex + Luhn checksum scan (the standard 10-modulo digit formula used to distinguish real 13–19 digit credit card numbers from ordinary IDs or phone numbers). Any failing line is written to a restricted quarantine table—a holding table recording(delivery_id, file_name, line_number, error_reason, raw_json)—while healthy rows continue to staging. However, if more than 0.5% of rows in a batch fail validation, a circuit breaker aborts before publishing and pages the team so an upstream schema break never overwrites the warehouse with a truncated table. - Idempotent loading (snapshot vs. delta).
- Full snapshot deliveries: Load validated rows into a staging table, run quality checks (
staged_rows + quarantined_rows == manifest_total, zero duplicateuser_ids, total count within ±5% of yesterday), and then atomically overwrite that date's partition (INSERT OVERWRITE ... PARTITION (dt = '2026-11-26')) before advancing theanalytics.usersview pointer. Rerunning2026-11-26simply overwrites the2026-11-26partition with the exact same rows, and users deleted upstream vanish naturally from the new snapshot. - Delta (change-only) deliveries: A delta file can contain three edits to
"usr-8042"within the same day, so we first keep only the highestsource_versionperuser_idin staging (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY source_version DESC) = 1), and then run a version-guardedMERGE:
- Full snapshot deliveries: Load validated rows into a staging table, run quality checks (
MERGE INTO analytics.users AS target USING staged_users_deduped AS src ON target.user_id = src.user_id -- Strict '>' makes duplicate file deliveries and out-of-order older files complete no-ops WHEN MATCHED AND src.source_version > target.source_version THEN UPDATE SET city = src.city, country = src.country, postal_prefix = src.postal_prefix, payment_method_count = src.payment_method_count, is_deleted = src.is_deleted, source_version = src.source_version, delivery_id = src.delivery_id WHEN NOT MATCHED THEN INSERT (user_id, city, country, postal_prefix, payment_method_count, is_deleted, source_version, delivery_id) VALUES (src.user_id, src.city, src.country, src.postal_prefix, src.payment_method_count, src.is_deleted, src.source_version, src.delivery_id);Child payment rows in `analytics.user_payment_methods` and `pii.user_payment_last4` are deleted and re-inserted inside the same transaction **only** for `user_id`s where `src.source_version > target.source_version` (or new users), so replaying an older delta file cannot resurrect a removed credit card.- Scheduling, retries, and backfills. An
ingested_deliveriesmetadata table logs(delivery_id, manifest_sha256, transform_version). If the upstream accidentally sends the exact same delivery twice under the same parser version, we skip it immediately; even without that check, partition overwrite andMERGEmake a second run a no-op. If we fix a bug inflatten_user()and want to reprocess the last 7 days of delta files (wheresource_versionin raw files equalstarget.source_version), we rebuild into a clean shadow table from the raw zone—filtering out anerased_userstable so deleted users stay deleted—and atomically swap table names.
- Replayable raw landing. Files land untouched in an immutable object-storage prefix (
Part 2 deep dive: ordering, duplicates, and crashes in streaming
Unlike nightly extracts, an unbounded stream never reaches an end-of-day completion boundary. Network retries create duplicate events, upstream worker threads can emit
version 42slightly out of order withversion 41, and our consumer can crash right between updating Postgres and saving its progress.1. Clarifying questions and transport ordering. We ask two questions up front: Does each event carry a monotonic per-user version? and Does the producer preserve per-user order? We ingest events through a durable log (such as Apache Kafka) using
user_idas the partition key. A Kafka partition is an ordered, append-only log file; hashinguser_idroutes every event for"usr-8042"to the exact same partition so a single consumer thread reads"usr-8042"'s events in arrival order. Six partitions comfortably handle ~230 events/s while giving 6-way consumer parallelism.2. Version-guarded upserts and tombstones. Even with Kafka partitioning, a multi-threaded upstream service might publish
version 41to Kafka a millisecond afterversion 42, or retryversion 42twice. And if a user deletes their account (version 43), physically deleting"usr-8042"from Postgres would create a nasty bug: if delayedversion 42arrives a second later,INSERTwould see no row and bring the deleted user back to life! Instead, deletes write a tombstone—a minimal marker row withis_deleted = true, personal fields wiped toNULL, andversion = 43preserved for a 7-day safety window:Event stream arriving for usr-8042: 1. upsert (v42, city="Seattle", 1 Mastercard) -> stored: v42, city="Seattle", is_deleted=false 2. upsert (v42, duplicate retry) -> 42 > 42 is false -> ignored (no-op) 3. upsert (v41, delayed older event) -> 41 > 42 is false -> ignored (never goes backward) 4. delete (v43) -> 43 > 42 is true -> tombstone: v43, PII=NULL, is_deleted=true, cards wiped 5. upsert (v42, straggler replay) -> 42 > 43 is false -> blocked by v43 tombstone!Inside one Postgres transaction, the consumer updates
users_currentand usesRETURNING user_idto update child payment rows only when the version guard actually accepted the event:-- Step A: Upsert or tombstone the parent row only if incoming :version is strictly newer. -- When :is_deleted is true, the caller passes NULL for :name, :street, :city, :postal_code. INSERT INTO users_current (user_id, name, street, city, postal_code, version, is_deleted) VALUES (:user_id, :name, :street, :city, :postal_code, :version, :is_deleted) ON CONFLICT (user_id) DO UPDATE SET name = EXCLUDED.name, street = EXCLUDED.street, city = EXCLUDED.city, postal_code = EXCLUDED.postal_code, version = EXCLUDED.version, is_deleted = EXCLUDED.is_deleted WHERE users_current.version < EXCLUDED.version RETURNING user_id; -- Step B (executed in the SAME transaction ONLY if Step A returned user_id): -- Delete existing payment rows for :user_id, and if :is_deleted is false, insert the new set.(What if the upstream has no version number at all? Then
updated_attimestamps can break ties down to milliseconds, and anevent_iddeduplication table drops exact retries over 7 days, though Kafka partition arrival order becomes the fallback for same-millisecond edits. Pushing the upstream to include its database row version or CDC log sequence number is strongly preferred.)3. Checkpointing, dead-lettering, and warehouse sync.
- At-least-once delivery + idempotent sink: A consumer offset is the bookmark Kafka stores for the last message a consumer finished processing. Our consumer commits its offset only after the Postgres transaction commits. If the consumer crashes right after Postgres commits but before committing the offset, restart replays those last few events—and the
version < EXCLUDED.versionguard turns them into harmless no-ops. - Dead-letter queue (DLQ) for bad events: In streaming, halting on one malformed JSON message would freeze an entire partition (1/6 of all users!). Instead, any message that fails JSON parsing,
flatten_user(), or the Luhn PAN check is published to a restricted dead-letter topic—a side queue holding failed raw messages and their error reason—and the consumer advances. An alert fires if DLQ rate exceeds a few events per minute; once fixed, replaying the DLQ through the normal consumer is completely safe thanks to the version guard. - Late events in warehouse aggregates: An archiver flushes raw stream events to object storage every 5 minutes, and a 15-minute scheduled
MERGEupdatesanalytics.*andpii.*. For daily metrics (such as new sign-ups per day), we group by event timestamp rather than arrival time and use a watermark—a rolling cutoff saying "we assume events up to timestampT - 1 hourhave arrived"—plus a lightweight daily recomputation over the last 48 hours to absorb rare stragglers.
- At-least-once delivery + idempotent sink: A consumer offset is the bookmark Kafka stores for the last message a consumer finished processing. Our consumer commits its offset only after the Postgres transaction commits. If the consumer crashes right after Postgres commits but before committing the offset, restart replays those last few events—and the
Protecting sensitive personal and payment data
- Strict schema classification and table separation: Analysts query
analytics.users(city,country, 3-characterpostal_prefix) andanalytics.user_payment_methods(brand,type,expires). Rawname,street, fullpostal_code, andlast4live exclusively inpii.*tables behind column- and role-based access policies. - Block raw card numbers at the door: Any string matching a 13–19 digit Luhn check triggers a high-severity alert and routes to an encrypted, security-restricted quarantine rather than staging or logs.
- Encryption and PII-free logs: Enforce TLS in transit and KMS-managed encryption at rest across object storage, Kafka, Postgres, and the warehouse. Application logs print only pointers (
delivery_id=d-7781 line=4092orpartition=2 offset=99182)—never raw JSON payloads or names. - Short raw retention: Expiring raw landing files, quarantine rows, and DLQ messages after 30 days (and Kafka segments after 7 days) ensures raw personal data does not accumulate indefinitely.
- Strict schema classification and table separation: Analysts query
Scaling, failure modes, and batch-vs-streaming trade-offs
Scaling to 10–100x (100M–1B users, ~2,300–23,000 events/s): In batch, split deliveries into ~128 MB
.jsonl.gzfiles and process files in parallel across worker pods (or moveflatten_userinto Spark/Beam when single-node orchestration becomes awkward). In streaming, raise Kafka partitions from 6 to 32–64, batch Postgres upserts (50–100 events per round-trip), and shardusers_currentbyuser_idonce single-primary write throughput (~5k–10k TPS) saturates.Failure scenario Part 1: Batch recovery Part 2: Streaming recovery Worker crashes mid-run Orchestrator retries task; staging/overwrite/MERGE is idempotent Consumer restarts from last committed offset; version guard ignores already-applied writes Duplicate input arrives ingested_deliveriesskips it;MERGE/ overwrite is a no-op anywayversion < EXCLUDED.versionmakes duplicate event a no-opPartial / truncated upload Missing _manifest.jsonor checksum mismatch holds the run and alertsNot applicable (events are self-contained messages) Malformed records Sent to quarantine; > 0.5% bad rows halts before publishSent to dead-lettertopic so partition never blocks; replayable after fixBug in flatten_user()Fix code, rebuild into shadow table from 30-day raw bucket, swap Fix code, replay from raw event archive into shadow/target tables Core trade-offs to summarize for the interviewer:
- Freshness vs. operational simplicity: Batch gives a crisp "complete day" boundary, cheap compute that runs 10 minutes a day, and effortless quality gates before anyone sees new data—at the cost of 24-hour staleness. Streaming delivers sub-minute freshness for live product features, at the cost of 24/7 consumers, tombstones, watermarks, and DLQ monitoring.
- Full records vs. field-level diffs: Carrying full user JSON in each stream event uses ~1 KB instead of ~100 bytes, but lets any newer event safely supersede missed or reordered older events without needing brittle distributed transactions.
- Halt-on-spike vs. isolate-and-continue: A batch pipeline can afford to pause today's publish when > 0.5% of rows fail validation, protecting analysts from partial tables; a live stream cannot freeze healthy users' updates, so it dead-letters bad events and alerts on rate.
Intuition & how it works
Think of the two pipeline modes like two ways a bookstore updates its catalog:
- Batch processing is like receiving one sealed shipping crate every midnight with a signed packing slip on top (a manifest—a summary file listing every file inside, its row count, and its checksum). You verify the packing slip so you know no box fell off the truck, inspect every book, set damaged ones aside on a quarantine shelf (a holding table for invalid records), and put the good ones out on display all at once before the store opens at 06:00.
- Streaming processing is like working a 24/7 conveyor belt where individual update parcels arrive one by one, forever. Nobody ever blows a whistle saying "all parcels have arrived." Sometimes the postal service drops off two copies of parcel #42, or delivers parcel #41 five seconds after parcel #42. You stay sane by stamping every user's shelf slot with the latest version number (
version = 42) and enforcing one iron rule: only overwrite a user's data if the incoming parcel has a strictly higher version number, and record account deletions as a tombstone (a placeholder row markedis_deleted = truewith personal data wiped, kept so a delayed parcel #42 cannot resurrect a deleted account).
Why do the naive approaches fail? Reading a 10 GB JSON dump with a single json.load() call blows up worker memory, and appending rows blindly on every run duplicates users whenever a failed job retries or an upstream partner uploads the same file twice. Starting a batch job the moment a filename appears in cloud storage reads half-written files, while crashing on the very first malformed record lets one bad row take down 10 million good ones. In streaming, deleting a row outright lets late-arriving older events re-create deleted users, and updating payment_methods[0] in place scrambles credit cards whenever a user removes or reorders a card.
Let's trace four concrete inputs for user "usr-8042" across both designs:
1. Initial record arrives (version 10, city="Seattle", cards=[Mastercard 7392, Discover 5160]):
flatten_user() splits 1 nested JSON object into:
- 1 user row (analytics.users gets city="Seattle"; pii.users_identity gets name & street)
- 2 card rows (keyed by hash of card attributes; pii.user_payment_last4 gets "7392", "5160")
2. Duplicate retry of version 10 arrives (network retry or re-sent delta file):
Version check: incoming 10 > stored 10 is FALSE -> skipped as a harmless no-op!
3. Out-of-order older event arrives (version 9, city="Tacoma"):
Version check: incoming 9 > stored 10 is FALSE -> ignored; city stays "Seattle".
4. Malformed update (expires="2030-15") followed by valid delete (version 11):
- Bad record raises ValueError("expires must match YYYY-MM") -> routed to quarantine /
dead-letter queue (a side topic for bad messages) without blocking other users.
- Delete (version 11 > 10) writes tombstone (is_deleted=true, PII columns set to NULL)
and deletes usr-8042's 2 card rows in the same transaction.
Key trade-offs
- Batch vs. streaming freshness and complexity: Batch processing gives a clean "complete delivery" checkpoint (via
_manifest.json), cheap scheduled compute (~8 minutes/day), and pre-publish quality gates, at the cost of hours-old data. Streaming delivers seconds-level freshness for live product services, at the cost of always-on consumers, Kafka partitions, tombstones, dead-letter queues, and watermarks (rolling time cutoffs used to decide when an hour or day of event-time metrics is ready to publish). Match the choice to the consumer: daily analyst dashboards rarely justify streaming; a live user-profile service does. - Partition overwrite vs.
MERGE: Overwriting a date partition (INSERT OVERWRITE) from a full daily snapshot is the simplest idempotent write and handles upstream deletions automatically, at the cost of transferring and rewriting all 10M users every day. Incremental delta files and streams transfer ~20x less data (~500k rows/day), but require explicit delete tombstones and a version-guardedMERGE. - Full records vs. changed-field diffs in streaming: Sending the full ~1 KB user JSON on every event uses slightly more network bandwidth than sending
{"city": "Portland"}, but makes every event self-contained. That lets a consumer safely skip stale or duplicate events (version <= stored_version), whereas field-level diffs require applying every single event in exact order without gaps. - At-least-once delivery + idempotent writes vs. distributed two-phase commit: Committing the Kafka consumer offset (the bookmark of processed messages) after the database transaction commits means a crash can replay a few events on restart, which our version guard absorbs effortlessly. Coordinating distributed exactly-once transactions across Kafka and Postgres + warehouse sinks adds heavy operational coupling for no extra accuracy here.
- Raw retention window vs. privacy footprint: Keeping raw landing files longer makes historical bug-fix backfills easier, but every extra week of raw storage is another place holding PII (Personally Identifiable Information) that right-to-erasure workflows must govern. A 30-day raw bucket TTL (and 7-day Kafka retention) balances operational replay against privacy compliance.
Common mistakes
- Calling
json.load()on an entire multi-gigabyte file: Loading 10 GB of JSON into a Python dictionary exhausts RAM; always stream gzipped JSON Lines (jsonl)—one JSON record per line—line by line. - Triggering batch ingestion as soon as a data file appears: Without waiting for a final
_manifest.json(and checking SHA-256 hashes and row counts), the worker will regularly ingest truncated, still-uploading files. - Appending rows on every run or merging an un-deduplicated delta file: Blind
INSERTdoubles rows on retry, and running SQLMERGEwhen the staging table contains two updates for the sameuser_idthrows a runtime error in most cloud warehouses (ROW_NUMBER()deduplication peruser_idis required first). - Crashing on the first bad record—or silently dropping 40% of a batch: One malformed user record should go to quarantine without killing the job, and a circuit breaker (such as > 0.5% quarantined rows) must stop a widespread upstream bug from publishing an incomplete table.
- Updating
payment_methodsby array index (0, 1, 2): Removing or reordering a card shifts indices and attaches attributes to the wrong card; always key child rows deterministically and replace that user's card set inside one transaction when the parent version advances. - Partitioning the stream by random round-robin instead of
user_id: Withoutkey = user_id, two updates for"usr-8042"land on different partitions and get processed concurrently by different workers. - Physically deleting rows in a streaming sink instead of writing tombstones: Without a tombstone remembering
version = 43, a delayedversion = 42event arriving moments later inserts"usr-8042"back into the table. - Committing Kafka offsets before the database write commits: If the process crashes right after committing the offset, those in-memory updates are lost forever (at-most-once loss).
- Allowing raw PII or full credit card numbers into analyst tables and error logs: Separate
analytics.*frompii.*, scan strings with a 13–19 digit Luhn checksum (the standard check-digit formula for payment card numbers) to block accidental full card numbers, and log only file/line or partition/offset pointers.
Follow-up questions
- When an account holder submits a right-to-erasure request, how do you purge their personal data across raw archives, analytical tables, and live streaming state? First, record
(user_id, requested_at)in a durableerased_usersregistry so every future backfill or replay filters that user out and never resurrects them. Next, publish anop = "delete"event to the stream sousers_currentand stream consumers overwrite the user row with a PII-wiped tombstone (name = NULL,street = NULL,is_deleted = true) and delete their child payment rows, then delete or anonymize the user's rows inpii.*andanalytics.*and expire historical warehouse table snapshots (time-travel files) past a short operational window. Because raw object-storage files and Kafka segments are immutable, our 30-day raw bucket TTL and 7-day Kafka retention automatically age out raw copies within standard regulatory windows (such as GDPR's 30-day response window); if raw archives must be kept longer, crypto-shredding—encrypting each user's PII fields with a per-user key stored in a key store and deleting that user's key on erasure—renders every historical copy unreadable immediately. - Suppose the producer silently introduces an extra nested attribute or alters an existing field's data type—how do the batch and streaming pipelines react? Adding an unknown attribute is non-breaking in both modes:
flatten_user()ignores unmapped keys while the full JSON remains preserved in raw files (or an optionalextra_jsoncolumn), and a daily schema-drift monitor alerts the data team so they can add the new column intentionally and backfill from raw storage. Changing an existing field's type (for example, turningpostal_codefrom"98101"into an object{"zip5": "98101"}) causesflatten_user()to raiseValueError: in batch, affected rows route toquarantine, and once > 0.5% of the delivery fails, the circuit breaker halts before publishing so analysts keep yesterday's clean table until the parser is updated and rerun from raw. In streaming, failing events route to the dead-letter queue while valid events continue uninterrupted, paging on-call when DLQ rate spikes so we can deploy the parser fix and replay the DLQ; adding a schema registry (a central service that validates producer schemas before events are accepted) catches breaking type changes at publish time before they ever enter Kafka. - How would you load twelve months of historical records into the streaming architecture without disrupting real-time traffic? Because Kafka retains 7 days and raw archives keep 30 days, a 12-month load starts with an upstream historical export (either a point-in-time snapshot plus CDC (Change Data Capture) history logs—database change logs recording past row versions—or a historical dump into object storage). Never dump a year of historical records into the live
user-eventsKafka topic, which would flood consumer lag and delay real-time profile updates for hours. Instead, run a parallel batch backfill job using the exact sameflatten_user()logic and the exact sameversion-guardedMERGE/ON CONFLICT ... WHERE version < EXCLUDED.versiondirectly against the target tables (after filtering outerased_users): because higher versions always win, historical rows cannot overwrite fresher live updates that arrived while the backfill was running, and any daily event-time aggregates can then be recomputed cleanly in batch and reconciled against source row counts. - If nightly batch extracts and real-time events both populate the same destination tables, how do you keep them consistent? Require both pipelines to key rows by
user_id, carry the same comparable upstreamsource_version(or authoritative sourceupdated_attimestamp with a deterministic tie-breaker), and write through the same strict newer-winsMERGE/ upsert rule. Never let a midnight batch snapshot loaded at 03:00 blindlyINSERT OVERWRITEthe live table, because that would wipe out three hours of fresh streaming edits made between 00:00 and 03:00! Instead, treat the daily snapshot as an audit and self-healing pass alongside the stream: any user whose snapshotsource_versionis higher than the table's stored version reveals a dropped stream event and heals automatically viaMERGE, any active table row whosesource_versionpredates the snapshot'sas_ofcutoff yet is absent from the snapshot reveals a missed delete, and any table row already at a newer version than the snapshot is left untouched—while logging the count of healed discrepancies as a daily health metric for the streaming pipeline.
Follow-up questions
- When an account holder submits a right-to-erasure request, how do you purge their personal data across raw archives, analytical tables, and live streaming state?
- Suppose the producer silently introduces an extra nested attribute or alters an existing field's data type—how do the batch and streaming pipelines react?
- How would you load twelve months of historical records into the streaming architecture without disrupting real-time traffic?
- If nightly batch extracts and real-time events both populate the same destination tables, how do you keep them consistent?
Similar questions
- Subordinate Rollups Across an Org Hierarchy
- Constant-Time Org-Chart Subtree Lookup
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests