End-to-End Cloud Ingestion and Serving Architecture

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Prompt

Design an end-to-end cloud data ingestion and serving architecture capable of handling both continuous event streams and scheduled batch feeds on a major public cloud platform of your choice (AWS, GCP, or Azure).

Your design should address the following engineering decisions:

  • Upstream capture strategy: Compare Change Data Capture (CDC), domain event sourcing, and scheduled micro-batch extraction, and select the appropriate pattern for different operational databases and external vendor feeds.
  • Physical layout & file maintenance: Justify your stream-topic and lakehouse table partitioning keys, and explain how your compaction strategy prevents small-file degradation without hurting query freshness.
  • Correctness, contracts, & privacy: Show how the pipeline guarantees end-to-end idempotency across retries and replays, supports non-breaking schema evolution (such as introducing nullable or default-valued fields), and tokenizes Personally Identifiable Information (PII) before analytical persistence while preserving joinability and erasure compliance.
  • Cloud cost governance: Specify concrete cost controls covering storage lifecycle tiering, retention TTLs across hot and cold stores, and target columnar file sizes.
  • Resilience & chaos validation: Describe one high-risk failure scenario you would inject in a chaos-engineering game day, detailing expected alerts, upstream blast-radius circuit breakers, and post-recovery data-integrity checks.

Scope & Expectations

  • Map realistic operational and third-party workloads onto managed cloud components that unify streaming and batch pipelines into shared analytical layers plus a low-latency operational store.
  • Back partitioning, checkpointing, and compaction intervals with concrete volume/file-count math so row-level ordering and scan efficiency both hold at scale.
  • Provide explicit, replay-safe patterns for deduplication and soft deletes, forward/backward schema compatibility, and secret-keyed in-flight PII tokenization.
  • Pair quantitative storage-tiering and TTL rules (avoiding metadata corruption pitfalls) with a well-bounded chaos experiment that protects primary production databases.

