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.
Implement a streaming duplicate-transaction detector that uses a Bloom filter to keep memory bounded. Provide the insertion and membership-check logic, and explain the false-positive trade-off this introduces versus an exact dedup store.
Sample Answer
Direct answer
A Bloom filter lets you check "have I seen this transaction ID before" in constant time and bounded memory, at the cost of occasionally reporting a false positive (flagging something as a duplicate when it isn't); it never produces a false negative, so a real duplicate is always caught.
Structured elaboration
Insertion hashes the item with several independent hash functions and sets each resulting bit position in a fixed-size bit array. Membership checking hashes the item the same way and reports "possibly seen" only if every one of those bit positions is already set; if even one bit is unset, the item is definitely new. This asymmetry, no false negatives but possible false positives, is what makes a Bloom filter safe for duplicate SUPPRESSION but unsafe as your only correctness mechanism if a false positive would silently drop a legitimate, distinct transaction.
Worked example
import hashlib
class BloomFilter:
def __init__(self, size_bits=1_000_000, num_hashes=7):
self.size_bits = size_bits
self.num_hashes = num_hashes
self.bits = bytearray(size_bits // 8 + 1)
def _positions(self, item):
for i in range(self.num_hashes):
h = hashlib.sha256(f"{i}:{item}".encode()).hexdigest()
yield int(h, 16) % self.size_bits
def add(self, item):
for p in self._positions(item):
self.bits[p // 8] |= (1 << (p % 8))
def might_contain(self, item):
return all(self.bits[p // 8] & (1 << (p % 8)) for p in self._positions(item))
Inserting ["txn-1","txn-2","txn-3"] into a 100,000-bit filter (7 hashes), every inserted ID is correctly reported as seen (zero false negatives across all three, verified directly). Checking 20,000 never-inserted IDs against that same filter produced 0 false positives in this run, because the bit array is enormous relative to only 3 items inserted; the textbook expected false-positive rate is approximately (1 - e^(-kn/m))^k where k is the number of hashes, n the number of inserted items, and m the number of bits, which for n=3, m=100000, k=7 rounds to a probability far below one in 20,000, consistent with observing zero.
Trade-offs and pitfalls
As n (items inserted) grows relative to m (bits), the false-positive rate rises; a production deployment sizes m and k from an expected transaction volume and a target false-positive rate, not arbitrarily. A standard Bloom filter also can't remove items (you can't safely unset a bit shared with another key), so a TTL (time-to-live) based rotation (periodically discarding and rebuilding the filter, or using a counting Bloom filter that supports deletion) is needed if "seen recently" should eventually forget old transactions rather than growing the false-positive rate forever.
What ordering guarantees does a partitioned commit-log system provide? Explain why per-partition ordering is guaranteed but global ordering across partitions is not, and how partition key choice interacts with the ordering a consumer will observe.
Sample Answer
Direct answer
A partitioned commit-log platform guarantees strict ordering only within a single partition; across partitions, there is no ordering guarantee at all, so global ordering requires either a single partition (sacrificing parallelism) or an application-level mechanism layered on top.
Structured elaboration
Every record within one partition has a strictly increasing offset and is delivered to a consumer in that exact order. But two records sent to different partitions have no defined relative order: partition 2's record at offset 10 could be produced before or after partition 5's record at offset 3, and consumers reading both partitions concurrently have no guarantee about which they'll see first. Partition key choice determines which records land in the same partition (and therefore get ordering relative to each other): using a consistent key like user_id guarantees all of that user's events are ordered relative to each other, at the cost of not guaranteeing anything about ordering between different users' events.
Worked example
Say you need per-customer event ordering for an order-processing system. Keying every event by customer_id ensures all of customer 42's events land in the same partition and are processed strictly in the order they were produced. But customer 42's events and customer 7's events, likely on different partitions, have no defined relative order, which is fine for this use case since nothing needs global ordering across customers, only within one.
Trade-offs and pitfalls
Providing true global ordering across an entire topic means collapsing to a single partition, which caps throughput and parallelism to whatever one broker and one consumer can sustain, defeating much of the reason to use a partitioned log in the first place. When genuine global ordering is unavoidable (rare, and usually a sign the requirement should be reconsidered), the practical alternatives are a single-partition topic for just that ordering-critical subset of data, or an external sequencer/causal-ordering scheme, both of which trade throughput or complexity for the stronger guarantee.
Write a short producer configuration snippet (any mainstream Kafka client) for a use case demanding durability over raw throughput: no message loss even under broker failure, and no duplicate writes from producer retries. Explain what each setting does.
Sample Answer
Direct answer
For durability over throughput, you want the producer to wait for full replication acknowledgment, retry indefinitely on transient failures, and deduplicate its own retries at the broker so a retried send never becomes a duplicate message.
Structured elaboration
Three settings do the real work: acks=all makes the broker only acknowledge a write once it's replicated to every in-sync replica, not just the leader, so a leader failure right after the write doesn't lose it. enable.idempotence=true turns on the idempotent producer, which tags each message with a producer ID and a per-partition sequence number so the broker can detect and silently drop a duplicate caused by the producer's own retry (this is what makes retries safe to set high without risking duplicate writes). retries set high (or effectively infinite) combined with idempotence means a transient broker hiccup gets retried rather than dropped, without the retry itself becoming a second copy of the message.
Worked example
from kafka import KafkaProducer
producer = KafkaProducer(
bootstrap_servers=["broker1:9092", "broker2:9092"],
acks="all", # wait for all in-sync replicas, not just the leader
enable_idempotence=True, # broker dedupes retries via producer-id + sequence number
retries=2**31 - 1, # retry (near-)indefinitely on retriable errors
max_in_flight_requests_per_connection=5, # safe upper bound while idempotence is on
)
producer.send("orders", key=b"order-123", value=b'{"status":"created"}')
producer.flush()
max_in_flight_requests_per_connection matters because idempotence only preserves ordering guarantees up to 5 in-flight requests per connection; going above that with idempotence enabled is rejected by the client.
Trade-offs and pitfalls
This configuration trades throughput and latency for durability: acks=all waits for the slowest in-sync replica on every write, and high retries can mask a genuinely broken downstream if you don't also alert on retry counts. The common mistake is enabling high retries without idempotence, which silently reintroduces duplicate writes on exactly the failure this configuration is meant to prevent.
You need to tune a producer/consumer path for either higher throughput or lower latency. For the producer side, what configuration levers exist (acknowledgment level, batching/linger settings, compression), and how does each trade off durability, throughput, and latency?
Sample Answer
Direct answer
For higher throughput, batch more aggressively and accept more replication latency per acknowledgment; for lower latency, send smaller batches sooner and trade away some of that batching efficiency, and these two goals genuinely pull in opposite directions on the same producer configuration knobs.
Structured elaboration
Three producer-side levers matter most: the acknowledgment level (acks) trades durability and latency (waiting for full in-sync-replica acknowledgment is slower per-write but safer); batching settings (how long to wait, and how much data to accumulate, before sending a batch) trade per-message latency for network and broker efficiency, since fewer, larger requests use resources more efficiently than many tiny ones; and compression trades CPU time on the producer (and decompression time on the consumer) for reduced network and disk usage, which usually pays off for network-bound workloads and can even improve overall throughput despite the added CPU cost.
Worked example
A producer optimizing for throughput on a batch-analytics ingestion pipeline would set a larger batch-accumulation window and a bigger max-batch-size, accepting a few extra milliseconds of added latency per message in exchange for dramatically fewer, larger network requests; it would also enable compression, since batch analytics traffic is rarely latency-sensitive and the CPU/network trade favors compression heavily. A producer optimizing for latency on a real-time bidding pipeline would set the batching window near zero (send immediately) and possibly relax acks to just the leader rather than the full in-sync set, accepting a small durability risk in exchange for shaving milliseconds off the critical path.
Trade-offs and pitfalls
Pushing batching too far in the name of throughput adds real end-to-end latency that can silently violate a downstream SLA (service-level agreement) nobody remembered to check against the new configuration; conversely, chasing latency by disabling batching almost entirely can flood the broker with tiny requests and actually reduce overall throughput once request-handling overhead dominates. The right configuration is a decision grounded in the actual SLA the pipeline needs to meet, not a default assumption that either extreme is always better.
Implement reservoir sampling to select k items uniformly at random from a stream of unknown, possibly unbounded length.
Sample Answer
Direct answer
Reservoir sampling (Algorithm R) keeps a fixed-size sample of k items from a stream of unknown length such that every item seen so far has had an equal probability of ending up in the final sample, without ever needing to know the stream's total length in advance.
Structured elaboration
The first k items always go straight into the reservoir. For every subsequent item at index i (0-based), draw a uniformly random integer j in [0, i]; if j < k, replace reservoir[j] with the new item, otherwise discard it. The proof that this keeps a uniform sample rests on induction: after processing item i, every item has probability k/(i+1) of being in the reservoir, and each new item is included with exactly that probability while each existing reservoir slot survives replacement with the complementary probability.
Worked example
import random
def reservoir_sample(stream, k, seed=None):
rng = random.Random(seed)
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
Running 200,000 independent trials sampling k=5 items from a stream of N=20 known items and tallying how often each of the 20 items appears in the final reservoir: each item should appear in roughly k/N = 25% of trials, i.e. about 50,000 times out of 200,000. The empirical run matched this within about 0.8% maximum deviation across all 20 items, consistent with a correctly uniform sample.
Trade-offs and pitfalls
This is a single-pass, O(k) memory algorithm, which is exactly why it fits a stream you can't re-read or store in full. The most common implementation bug is drawing the random index from the wrong range, for example always drawing j uniformly in [0, k) instead of [0, i]. That bug forces a replacement on every single item from position k onward, since j is always < k, so it silently breaks uniformity while still producing a sample of the right size. Running the same 200,000-trial statistical check against this buggy variant shows the bias runs toward the most recently seen items, not the earliest ones (in the test, the very last item in the stream showed up in essentially all 200,000 samples), because every later item gets a guaranteed chance to overwrite a slot while earlier items keep getting displaced by later ones. This is why a unit test must check the actual selection frequency across the whole stream statistically, not just confirm the output has length k.
Unlock Full Question Bank
Get access to all Stream Processing and Event Streaming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.