Stream Processing and Event Streaming Questions
Building on event-streaming platforms: Kafka and message queues, event sourcing, partitioning, consumer groups, exactly-once vs at-least-once delivery, and windowing. Covers handling late and out-of-order events, watermarks, and stateful stream operators. The core skill for real-time data engineering.
For a real-time scoring use case, compare embedding a machine learning model's inference directly inside the stream-processing job versus calling out to a separate model-serving service. What drives the choice?
Sample Answer
Direct answer
Embedding a model's inference directly inside the stream job avoids network round-trip latency and an external dependency, favoring the lowest-latency path; calling out to a separate model-serving service centralizes model versioning, scaling, and monitoring for the model independent of the streaming job, favoring operational cleanliness at the cost of added latency and a new failure mode.
Structured elaboration
Embedding the model means the model's weights and inference code ship as part of the stream job's own deployment artifact, so scoring an event never leaves the process, the fastest possible path but meaning every model update requires redeploying the streaming job itself, and the job's own resource footprint (memory, potentially GPU) now includes the model's requirements too. A separate serving call decouples model lifecycle from the streaming job's lifecycle entirely (the model team can deploy a new model version independently, with its own canary and rollback process), and lets the model-serving layer scale and be monitored on its own, at the cost of a network call on the hot path (latency, and a new dependency that can fail or slow down independent of the streaming job's own health).
Worked example
A use case needing sub-millisecond scoring latency at extremely high event volume, where the model changes infrequently, favors embedding: no external call, and infrequent model updates mean the redeploy-to-update cost is acceptable. A use case where the model is updated frequently (multiple times a day, by a separate ML team iterating quickly) and can tolerate a few milliseconds of added latency favors a separate serving call, decoupling the model team's release cadence entirely from the streaming job's own deployment schedule.
Trade-offs and pitfalls
Embedding ties the streaming job's own release cycle to the model's release cycle, which can become a real organizational bottleneck if the model changes far more often than the streaming logic itself does. Calling out to a serving layer adds a genuine new failure mode (the serving layer being slow or down) that the streaming job needs an explicit fallback behavior for (skip scoring, use a cached prior score, or apply backpressure), not silently blocking indefinitely on a stalled call.
A client needs effectively-exactly-once writes into a system of record (for example a ledger or data warehouse) whose sink does not support distributed transactions. Given the available techniques (Kafka transactions with a two-phase-commit sink, idempotent upserts with dedup keys, outbox-plus-CDC, an external coordinator), which would you actually implement for a high-throughput case, and why?
Sample Answer
Direct answer
Given a sink that doesn't support distributed transactions, the most broadly practical choice is idempotent upserts keyed by a deterministic ID derived from the source offset, because it needs no special protocol support from the sink and degrades gracefully; reach for Kafka transactions with a two-phase-commit-capable sink, outbox-plus-CDC, or a fully external coordinator only when the sink genuinely can't express an idempotent write (a pure append-only log with no upsert semantics) or the write itself has side effects that can't be made idempotent.
Structured elaboration
Each option has a distinct failure mode to weigh. Kafka transactions (the producer's transactional.id, initTransactions/beginTransaction/commitTransaction API, paired with consumers reading at isolation.level=read_committed) give exactly-once atomicity across multiple Kafka topics and partitions, and can be extended end-to-end only if the sink itself participates in a two-phase-commit protocol (pre-commit, then a durable commit marker written once the transaction coordinator confirms); this works well when the sink is Kafka itself or a connector explicitly built for it, but most warehouses and ledgers don't expose that kind of commit protocol, and even when they do, the extra coordinator round-trip per transaction adds real latency that hurts at high throughput. Idempotent upserts (keyed by, say, partition + offset) are simple and need no sink cooperation beyond supporting an upsert, but require the write itself to be naturally expressible as "set this row to this value" rather than an unconditional append or an external side effect (charging a card, calling a third-party API) that can't be replayed harmlessly. Outbox-plus-CDC (writing the intended change to a local transactional table, then relaying it via change-data-capture) buys atomicity between a primary write and a downstream event at the cost of an extra moving part (the CDC relay) and added latency. A fully external coordinator (building your own two-phase-commit-like protocol across the source and sink, distinct from Kafka's own built-in transactions) gives a similarly strong guarantee to the Kafka-transactions option but without even Kafka's native support, making it the most operationally complex to build and maintain correctly; it's rarely justified unless neither of the simpler options fits.
Worked example
For a high-throughput case writing aggregated metrics into a data warehouse table: an idempotent upsert keyed by (window_start, dimension_key) is almost always sufficient, since re-computing and re-writing the same aggregate for the same window and key after a recovery produces an identical row, with no need for the warehouse to understand Kafka transactions or a two-phase-commit protocol at all. This is the implementation you'd actually ship for that case; Kafka transactions with a 2PC-capable sink would add a coordinator round-trip to every commit for a guarantee the idempotent upsert already provides more cheaply here, and building a fully external coordinator would add even more operational surface for no additional benefit in this scenario.
Trade-offs and pitfalls
The idempotent-upsert approach breaks down the moment the operation has an external side effect that can't be expressed as a deterministic upsert (sending an email, calling a payment gateway); those cases genuinely need either Kafka transactions paired with a sink that can honor a two-phase commit, a fully external coordinator, or an idempotency-key mechanism enforced at the external system's own API boundary, which the streaming pipeline alone can't manufacture. Choosing the heaviest option (Kafka transactions with a 2PC sink, or a hand-built external coordinator) by default, out of caution, adds real operational and latency cost that's usually unjustified when a simpler idempotent write would have been sufficient for the actual side effect involved.
Design an idempotent sink that writes streaming results into an external database that does not support distributed transactions, ensuring no duplicate rows even when the streaming job restarts and reprocesses.
Sample Answer
Direct answer
Design the sink so writes are naturally idempotent, typically an upsert keyed by a deterministic identifier derived from the source event (its partition and offset, or a stable business key), so a replayed write after a restart produces the identical row rather than a second one.
Structured elaboration
Without distributed-transaction support at the sink, you can't get the streaming job's checkpoint and the sink's write to commit as a single atomic unit; the workaround is to make the write itself safe to repeat. Concretely: derive a deterministic key for every write (source offset, or a natural key already unique to the business event), and express the write as "set this row's value" (an upsert) rather than "append a new row." On a restart-and-replay after a crash, the same source records get reprocessed and re-written with the identical key and value, so the external database simply overwrites the same row with the same content, producing no visible duplicate.
Worked example
A sink writing aggregated hourly revenue per product to a relational table keyed by (product_id, hour): an upsert (INSERT ... ON CONFLICT (product_id, hour) DO UPDATE SET revenue = excluded.revenue) means that if the job crashes after writing hour 14's revenue but before its checkpoint commits, and recovery reprocesses and rewrites hour 14's revenue again, the second write simply overwrites the row with (in this case) the same recomputed value, leaving no duplicate row and no incorrect double-counted total.
Trade-offs and pitfalls
This only works cleanly when the write is naturally expressible as an idempotent upsert; an operation with an external side effect (sending a notification, charging a payment) can't be made idempotent this way without an additional mechanism, typically an idempotency key checked and recorded at the point of the side effect itself, not just at the database write. A common mistake is deriving the upsert key from something that isn't actually stable across a replay (a randomly generated ID rather than the source offset or a genuine business key), which silently reintroduces duplicates despite the upsert pattern looking correct.
Compare Kafka Streams, Apache Flink, and Spark Structured Streaming as stream-processing engines: latency model, state management, exactly-once support, and deployment model. For a given low-latency, stateful use case, which would you recommend and why?
Sample Answer
Direct answer
Kafka Streams is the lightest-weight option, embedded directly in your application with no separate cluster to run, well suited to simpler stateful transformations; Apache Flink offers the most sophisticated event-time and state-management model for genuinely complex, low-latency stateful processing; Spark Structured Streaming trades some latency for tighter integration with the broader Spark batch ecosystem, which matters if your team already lives in Spark for batch workloads. All three can offer exactly-once processing, but the mechanism and how far the guarantee reaches (internal state only, versus all the way to an external sink) differs.
Structured elaboration
Latency model: Flink processes records individually as they arrive (true streaming), giving the lowest latency of the three; Spark Structured Streaming's default micro-batch model processes in small batches, adding latency roughly proportional to the batch interval (its continuous-processing mode narrows this gap but with feature trade-offs); Kafka Streams also processes record-by-record but runs embedded within your own application's JVM rather than on a separate cluster. State management: Flink's RocksDB-backed state and incremental checkpointing is the most mature for very large keyed state; Kafka Streams uses a similar RocksDB-backed local state store, backed by a Kafka changelog topic for durability; Spark's state management is comparatively less flexible for complex custom stateful operators, though sufficient for standard windowed aggregations. Exactly-once support: Kafka Streams achieves it end-to-end (source topic to internal state to output topic) using Kafka's transactional producer under the exactly_once_v2 processing guarantee, since both its input and output are Kafka topics it can wrap in one transaction. Flink achieves exactly-once via its checkpointing mechanism (a Chandy-Lamport-style distributed snapshot) for internal state, and extends it to external sinks through two-phase-commit sink implementations, so the guarantee's reach depends on whether the specific sink connector supports that protocol. Spark Structured Streaming relies on checkpointing plus idempotent or transactional sink writes keyed by micro-batch ID; its built-in sinks (like the Kafka sink) support this, but a custom foreachBatch sink only gets exactly-once if you make the write itself idempotent, since Spark doesn't manage a cross-system transaction for you. Deployment: Flink and Spark both need a dedicated cluster to operate; Kafka Streams needs nothing beyond your application and a Kafka cluster it already talks to, which is a real operational simplicity win for a smaller team.
Worked example
For a low-latency, stateful fraud-scoring use case needing sub-second decisions on complex event-time joins with exactly-once results landing in an external store, Flink is the strongest fit given its event-time model, low per-record latency, and two-phase-commit sink support for extending exactly-once beyond its own state. For a smaller team already running a handful of microservices that just need to maintain a rolling aggregate per key, reading and writing Kafka topics only, Kafka Streams' embedded model removes an entire piece of infrastructure to operate while still getting full exactly-once end to end via exactly_once_v2. For a team whose batch ETL is already deeply invested in Spark and needs streaming mostly to reduce the latency of an existing batch pipeline, Spark Structured Streaming lets that team reuse most of its existing code and operational expertise, provided its sink can be made idempotent.
Trade-offs and pitfalls
Choosing Kafka Streams for a workload that actually needs Flink-grade complex event-time semantics (multiple windowed joins, sophisticated late-data handling) will hit real capability limits; choosing Flink for a simple use case that Kafka Streams could handle adds an entire cluster's worth of operational overhead for no real benefit. A common exactly-once-specific mistake is assuming Spark's exactly-once guarantee automatically extends to a custom sink without checking that the sink write is actually idempotent under batch-ID replay; the most common mistake overall is choosing based on team familiarity alone without checking the specific latency, state-complexity, and exactly-once requirements against what each engine actually supports.
Events can arrive well beyond your allowed-lateness window, sometimes hours or days late. Describe practical strategies for handling this (recompute historical results, side-output late records, tiered storage for rare late arrivals) and the cost trade-offs of each.
Sample Answer
Direct answer
For events arriving well beyond the allowed-lateness window, the practical options are recomputing the affected historical result from scratch, routing the late record to a side output for a separate, deliberate reconciliation pass, or accepting the small inaccuracy and relying on tiered, cheap storage to make eventual full recompute affordable if it's ever needed.
Structured elaboration
Recomputing a historical result (a full or targeted reprocessing of the affected time range) gives the most correct answer but is expensive at scale and disruptive if it touches a live, already-served result; it's the right choice when correctness for that period genuinely matters (financial reporting, compliance) and the affected range is bounded and known. Routing genuinely late records to a side output lets you keep serving fast, mostly-correct real-time results while accumulating the rare late arrivals somewhere queryable, to be reconciled on your own schedule (a nightly batch job that folds them into a corrected historical table) rather than blocking the real-time path. Accepting the inaccuracy (simply dropping records past the allowed-lateness window) is viable when the business cost of being slightly wrong on a rare, small fraction of data is genuinely lower than the cost of building either of the other two mechanisms.
Worked example
For a rare but real case, events arriving 24+ hours late due to an upstream device being offline: routing those to a side-output table, then running a daily batch job that recomputes just the specific historical windows those late events touch and republishes a corrected version of that day's aggregate, keeps the real-time path fast and simple while still eventually reaching correctness, without paying the cost of a full-history recompute for every late arrival.
Trade-offs and pitfalls
Storing raw events indefinitely just in case a very late arrival needs full reprocessing gets expensive at scale; tiering that raw storage to cheaper, slower object storage (accepting a slower recompute in the rare case it's needed) is usually the better trade than either paying for expensive hot storage forever or deleting the raw data and losing the ability to ever correct for late arrivals at all. The choice among these three options should be made explicitly and documented, since "we silently drop very late data" is a defensible business decision but only if stakeholders actually know that's happening, not a decision the team quietly made once and never revisited.
Unlock Full Question Bank
Get access to all 29 Stream Processing and Event Streaming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.