Step-by-step walkthrough

  1. Define workload assumptions and pick AWS building blocks

    Every good architecture answer starts by pinning down concrete workload numbers so later choices (partition counts, file sizes, storage tiers) can be justified mathematically:

    • Upstream data sources:
      1. Three operational PostgreSQL databases (orders, customers, payments on Amazon Aurora/RDS) generating ~5,000 row changes/s on average (432 M changes/day) and ~20,000 changes/s at peak (~90 GB/day compressed).
      2. Nightly third-party SaaS exports (CRM and ad spend) delivered as daily CSV/JSON files (~10 GB/day), bringing total daily ingestion to ~100 GB/day (36.5 TB/year).
    • Downstream consumers:
      1. BI & analytics: SQL dashboards needing data fresh within 15 minutes.
      2. Data science: full historical replay and point-in-time training snapshots.
      3. Online product API: per-customer spend/order summaries served in < 50 ms p99.
    • Privacy & compliance: PII (Personally Identifiable Information) — emails, phone numbers, names, addresses — must never land in lake storage in plain text, and customer deletion requests (GDPR/CCPA) must be honored end to end.

    Preferred cloud: AWS (every component has a 1-to-1 equivalent on GCP and Azure): - Transport & stream processing: Amazon MSK (managed Apache Kafka) + MSK Connect running Debezium, Glue Schema Registry, and Managed Apache Flink. - Lakehouse storage & batch: Amazon S3 storing Apache Iceberg tables (an open lakehouse table format that adds ACID transactions, schema tracking, and SQL MERGE updates on top of Parquet files in object storage), cataloged in AWS Glue, orchestrated by MWAA (managed Airflow), and queried via Athena / Redshift. - Low-latency serving & security: DynamoDB (< 10 ms key-value reads), AWS KMS (encryption keys), and Lake Formation (access control).

  2. Choose CDC, micro-batch, or event sourcing per upstream source

    Instead of forcing one ingestion style everywhere, match each source to how it actually produces state:

    Pattern          How it captures data                  Strengths                        Weaknesses
    ---------------  ------------------------------------  -------------------------------  -----------------------------------
    CDC (Change      Reads the database's internal WAL     Captures every insert, update,   Needs DB replication slot; records
    Data Capture)    (Write-Ahead Log) in commit order     and hard delete with ~0 DB load  row diffs rather than user "why"
    Event sourcing   App writes immutable domain events    Preserves rich business intent   Requires rewriting the application
                     ("OrderCancelledByUser") as truth     and complete replayable history  from scratch; impossible for legacy
    Micro-batch      Scheduled SQL poll (updated_at > T)   Dead simple; only option when    Polling misses hard deletes and
                     or periodic file drop                 vendors ship daily CSV/API dumps intermediate state transitions
    

    Our choice: - Operational Postgres databases -> CDC via Debezium reading logical replication from the WAL (the Write-Ahead Log, Postgres's sequential transaction journal). Rewriting existing apps for event sourcing is unrealistic, and polling WHERE updated_at > last_run every 15 minutes both hammers the production DB and misses intermediate transitions (like an order moving placed -> paid -> refunded within 4 minutes) as well as hard DELETE rows. - Third-party SaaS exports -> Micro-batch file ingestion. Because external vendors only drop nightly files to S3, scheduled Spark/Airflow micro-batches are the clean, right-sized fit. - Event sourcing -> Reserve for brand-new greenfield microservices where an immutable ledger is the product (for example, a new wallet ledger publishing directly to MSK).

  3. Connect streaming, batch, and low-latency serving in one lakehouse

    We organize S3 + Iceberg into medallion layers (bronze = raw append-only history, silver = deduplicated current table state, gold = business marts) shared by both streaming and batch paths:

    SOURCES              INGEST & STREAMING                          LAKEHOUSE (S3 + Iceberg)             SERVING
    Postgres x3 --WAL--> Debezium --> MSK Kafka (key = PK)
                                       | (Glue Schema Registry)
                                       v
                            Flink (validate, HMAC-tokenize PII) ---> DynamoDB (customer totals, TTL) ---> Product API
                               |                          |                                               (< 50 ms)
                               v                          v
                        Dead-letter topic        Bronze Iceberg (append-only tokenized change log)
                        (malformed values)                |
                                                          v  Idempotent MERGE by (PK, LSN) every 2-5 min
                                                 Silver Iceberg (current state + soft-delete flags)
                                                          |
                                                          v  Spark / dbt transforms (MWAA)
                                                  Gold Iceberg  ---> Athena / Redshift ---> BI & ML notebooks
                                                          ^
    SaaS CSV/JSON --> S3 landing/ --> Spark batch --------+ (reuses exact same PII tokenizer -> Bronze -> Silver)
    

    Sharing one tokenization library and one bronze -> silver -> gold table hierarchy eliminates "two-pipeline drift" between streaming and batch, while pushing hot customer aggregates straight from Flink to DynamoDB keeps high-QPS API traffic off the analytical lake.

  4. Partition smartly and compact away the small-files problem

    Kafka partitioning: key every CDC message by its table primary key (order_id) across 64 partitions (sized with headroom for 20,000 events/s) so every change to Order #42 lands in the exact same partition in strict commit order. Size partitions generously up front because changing a topic's partition count later reshuffles key-to-partition hashes and temporarily breaks per-key ordering.

    Iceberg table partitioning: - Partition bronze and silver by calendar day using Iceberg hidden partitioning (days(updated_at)), matching the date-range WHERE filter on 95% of analytical queries. - On massive tables frequently filtered by customer, add a fixed hash bucket (bucket(16, customer_id_token)), splitting each day into 16 balanced chunks. - Never partition directly by a high-cardinality ID like customer_id: 100,000 active customers per day creates 100,000 tiny directories per day, crippling S3 listing and query planning.

    Why streaming requires compaction: in streaming, each parallel Flink writer task flushes one new Parquet file on every checkpoint commit. Look at the file explosion without compaction (rewriting many tiny files into fewer large Parquet files):

    64 Flink tasks * 1 commit/minute * 1,440 minutes/day = 92,160 files/day!
    100 GB/day / 92,160 files = ~1.1 MB per file  (slow S3 LIST/GET, poor Parquet compression)
    
    After hourly compaction to 512 MB targets:
    100,000 MB/day / 512 MB   = ~196 files/day    (fast planning, cheap columnar scans!)
    

    We commit checkpoints every 2-5 minutes, schedule hourly Iceberg rewrite_data_files jobs targeting 256-512 MB files (also compacting merge-on-read delete files), and run daily expire_snapshots (keeping 7 days of time-travel history) plus remove_orphan_files so old unreferenced files don't silently accumulate on S3.

  5. Guarantee idempotency with LSN-guarded merges and soft deletes

    Distributed pipelines always retry after crashes: network hiccups cause producer retries, and restarting Debezium or Flink replays recent WAL changes. Rather than chasing impossible "once-only network packets", we design idempotency ("exactly-once effect": replaying the same event multiple times leaves the exact same final state):

    1. Transport & sink commits: enable Kafka idempotent producers (enable.idempotence=true) and Flink two-phase checkpoint commits to Iceberg so partial failed batches never become visible.
    2. LSN-guarded MERGE with soft deletes in silver: Postgres stamps every WAL change with a strictly increasing LSN (Log Sequence Number). Inside each micro-batch we keep only the highest-LSN change per order_id, and we update silver only when incoming.lsn > stored.lsn. Crucially, we use soft deletes (deleted = true while keeping the row and its lsn): if we physically deleted Order #42 at LSN = 102, a delayed replay of LSN = 101 would find no row and resurrect the deleted order!
    MERGE INTO silver.orders AS t
    USING (
        -- Deduplicate inside the incoming batch first: keep only the newest LSN per order_id
        SELECT * FROM (
            SELECT c.*, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY lsn DESC) AS rn
            FROM bronze_orders_batch AS c
        ) AS ranked
        WHERE rn = 1
    ) AS s
    ON t.order_id = s.order_id
    -- Only apply if strictly newer than what silver already applied; preserve last non-null fields on delete
    WHEN MATCHED AND s.lsn > t.lsn THEN
        UPDATE SET
            status = COALESCE(s.status, t.status),
            amount_cents = COALESCE(s.amount_cents, t.amount_cents),
            lsn = s.lsn,
            deleted = (s.op = 'd')
    WHEN NOT MATCHED THEN
        INSERT (order_id, status, amount_cents, lsn, deleted)
        VALUES (s.order_id, s.status, s.amount_cents, s.lsn, s.op = 'd')
    

    Here is a runnable Python trace proving that replaying older changes after a crash has zero effect:

    def apply_cdc_event(silver_table: dict, event: dict) -> None:
        """Idempotently apply one CDC event keyed by primary key using an LSN guard and soft deletes."""
        pk = event["order_id"]
        existing = silver_table.get(pk)
        # Ignore any duplicate or older out-of-order replay
        if existing is not None and existing["lsn"] >= event["lsn"]:
            return
        last_data = existing["data"] if existing is not None else None
        silver_table[pk] = {
            "lsn": event["lsn"],
            "deleted": event["op"] == "d",
            "data": event["data"] if event["data"] is not None else last_data,
        }
    
    
    stream = [
        {"order_id": 42, "lsn": 100, "op": "c", "data": {"status": "placed", "cents": 3000}},
        {"order_id": 42, "lsn": 101, "op": "u", "data": {"status": "paid", "cents": 3000}},
        {"order_id": 42, "lsn": 102, "op": "d", "data": None},
    ]
    silver = {}
    # Simulate normal processing followed by a connector restart replaying LSN 100 and 101:
    for msg in stream + stream[:2]:
        apply_cdc_event(silver, msg)
    
    print(silver[42])  # {'lsn': 102, 'deleted': True, 'data': {'status': 'paid', 'cents': 3000}}
    

    For nightly SaaS file batches (which have no LSN), achieve idempotency by overwriting the full target date partition (INSERT OVERWRITE ... PARTITION (dt = '2025-09-01')) and tracking processed file checksums in a manifest table.

  6. Evolve schemas safely and tokenize PII before storage

    Schema evolution: register Avro/Protobuf schemas in Glue Schema Registry with FULL_ALL compatibility, meaning every new version is both backward compatible (updated Flink/Spark readers can read historical records) and forward compatible (consumers still running yesterday's code can safely read today's records). In CDC, upstream DB migrations hit Debezium before downstream consumers redeploy, so both directions are vital: - Safe change (optional field with default): adding "coupon_code": ["null", "string"], "default": null works seamlessly in both directions, and Iceberg tracks columns by integer ID rather than name/position so adding, renaming, or widening (int -> long) columns requires zero Parquet rewrites. - Unsafe change protection: block breaking DB migrations in CI, and keep Debezium's errors.tolerance = none so an unexpected breaking change halts the connector task and pages on-call immediately instead of silently dropping source changes (since Kafka Connect dead-letter queues only exist on sink connectors, never source connectors; Flink's dead-letter topic handles bad data values downstream).

    In-flight PII tokenization: Flink and the Spark batch loader strip PII in memory before writing bronze to S3: - Deterministic keyed HMAC tokens: compute HMAC-SHA256(kms_secret_key, normalized_value). Unlike an unkeyed SHA256 — where an attacker can hash all 10^10 possible 10-digit phone numbers in minutes to reverse the hash — an HMAC (Hash-based Message Authentication Code) requires the secret key stored in AWS KMS, while still mapping "Ana@Example.com " to the exact same token across customers and orders so SQL JOIN and COUNT(DISTINCT) keep working! - Vault & right-to-erasure: store raw PII only inside a KMS-encrypted, audit-logged DynamoDB token vault for authorized workflows (such as billing support), keep raw Kafka topic retention short (3-7 days, encrypted at rest), and on a GDPR deletion request purge both the vault entry and the user's rows in silver/gold (followed by snapshot expiry), since a linkable pseudonym still counts as personal data under GDPR.

    import hashlib
    import hmac
    
    
    def tokenize_pii(raw_value: str, secret_key: bytes, key_version: str = "v1") -> str:
        """Create a deterministic, secret-keyed token safe for joins without exposing raw PII."""
        cleaned = raw_value.strip().lower().encode("utf-8")
        mac_hex = hmac.new(secret_key, cleaned, hashlib.sha256).hexdigest()
        return f"tok_{key_version}_{mac_hex[:32]}"
    
    
    kms_key = b"32-byte-secret-loaded-from-aws-kms"
    assert tokenize_pii(" Ana@Example.com ", kms_key) == tokenize_pii("ana@example.com", kms_key)
    
  7. Control cloud costs with storage tiering, TTLs, and file targets

    At 100 GB/day, one year of bronze history is 36,500 GB (36.5 TB). Applying S3 lifecycle storage tiering (using approximate us-east-1 list rates) slashes storage cost by ~70%:

    Storage strategy   Data age      S3 storage class ($/GB-month)        Volume (GB)   Monthly cost
    ----------------   -----------   ----------------------------------   -----------   ------------
    All S3 Standard    Days 1-365    S3 Standard ($0.023)                      36,500          ~$840
    Lifecycle tiered   Days 1-30     S3 Standard ($0.023)                       3,000            $69
                       Days 31-90    S3 Standard-IA ($0.0125)                   6,000            $75
                       Days 91-365   Glacier Instant Retrieval ($0.004)        27,500           $110
                       Total tiered  (instant ms reads; ~$0.03/GB replay)      36,500          ~$254
    

    Pair tiering with strict TTLs (Time-To-Live expiration rules) and compute guardrails: - Safe TTLs: 3-7 days on MSK Kafka topics; 30 days native TTL on inactive DynamoDB serving keys; 7 days on Iceberg snapshots and staging buckets; and 365-day retention on bronze enforced via Iceberg partition DELETE + expire_snapshots (never raw S3 prefix deletion rules, which delete underlying Parquet files behind Iceberg's metadata and corrupt queries!). Also never transition active silver/gold files into asynchronous Glacier tiers that require multi-hour restores. - Scan & compute efficiency: 256-512 MB zstd-compressed Parquet files with date pruning minimize Athena per-TB scan charges; Spot instances run stateless/idempotent Spark compaction and batch jobs at 60-70% discount; AWS Budgets alert on cost per ingested GB.

  8. Chaos-test a stalled CDC connector before it fills production disk

    Why simulate this specific failure? When Debezium stops consuming from Postgres, Postgres's replication slot (the bookmark tracking how far CDC has read) refuses to recycle unread WAL segments on the production database. Left unchecked, a broken analytics connector fills the primary OLTP disk and takes down live customer checkout!

    Chaos game-day protocol (run in load-tested staging first; in production, isolate on a dedicated connector + slot watching a non-critical table): 1. Steady-state hypothesis: silver freshness p95 < 15 min, Postgres disk < 70%, zero duplicate primary keys in silver. 2. Injected faults: pause the Debezium MSK Connect task for 2 hours under realistic 5,000 changes/s write load; then resume it and immediately kill one Flink TaskManager mid-checkpoint during catch-up. 3. Math & expected safeguards verified: - At 5,000 changes/s x ~1 KB WAL per change = 5 MB/s = 18 GB/hour, the slot accumulates 36 GB in 2 hours (144 GB at 20,000/s peak!). Verify our CloudWatch OldestReplicationSlotLag >= 10 GB alarm pages on-call at ~33 minutes. - Verify Postgres max_slot_wal_keep_size is configured as the ultimate circuit breaker so Postgres drops the analytics slot rather than crashing production (and rehearse Debezium's chunked incremental re-snapshot runbook for recovering an invalidated slot). - Verify that after resume + Flink crash recovery, replayed WAL records become no-ops under the s.lsn > t.lsn guard (COUNT(*) == COUNT(DISTINCT order_id) in silver), zero half-written Iceberg files appear, and row counts + checksums match a Postgres read replica within 30 minutes. 4. Hard abort trigger: if source DB disk crosses 80%, immediately resume/drop the test slot and abort.

Intuition & how it works

Think of building a cloud data platform like running a bank's central accounting ledger alongside a fast ATM balance screen. Rather than asking busy bank tellers (your production Postgres databases) to stop every 5 minutes and photocopy their entire filing cabinet, you tap into the bank's sequential receipt tape — CDC (Change Data Capture) reading the database's WAL (Write-Ahead Log) — scrub sensitive customer identities into secret-keyed tokens before anything touches disk, archive every raw receipt in an append-only vault (bronze), maintain one clean up-to-date balance book (silver), and push hot per-customer totals straight to a fast key-value store (DynamoDB) for < 50 ms app lookups.

The obvious beginner setup — running SELECT * FROM orders WHERE updated_at > last_run every 15 minutes and appending raw JSON/Parquet files straight into S3 — breaks quickly at scale. Polling updated_at misses hard DELETEs and intermediate state changes (placed -> paid -> refunded inside 5 minutes), streaming writers create tens of thousands of tiny 1 MB S3 files per day that grind SQL engines to a halt, crash retries create duplicate rows, and storing raw emails in S3 turns every analytics table into a privacy liability.

Trace a single order (order_id = 42 for "Ana@Example.com") across four events to see how every piece protects correctness: 1. Create (LSN = 100, placed) & Update (LSN = 101, paid): Debezium reads both changes from Postgres's WAL into Kafka partition hash(42) mod 64. Flink normalizes Ana's email and replaces it in memory with HMAC-SHA256(kms_key, "ana@example.com") -> tok_v1_9f3a... before writing to bronze Iceberg on S3 and updating Ana's live spend counter in DynamoDB. 2. Delete (LSN = 102, op = 'd'): silver runs an Apache Iceberg MERGE guarded by LSN (Log Sequence Number) (s.lsn > t.lsn), flipping Order 42 to a soft delete (deleted = true, lsn = 102) instead of erasing the row completely. 3. Connector crash & replay (LSN = 100 and 101 arrive again): because silver already holds lsn = 102, the guard 101 > 102 is false — the duplicate replay is ignored with zero side effects (idempotency), and hourly compaction merges tiny 1.1 MB streaming files into clean 512 MB Parquet files.

Key points

  • Match ingestion pattern to source reality: use CDC (Debezium over Postgres WAL) for operational databases to capture inserts, intermediate updates, and hard deletes with near-zero query load; micro-batch (INSERT OVERWRITE by date) for nightly SaaS file drops; and event sourcing only for greenfield services built natively around immutable domain events.
  • Unified medallion lakehouse + split serving: stream MSK -> Flink -> Iceberg bronze -> silver -> gold on S3 (reusing the exact same tokenizer and tables for Spark batch loads), while pushing < 50 ms operational lookups to DynamoDB so app traffic never hits analytical tables.
  • Partition for access patterns & compact aggressively: key Kafka by primary key (64 partitions) for per-row ordering; partition Iceberg by calendar day (days(updated_at) plus optional bucket(16, customer_id_token), never raw high-cardinality IDs); and compact ~92,160 daily 1.1 MB streaming files down to ~200 512 MB Parquet files hourly while expiring old snapshots.
  • Idempotency ("exactly-once effect"): combine idempotent Kafka producers, Flink checkpointed Iceberg commits, an LSN-guarded MERGE (WHEN MATCHED AND s.lsn > t.lsn), and soft deletes so out-of-order replays after a crash can never duplicate rows or resurrect deleted records.
  • Two-way schema evolution & pre-storage PII tokenization: enforce FULL_ALL (both backward and forward) compatibility in Glue Schema Registry so optional fields with defaults roll out without breaking lagging consumers; replace PII in Flink before S3 using KMS-keyed HMAC-SHA256 tokens (preserving SQL joins while preventing rainbow-table reversal of phone numbers) backed by an audited DynamoDB vault and full lakehouse row deletion on GDPR erasure requests.
  • Disciplined cost controls: lifecycle-tier bronze across S3 Standard (1-30d), Standard-IA (31-90d), and Glacier Instant Retrieval (91-365d) to cut 36.5 TB storage from ~$840/mo to ~$254/mo (~70%), set explicit TTLs on Kafka/DynamoDB/snapshots, delete aged Iceberg data through Iceberg commits (never raw S3 lifecycle deletes), and run idempotent compaction on Spot instances.
  • Chaos test the upstream blast radius: simulate a 2-hour stalled Debezium connector (~18 GB/hr retained Postgres WAL at 5,000 changes/s) plus a mid-checkpoint Flink kill to verify the 10 GB slot-lag page (~33 min), max_slot_wal_keep_size production disk protection, duplicate-free LSN replay, and replica-to-silver checksum reconciliation.

Common mistakes

  • Polling WHERE updated_at > last_run on transactional databases: silently drops hard-deleted rows, misses rapid intermediate status transitions, and adds expensive index/table scans to customer-facing databases.
  • Partitioning S3/Iceberg directly by customer_id or user_id: explodes metadata into hundreds of thousands of tiny files per day, ruining query planning and S3 request costs.
  • Streaming to S3 without compaction or snapshot expiry: queries slow down over weeks as 1 MB files and uncompacted delete files pile up, and S3 bills balloon because superseded files are still referenced by old snapshots.
  • Confusing "Kafka/Flink exactly-once" with sink idempotency: if a downstream table simply appends or hard-deletes without a primary-key + LSN check (or partition overwrite), connector restarts and backfills will duplicate or resurrect rows.
  • Hashing emails or phone numbers with plain unkeyed SHA256: 10 billion possible US phone numbers can be brute-forced on a single GPU in minutes without a secret HMAC key; or tokenizing only in gold after plain-text PII has already been persisted in bronze.
  • Using BACKWARD-only schema compatibility on CDC topics: in CDC the source database upgrades first, so older downstream consumers immediately see the new schema and crash unless FORWARD (FULL_ALL) compatibility is also enforced.
  • Putting raw S3 expiration rules or asynchronous Glacier Archive rules on live Iceberg prefixes: deleting or freezing Parquet files behind Iceberg's metadata catalog breaks every query touching the table.

Follow-up questions

  • Suppose a stream-processing bug corrupted a silver table over the past 30 days, while table snapshots are retained for only 7 days. How do you repair silver with near-zero downtime? Because bronze retains 365 days of immutable, already-tokenized CDC events (each carrying its LSN and full post-change row values when REPLICA IDENTITY is configured appropriately), we never need to re-query the production Postgres database. Deploy the fixed code and replay the last 30 days of bronze into an isolated Iceberg branch (the Write-Audit-Publish pattern), running row-count and checksum audits against a Postgres read replica until the branch is verified clean. Finally, pause the live silver merge for a minute, apply the tiny tail of bronze events that arrived during the backfill (the s.lsn > t.lsn guard safely ignores any overlap), atomically fast-forward silver's main pointer to the verified branch, and notify owners of downstream gold jobs that read the affected window.
  • How do you continuously verify that the silver layer has not silently drifted from the operational PostgreSQL databases? Run two automated checks: (1) a CDC heartbeat table in each Postgres DB updated once per minute with the current timestamp so end-to-end ingestion freshness is measured continuously even on low-traffic tables, and (2) a nightly reconciliation job running against a Postgres read replica (never the primary) that compares daily row counts and lightweight order-independent hash sums over (primary_key, updated_at) against non-deleted rows in silver. Combine those with real-time alerts on Kafka consumer lag, Postgres replication-slot lag, and Flink dead-letter counts so drift is caught within minutes rather than by an executive spotting a wrong revenue chart.
  • When would you recommend building an upstream service natively around event sourcing rather than using CDC? Choose event sourcing only when building a brand-new core domain where why a change happened and an auditable replayable ledger are product requirements in their own right — such as double-entry financial ledgers, billing entitlements, or order fulfillment state machines where OrderCancelledByCustomer vs OrderCancelledForFraud triggers completely different downstream workflows that a raw row diff (status: 'paid' -> 'cancelled') loses. Even then, account for the engineering tax up front: application engineers must maintain strict versioned event contracts, build state snapshots for fast reads, and handle bugs via compensating events rather than simple UPDATE fixes.

Follow-up questions

Similar questions

More EY interview questions

All 6 EY questions →