
Real Interview Questions for the Data Engineer at Spotify
NewInterview Q&A
Q&A-1What is eventual consistency?
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 60-second answer
Eventual consistency is a guarantee about convergence, not about what a read returns right now. If writes stop, every replica of a key eventually holds the same value. Until then, readers on different replicas can see different values, and the system makes no promise about which one is newest at a given moment. Strong consistency gives every reader the latest committed value, but each read or write has to coordinate with other replicas to do it. Eventual consistency gives up that ordering guarantee to keep reads and writes local and fast, so a replica accepts a write and propagates it asynchronously.
I'd state one assumption first: the question is about a replicated store or a multi-hop pipeline, and "eventually" means bounded by propagation lag, not a fixed deadline.
Trace, with hypothetical figures
A listener renames a playlist in eu-west. The write lands on the eu-west replica at t=0 and reaches us-east after 900 ms of replication lag.
| t | eu-west replica | us-east replica | read served by us-east |
|---|---|---|---|
| 0 ms | "Road trip" | "Roadtrip" | "Roadtrip" |
| 900 ms | "Road trip" | "Road trip" | "Road trip" |
Between 0 and 900 ms, a read from us-east returns the old name. That is correct behaviour under the contract, not a bug. What the model does not promise is a bound on how long the stale window lasts unless you measure and enforce one.
Where it bites in data engineering
The warehouse is eventually consistent with the event source. If a Kafka consumer group lags 40 minutes behind the listening-events topic, the aggregates built from it are stale by about 40 minutes, then correct once the consumer catches up. Problems start when a downstream job treats a stale state as final. Two common failures:
- A stream-to-batch join reads a dimension table before a country update has landed, so rows get attributed to the old market. The job succeeds, and the error only shows up in a later reconciliation.
- Two regions accept conflicting writes during a partition, and last-writer-wins resolves the conflict by timestamp. With clock skew, the write with the later wall-clock time can be the older logical update, so one write disappears silently.
Detection is what makes this manageable: replication lag metrics per replica, source-to-sink count reconciliation per partition and hour, and key-level spot checks on a sample of recently updated entities.
When not to use it
Balances, payment state, and entitlement checks where a revoked subscription must stop access immediately should not rely on eventual reads. Use a conditional write (compare-and-set on a version), a single writer per key, or a quorum read with R + W > N if the store supports tunable quorums. Session guarantees such as read-your-writes are a middle ground: the user sees their own write immediately while other users may lag.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Explain the CAP Theorem and how it influences database selection in distributed environments.
Reported in Spotify Data Engineer Interview Questions & Guide 2026
The 90-second answer
CAP says that when a network partition splits a distributed system, you can keep serving every request or you can keep every replica in agreement, but not both. Partitions happen, so the real choice is between consistency (C) and availability (A) during a partition. Partition tolerance (P) is not a option you buy. I'd say that first, because candidates who frame CAP as "pick any two" get marked down.
CAP only describes behaviour during a partition. The PACELC extension covers the normal case too: if there is a partition, choose availability or consistency; else, choose latency or consistency. Most of the database decisions I make come from the latency side, because we are not running on a partition most of the time.
What this means for database selection
At Spotify the question is almost never "which database is CAP-correct". It is which store backs which read path, and what the product tolerates when a replica is stale. Some examples I'd use:
| Data | Requirement | Lean |
|---|---|---|
| Play counts for dashboards | Stale by seconds is fine, outage is not | AP, eventual reads |
| Entitlements or billing state | Stale read can grant or deny wrongly | CP for writes, strong reads |
| Playlist serving at the edge | Low p99, slightly old data acceptable | AP with bounded staleness |
| Warehouse tables (BigQuery) | Batch consistency at load time | Not a CAP choice in the usual sense |
The warehouse is a useful trap. It is managed and you do not pick its replication model, so the CAP trade-off sits in the serving layer and in the pipeline that feeds it.
Tunable consistency, with arithmetic
Cassandra-style quorum systems make the choice per query. With N = 3 replicas, a write at QUORUM (W = 2) and a read at QUORUM (R = 2) overlap on at least one replica, since R + W > N. Hypothetical figures: with one replica down, QUORUM still succeeds, so the system stays available, and reads still see the latest acknowledged write. Drop the read to ONE (R = 1) and R + W = 3 is not greater than N = 3 for a stale-prone path, so a read can miss the newest write. That is the trade stated in numbers.
Failure modes and how I'd detect them
- Silent staleness after a partition heals. Detect it with replication lag per region and a canary read that compares a known write.
- Split-brain writes on a leader-based store if failover promotes two leaders. Detect it with duplicate-key conflicts and fencing token rejections.
- Pipelines that assume exactly-once delivery. Event delivery is at-least-once, so the batch job dedupes on event ID. A serving store that accepts duplicates turns a retry into a double count.
When not to reach for the stronger guarantee
A CP store in front of a high-fanout read path will push p99 up and make the service unavailable during a partition that the product could have ridden out. I'd only pay for consistency where a wrong answer costs money or trust.
I'd close the loop by naming the decision explicitly: for each dataset, state the stale-read budget in seconds and the availability target, then pick the store that meets both.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Walk me through the data formats you have worked with, such as Avro and Parquet, and the differences between them.
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 90-second answer
I pick the format by access pattern, not by habit. Avro is row-oriented and binary, with the writer's schema stored in the file or in a registry, so it suits event streams and anything that gets written one record at a time and read whole. Parquet is columnar, so it suits analytical scans where a query touches a few columns out of many and filters on values. In our pipelines events land on Kafka as Avro with schema IDs from a registry, and curated tables in the lake are Parquet. The conversion happens in the batch step, and that boundary is where I check schema compatibility.
How they differ
| Property | Avro | Parquet |
|---|---|---|
| Layout | row-oriented, records stored together | columnar, values per column in row groups |
| Schema | writer schema in container header, or registry ID on the wire | schema in file footer |
| Column pruning | none, every record is read whole | yes, reads only requested column chunks |
| Predicate pushdown | none at file level | min/max statistics per page and row group let readers skip data |
| Schema evolution | reader/writer resolution; new fields need defaults, unions need care | supported by name for added columns in most engines, but type changes are fragile |
| Typical write pattern | append per record, streaming friendly | buffered batches, needs row groups of a useful size |
Trace of a scan. Take SELECT track_id, SUM(ms_played) FROM plays WHERE day = '2024-05-01' GROUP BY track_id over 400 columns. On Avro, every record is deserialised in full and 399 unused fields are decoded and discarded. On Parquet, the reader fetches the track_id and ms_played column chunks, and the footer statistics let it skip row groups whose day range excludes the partition. The I/O difference is the reason the lake stores Parquet; the figures depend on the table, so I measure rather than quote one.
Failure modes I watch for
Small files. A streaming job writing one Parquet file per micro-batch produces thousands of tiny files, the footer overhead dominates, and planners spend their time listing. The fix is compaction into row groups of tens to a few hundred MB, and I alert on average file size per partition.
Schema drift. A producer changes ms_played from int to long and a Parquet reader that matches by position or an old Avro reader fails at read time, long after the write succeeded. The guard is a compatibility mode on the registry (backward or full) enforced at publish, plus a contract test in CI that reads sample files with the new writer and the current reader.
Nullability. Avro union types with null are the usual way to add optional fields safely, but a missing default turns an additive change into a breaking one. I check defaults in review, not just the schema diff.
When not to use them
If the consumer needs point lookups by key, neither format is the answer, and I would reach for a table format or a key-value store. Parquet is a poor choice for sub-minute streaming output without a compaction stage behind it.
If someone asks which is faster in general, I say the question is underspecified: the answer depends on selectivity, column count, compression codec (Snappy and zstd are common defaults in Spark and parquet-mr, with different CPU and ratio trade-offs) and the engine.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4What are the benefits of using the Iceberg table format?
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 90-second answer
Iceberg is a table format, not a storage engine or a query engine. It is a metadata layer over Parquet, ORC or Avro files on object storage, and its benefits come from how that metadata is organised. The main gains are: atomic multi-file commits with snapshot isolation, schema and partition changes that don't rewrite data, time travel and rollback, and one table that Spark, Trino, Flink and others can all read and write through a shared catalog.
At Spotify's scale the two that matter most are partition evolution and safe concurrent writes. Event tables such as listening or playback logs get partitioned by day, and later you want to change that without a full backfill. Iceberg lets you do that because partition specs are recorded per snapshot and old files keep their old layout.
How it works
A table is a tree: a catalog points to the current metadata.json, which lists snapshots. Each snapshot references manifest lists, and manifests list data files with per-column min/max and null counts. A commit writes new manifests and a new metadata file, then swaps the catalog pointer atomically. Readers never see a half-written commit, and a writer that loses the race retries against the new base.
-- Spark SQL, Iceberg 1.x with Spark 3.3+
CREATE TABLE listens (user_id BIGINT, track_id BIGINT, event_ts TIMESTAMP)
USING iceberg
PARTITIONED BY (days(event_ts));
-- later: change the layout without rewriting old files
ALTER TABLE listens ADD PARTITION FIELD hours(event_ts);
-- time travel for a backfill audit
SELECT count(*) FROM listens TIMESTAMP AS OF '2024-05-01 00:00:00';Hidden partitioning matters here. The days(event_ts) transform is stored in metadata, so analysts filter on event_ts directly and Iceberg prunes files. Hive-style tables force callers to know the partition column (dt = '2024-05-01') or get full scans.
| Benefit | Mechanism | Limit to state |
|---|---|---|
| ACID commits | atomic catalog pointer swap, optimistic concurrency | conflicting writers retry; heavy contention on one table serialises |
| Schema evolution | columns tracked by field ID | renames and reorders are safe; type changes are restricted to widening |
| Partition evolution | specs versioned per snapshot | old data keeps old layout until rewritten |
| Time travel and rollback | retained snapshots | only as far back as snapshot expiry allows |
| Data skipping | manifest-level column stats | effective only when the filter column is well clustered |
| Multi-engine access | shared catalog and spec | engine feature support varies by version |
Failure modes I would watch
Streaming ingestion produces many small files, and planning time grows with manifest count. Detect it by watching the file count and planning time per query, then schedule rewrite_data_files for compaction and rewrite_manifests to fold manifests. Snapshots accumulate, so expire_snapshots and remove_orphan_files need a schedule. Without them, storage and metadata cost climb with no visible error. Position and equality deletes (format v2) make row-level updates cheap on write but add read-time merge cost until compaction runs.
When not to use it
If the table is small, single-engine and rarely changes, plain Parquet in a Hive-style layout is simpler to operate. If the workload is mostly point lookups by key, a serving store is the right tool, and Iceberg is a poor fit for it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5How would you explain MapReduce?
Reported in Spotify Data Engineer Interview Guide | DataDriven
MapReduce is a batch model for applying two user functions to a large dataset in parallel across a cluster. The framework handles partitioning, the shuffle between machines, and retrying failed tasks. The user writes a map function and a reduce function, and the framework guarantees that all values for one key reach one reducer. Three phases matter. Map runs once per input record and emits key/value pairs. Shuffle hashes each key to one of R reducer partitions and moves the pairs over the network, sorting by key on the way. Reduce receives one key with its full list of values and emits the result. I'd check the model against a concrete job before going further. Say the input is stream events, each with a track_id and a user_id, and we want plays per track. Hypothetical input across two splits: split 1 holds (A, u1) and (B, u2); split 2 holds (A, u3). Map emits (A,1), (B,1), (A,1). Shuffle sends both A pairs to the same reducer, because hash(A) mod R is fixed for the job. Reduce for A sees [1,1] and emits A=2; reduce for B sees [1] and emits B=1. In code: def map(e): yield (e.track_id, 1) and def reduce(k, vs): yield (k, sum(vs)). The reducer never sees a partial list, which is what makes the result correct regardless of how the framework splits the input. Two refinements come up in every follow-up. A combiner runs the reduce logic map-side on each split, so the shuffle carries one pair per track per split instead of one per event. For a sum or count that is safe; for a median it is not, because the combiner's output is not the reduce's input type. Second, skew. A single viral track can send most of the values to one reducer, and that reducer becomes the straggler that holds the job open. The usual fix is two-stage aggregation: salt the key with a random suffix from 0 to 9, reduce on track_id plus suffix, then strip the suffix and reduce again. You detect skew by comparing reducer input bytes and task durations: a p99 reduce task several times the median, with one partition holding most of the bytes, is the signature. Failure handling is the other thing to state. Tasks are retried on failure, so map and reduce functions must be deterministic and side-effect-free. A map that writes to an external store on each attempt will double-count when a task retries. When not to use it: iterative algorithms such as PageRank pay a full disk write and shuffle per iteration, and interactive queries pay job startup on every run. For those, a dataflow engine that keeps intermediate data in memory or pipelines stages, or a SQL engine, is the better choice. On Spotify's stack, most batch work now runs as Scio pipelines, a Scala API over Apache Beam on Google Cloud Dataflow, rather than hand-written Hadoop jobs. You rarely write the reducer by hand there, but the same three phases sit underneath every GroupByKey, and that is what I would use to reason about a slow or skewed stage.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Walk me through how you would find the most common consecutive three-track sequence in a timestamp-ordered list of Spotify track-play events (user_id, track_id, timestamp), and the number of times it occurred.
Reported in Spotify Data Engineer Interview Guide 2026: Process and Questions
The 90-second answer
I'd treat "consecutive" as adjacent within one user's play history, not adjacent in the global log. Otherwise the last track of user A and the first track of user B would form a triple. I'd also count overlapping windows: in A,B,C,A,B,C the triple (A,B,C) occurs twice. I'd confirm both with the interviewer before writing code.
Algorithm: group plays by user_id, keep each user's order by timestamp, slide a window of size 3 over each list, and count the tuples in a hash map. That is O(N) time and O(distinct triples) for the counter. Ties on timestamp need a deterministic tiebreak such as event_id, or the window contents change between runs.
from collections import Counter, defaultdict
def top_triple(events):
# events: iterable of (user_id, track_id, ts), already globally ordered by ts
by_user = defaultdict(list)
for user_id, track_id, _ts in events:
by_user[user_id].append(track_id) # global order preserved per user
counts = Counter()
for tracks in by_user.values():
counts.update(zip(tracks, tracks[1:], tracks[2:]))
if not counts:
return None
return counts.most_common(1)[0] # ((t1, t2, t3), n)Trace: u1 plays A,B,C,A,B,C gives triples (A,B,C), (B,C,A), (C,A,B), (A,B,C). u2 plays B,C,A gives (B,C,A). Final counts: (A,B,C)=2, (B,C,A)=2, (C,A,B)=1. That is a tie, so the answer must say how ties break. The tie itself is a useful finding to raise.
At Spotify scale
The Python version holds every user's history in memory, which fails at billions of plays. The same logic in a warehouse or Spark:
WITH w AS (
SELECT track_id AS t1,
LEAD(track_id, 1) OVER (PARTITION BY user_id ORDER BY ts, event_id) AS t2,
LEAD(track_id, 2) OVER (PARTITION BY user_id ORDER BY ts, event_id) AS t3
FROM plays
)
SELECT t1, t2, t3, COUNT(*) AS n
FROM w
WHERE t3 IS NOT NULL
GROUP BY t1, t2, t3
ORDER BY n DESC
LIMIT 1;The PARTITION BY is what stops triples crossing user boundaries. Dropping it is the most common bug.
| Concern | Choice | Why |
|---|---|---|
| Ordering | ORDER BY ts, event_id | deterministic on timestamp ties |
| Partitioning | by user_id | keeps windows inside one user |
| Heavy users (bots, automation) | pre-aggregate per user, then merge | one partition with millions of rows stalls the shuffle |
| Repeated same-track plays | decide explicitly | A,A,A yields (A,A,A); filter or keep by definition |
Failure modes
Skew: a few power users dominate one partition. Detect it from the task-level shuffle read sizes and fix with per-user pre-aggregation or a salted key. Silent cross-user leakage: row counts look plausible but the top triple is an artefact of the boundary, so check a few known users by hand. Non-determinism on timestamp ties: the top triple changes between reruns, so the tiebreak column is required.
I'd also return the full top-k with counts, not just one row, because the top triple is often close to second place and that gap is what the product team cares about.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Design a weekly Top 50 tracks playlist per country using the previous week's listening data.
Reported in Spotify Data Engineer Interview Guide 2026: Process and Questions
The 90-second answer
I'd run this as daily batch aggregation feeding a weekly ranking, then an idempotent publish step per country and week. Before designing anything I'd pin three definitions with the interviewer: what counts as a stream, what "previous week" means for a country, and what happens to tracks we can't show.
A stream counts when a user plays at least 30 seconds of a track, excluding playback flagged as bot or looped. Each user contributes at most 20 streams per track per week, so one account on repeat can't buy a chart position. The ranking is by capped streams, with distinct listeners as the tie-breaker.
The week is the country's local calendar week, Monday 00:00 to Sunday 23:59 local time. That way a Monday publish in Brazil and in Japan both reflect a complete week. The job therefore buckets events by local date, not UTC.
Pipeline
- Raw play events land in the lake, partitioned by UTC date and hour.
- A daily job per country-local-date writes partials:
(country, local_date, track_id, user_id, streams). - A weekly job sums the seven daily partials per user and track, then applies the cap. The cap must run after the merge. Capping per day would let a user earn 20 per day, 140 per week.
- The ranker takes the top 50 per country, then applies licensing and availability filters.
- The publisher replaces the playlist's tracks from a stored snapshot row.
WITH weekly AS (
SELECT country, track_id, user_id,
LEAST(SUM(streams), 20) AS capped_streams
FROM daily_partials
WHERE week_start = DATE '2025-03-03'
GROUP BY country, track_id, user_id
)
SELECT country, track_id,
SUM(capped_streams) AS streams,
COUNT(DISTINCT user_id) AS listeners,
ROW_NUMBER() OVER (
PARTITION BY country
ORDER BY SUM(capped_streams) DESC, COUNT(DISTINCT user_id) DESC, track_id
) AS rnk
FROM weekly
GROUP BY country, track_id
QUALIFY rnk <= 50QUALIFY is BigQuery and Snowflake syntax. On engines without it, wrap the ranking in a subquery.
Arithmetic check with hypothetical figures: a track with 1.2 M listeners, each capped at 20, can reach 24 M streams. A heavy user with 300 plays of one track contributes 20, so the cap removes 280 of their plays from the ranking.
Idempotency
The publish key is (country, week_start). A rerun regenerates the same snapshot and replaces the playlist's tracks, never appends. Publishing happens at 06:00 local Monday. Events arriving after 04:00 are counted in the next run's audit log, not in the published chart. Once published, a snapshot is not edited.
Failure modes
| Failure | Detection | Response |
|---|---|---|
| Sparse country, fewer than 50 eligible tracks | row count check before publish | publish fewer tracks and flag it, or fall back to a regional chart |
| Late events past cutoff | late-arrival count per partition | keep the snapshot, log the delta |
| Track unavailable in country | availability join at publish | drop it and take the next rank |
| Bot spike on a few accounts | stream volume z-score per user | exclude the users before the cap |
| Playlist API fails mid-update | publish job status | retry with the same snapshot id |
Batch or streaming? A weekly deadline with a fixed cutoff makes batch the right choice. Streaming buys intra-week freshness that the product doesn't need, at the cost of harder exactly-once semantics on the cap. I'd move to streaming only if the product asked for a live chart.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Here is a SQL query, a CTE with an aggregation, that a colleague wrote to get the average time played. It runs out of memory and returns wrong results. Debug it and correct it.
Reported in Spotify Data Engineer Interview Guide 2026: Process and Questions
The 90-second answer
Before I change anything I'd pin down two things: the grain of the metric (average ms per play, per listener, or per track), and whether track_sessions belongs in this query at all. The likely fault is the join. play_events is joined to track_sessions on user_id alone, so every play row is copied once per session row for that user. That inflates SUM(ms_played) and makes the CTE far larger than its source, which is where the memory goes.
Trace with hypothetical figures. One track has 1,000,000 play rows from 10,000 listeners, and each listener has 40 rows in track_sessions. The join produces 40,000,000 intermediate rows before the GROUP BY collapses them. Each listener's total comes out 40 times too large, so the average is wrong by the same factor.
-- buggy
WITH plays AS (
SELECT e.user_id, e.track_id, SUM(e.ms_played) AS ms
FROM play_events e
JOIN track_sessions s ON s.user_id = e.user_id
GROUP BY e.user_id, e.track_id
)
SELECT track_id, AVG(ms) AS avg_ms_played
FROM plays
GROUP BY track_id;-- corrected: aggregate the base table once, at the grain you report
WITH listener_track AS (
SELECT user_id, track_id,
SUM(ms_played) AS ms_played,
COUNT(*) AS play_count
FROM play_events
WHERE event_date BETWEEN DATE '2025-01-01' AND DATE '2025-01-31'
GROUP BY user_id, track_id
)
SELECT track_id,
COUNT(*) AS listeners,
SUM(ms_played) / SUM(play_count) AS avg_ms_per_play,
SUM(ms_played) / COUNT(*) AS avg_ms_per_listener
FROM listener_track
GROUP BY track_id;Two details matter. First, AVG(ms) over per-listener totals is not the average per play, because listeners with more plays get the same weight as those with fewer. The ratio of sums gives the per-play figure. Second, if track_sessions is only there to filter (for example, premium users), use WHERE user_id IN (SELECT user_id FROM track_sessions ...) or a semi-join. A filter cannot multiply rows, a join can.
How I'd check it. Compare the CTE row count with COUNT(DISTINCT user_id, track_id) on the filtered base table; they must match. Check that SUM(ms_played) equals the source total for the same filter. Run EXPLAIN and look for row estimates that jump at the join. On Spark, a large shuffle spill on one stage is the usual sign of the same fan-out.
When the join is legitimate. If the metric really should be weighted by session, make that explicit in the CTE, pre-aggregate track_sessions to one row per user first, and state the grain in the output column name.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Implement a solution that emits play records with a new field wasRecommended.
Reported in Spotify Data Engineer Interview Guide 2026: Process and Questions
The 90-second answer
I'd set wasRecommended once, when playback starts, from the context the client already holds, and carry it on the play record as a nullable boolean. Three decisions matter: where the flag is decided, how the schema changes without breaking consumers, and what happens to history.
The flag has to come from the start-of-play request. The server can't reconstruct it later from the event stream, because by then the user may have searched, saved or skipped. So the client sends entry_surface on the start request, the producer maps it to a boolean, and the value is frozen on the record. Skips and later actions never change it.
from dataclasses import dataclass
from typing import Optional
PLAY_SCHEMA_VERSION = 4
RECOMMENDATION_SURFACES = {"discover_weekly", "release_radar", "radio", "autoplay"}
@dataclass(frozen=True)
class PlayEvent:
play_id: str # UUID minted once per playback start
user_id: str
track_id: str
started_at_ms: int
context_uri: str
was_recommended: Optional[bool]
schema_version: int = PLAY_SCHEMA_VERSION
def build_play(req: dict) -> PlayEvent:
surface = req.get("entry_surface")
flag = None if surface is None else surface in RECOMMENDATION_SURFACES # old clients: unknown, not false
return PlayEvent(
play_id=req["play_id"],
user_id=req["user_id"],
track_id=req["track_id"],
started_at_ms=req["started_at_ms"],
context_uri=req["context_uri"],
was_recommended=flag,
)Schema: add the field as optional with a null default (Avro union ["null","boolean"], or a new field number in Protobuf). Null means the producer predates the field. False means the producer knew and the track was not recommended. Collapsing the two poisons every ratio you compute.
Trace. The start request for play_id 9a1 from user u_77 carries entry_surface: "discover_weekly". The record is written with was_recommended: true. Four seconds later the user skips. The skip goes to its own event stream and the play row is untouched. A retry of the same start request arrives with the same play_id. The sink upserts on play_id, so there is one play, not two.
| Option | Why not, or why yes |
|---|---|
| Derive in batch from context URI | Works for playlists, fails for radio seeded by a track, and misses autoplay unless you join the session log |
| Server computes from play history | Depends on events that arrive later and can be reordered or dropped |
| Client sends entry surface, producer maps it | Chosen: decided at the moment of intent, one place to change the mapping |
Failure modes and how I'd catch them
- Client version skew: coverage (non-null share) per app version. Alert when a release drops coverage below the prior week's level.
- Autoplay after a recommended track: the spec has to say whether it inherits. I'd count autoplay as recommended and say so in the data dictionary, because otherwise the ratio shifts silently.
- Backfill: don't infer history from context URIs. Old rows stay null and the dashboard reports coverage next to the ratio.
- Duplicate starts: dedupe on
play_id, never onstarted_at_ms, which differs across retries.
Downstream, the metric is count(was_recommended = true) / count(was_recommended is not null), published with coverage beside it so nobody reads a 40% ratio that is really 40% coverage.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Find every user active on 3 or more consecutive days.
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 90-second answer
I'd first pin down what "active" means and what a day is. I'll assume a play event counts as activity, and that the day is the user's local calendar date, which I'd have already computed at ingest from the user's timezone. Then I'd reduce the events to one row per user per day, because a user can play 300 tracks in a day and that must count once. With distinct (user_id, play_date) rows, a user has a run of 3 starting on day d exactly when the distinct day three positions later is d+2. A window function over the deduplicated days does that in a single shuffle.
WITH days AS (
SELECT DISTINCT user_id, play_date
FROM play_events
WHERE play_date >= DATE '2024-03-01' AND play_date < DATE '2024-04-01'
),
windowed AS (
SELECT user_id, play_date,
LEAD(play_date, 2) OVER (PARTITION BY user_id ORDER BY play_date) AS day_plus_2
FROM days
)
SELECT DISTINCT user_id
FROM windowed
WHERE day_plus_2 = play_date + 2 -- date_add(play_date, 2) in SparkTrace. User 7 plays on 1, 2, 2, 4, 5, 6 March. After DISTINCT the days are 1, 2, 4, 5, 6. LEAD(…, 2) gives 1→4, 2→5, 4→6, 5→null, 6→null. Day 1 fails (4 is not 3), day 2 fails (5 is not 4), day 4 passes (6 = 4+2). So user 7 qualifies, with the run 4 to 6. The duplicate 2 March row is removed by the DISTINCT, which is why LEAD counts positions among distinct days and not raw events.
If the interviewer wants the longest streak per user rather than a yes/no, I'd switch to gaps-and-islands: subtract ROW_NUMBER() from the day number to get a constant key per run, group by that key, and keep runs of length 3 or more. That costs one more window and is worth naming, but it answers a different question.
Why this shape. The LEAD version never needs a self-join or a calendar table, and it reads each user's days once. A self-join on day+1 and day+2 would work but multiplies rows for heavy users.
Cost and skew. The window sorts within each user_id partition. Spotify's heavy listeners produce far more distinct days than typical users only within a 31-day window, which is bounded, so the skew is in event volume before the DISTINCT, not in the window. I'd filter to the date range before the window and rely on the DISTINCT to shrink the input first. If the partition is still skewed on a warehouse with fixed slots, I'd check the shuffle stage for a few oversized partitions in the query plan.
Failure modes I'd check.
- Timezone drift: if play_date is UTC for some clients and local for others, a user can appear to skip a day. I'd verify the date column comes from one definition.
- Duplicate delivery: at-least-once ingestion repeats events. The DISTINCT on user and day absorbs this, but a duplicate that crosses midnight in the wrong zone would not, so deduplicate on event id upstream.
- Late events: a day that is still arriving will show a gap. I'd only count days past the watermark, or state that the result is provisional for the last two days.
- Empty days: a user with no events on a day is correctly broken, but a pipeline that drops zero-activity days from a daily snapshot would hide that. Here the source is events, so it doesn't arise, but I'd confirm that before trusting the query.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Write a function to check that a String is parenthetically balanced.
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 60-second answer
First I'd pin the rules down: three bracket pairs (), [], {}; every other character is ignored; an empty string is balanced. Brackets must close in the reverse order they opened, so ([)] is not balanced even though each type appears equally often.
A single left-to-right pass with a stack does this. Push each opener. On a closer, the stack top must be its matching opener, otherwise fail. At the end the stack must be empty. That's O(n) time, and O(d) space where d is the maximum nesting depth, not the string length.
# Python 3.12
def is_balanced(s: str) -> bool:
pairs = {')': '(', ']': '[', '}': '{'}
stack: list[str] = []
for ch in s:
if ch in '([{':
stack.append(ch)
elif ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
return not stackTrace on {[()]} and ([)]:
| char | action | stack after |
|---|---|---|
{ | push | { |
[ | push | { [ |
( | push | { [ ( |
) | top is (, pop | { [ |
] | top is [, pop | { |
} | top is {, pop | empty, return True |
For ([)]: ( pushes, [ pushes, then ) sees top [, which doesn't match, so it returns False at index 2. The check fails before the string is finished, which matters for the error location.
Why not a counter? Keeping one integer per bracket type handles (()) but says )( is balanced only if you forget order. Counters also miss ([)]. A stack is the smallest structure that records order.
Failure modes I'd test:
- Closer first:
)(hits an empty stack on the first closer and returns False. Easy to miss if you check only the final stack. - Leftover openers:
((passes the loop and fails onnot stack. - Non-bracket noise:
a(b)cmust return True. Ignoring unknown characters is a decision to state, not an accident.
Pipeline angle. Log payloads and embedded JSON-like fields often arrive truncated. If the input is streamed in chunks, keep the stack across chunks and only the depth is held in memory, so a multi-gigabyte field doesn't need to be buffered. Validate at the edge, and count rejects by reason so a sudden rise in unbalanced fields shows up as a metric.
Tests I'd write: empty string, single opener, mixed valid and interleaved pairs, and a 10^6-character nested string to confirm linear time.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Walk me through how you would create a Fibonacci sequence.
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 60-second answer
I'd confirm two things first: whether the caller wants the first n terms or the term at index n, and which indexing convention applies (F(0)=0, F(1)=1, or the variant starting 1, 1). I'll assume: return the first n terms, 0-indexed from 0, 1, and reject negative n. Then I'd write a generator, not a list builder, because a sequence feeding a pipeline should not need to be materialised first.
def fib(n):
if n < 0:
raise ValueError("n must be >= 0")
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + bTrace for n=5. Start a=0, b=1. Yield 0, then (a,b)=(1,1). Yield 1, then (1,2). Yield 1, then (2,3). Yield 2, then (3,5). Yield 3, then (5,8). Stop. Output: [0, 1, 1, 2, 3]. The loop yields before updating, so the first value is F(0), not F(1). Getting that order wrong is the most common off-by-one.
Complexity. Time is O(n) additions. Space is O(1) for the generator state. Strictly, the integers grow to about 0.694n bits, so each addition costs O(n) bit operations and the full run is O(n^2) bit work. For n up to a few thousand that is irrelevant. It matters if someone asks for F(10^6), where the output itself is hundreds of kilobytes per term.
Alternatives and when to use them.
| Approach | Cost for term F(n) | Use when |
|---|---|---|
| Naive recursion | O(φ^n), exponential | Never in production; mention it to show you know why it's slow |
| Memoised recursion | O(n) time, O(n) stack and cache | Teaching; hits recursion limit near n≈1000 in CPython |
| Iterative generator | O(n) time, O(1) state | Streaming a sequence |
| Fast doubling | O(log n) multiplications | Only the single term F(n), and n is huge |
Failure modes I'd check. Fixed-width integers: in Java or C with long, F(93) overflows, so the bound must be stated or checked. Zero or negative n: decide between an empty result and an error, and say which. Mutable state shared across calls: a module-level list used as a cache returns stale or extended results to later callers.
In a Spotify data context I'd keep this as a generator and let the consumer decide how many terms to take, since the same pattern works for generating synthetic test sequences or bounded windows over event data.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Walk me through how you would solve a sliding window problem.
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 90-second answer
I'd pin the definition first, then solve it in one pass. Assumptions I'd state: events arrive as (user_id, ts) with ts in integer epoch seconds, the window is 600 seconds, the window is half-open (t - 600, t], and I want the single user with the most plays inside any window, plus that count. I'd ask whether input is already ordered by ts. If not, the sort costs O(n log n) and dominates everything else.
With sorted input, keep one deque per user holding timestamps still inside the window. For each event, append its timestamp, evict anything at or before ts - 600 from the left, and record the deque length. Each timestamp enters and leaves its deque once, so the pass is O(n) time. Memory is bounded by the number of plays any user has in one window, not by the stream length.
# Python 3.11, events sorted by ts ascending
from collections import defaultdict, deque
def busiest_user_window(events, window=600):
recent = defaultdict(deque)
best_count, best_user = 0, None
for user, ts in events:
q = recent[user]
q.append(ts)
while q[0] <= ts - window:
q.popleft()
if len(q) > best_count:
best_count, best_user = len(q), user
return best_user, best_countTrace. Window 600, one user, plays at t = 0, 200, 400, 600 (hypothetical figures).
| ts | deque after append | evict ts <= ts-600 | len |
|---|---|---|---|
| 0 | [0] | none | 1 |
| 200 | [0, 200] | none | 2 |
| 400 | [0, 200, 400] | none (0 is not <= -200) | 3 |
| 600 | [0, 200, 400, 600] | evicts 0 (0 <= 0) | 3 |
The answer is 3. It first reaches 3 at t = 400 from plays at 0, 200 and 400, and stays at 3 at t = 600 from plays at 200, 400 and 600. The play at 0 drops out exactly when the window reaches 600, which is why the boundary matters: an inclusive lower bound would keep it and report 4 at t = 600.
Spark version. On a warehouse-scale table I'd write this as a window function in Spark 3.x SQL, since the job runs where the data already is:
SELECT user_id, ts,
COUNT(*) OVER (PARTITION BY user_id ORDER BY ts
RANGE BETWEEN 599 PRECEDING AND CURRENT ROW) AS plays_10m
FROM play_events;With integer ts, RANGE 599 PRECEDING covers ts >= current - 599, which is the same half-open window as the Python loop, and MAX(plays_10m) finishes the job. The trade-off: this engine sorts within each partition, so a single very active user produces one huge partition and a skewed task. I'd check partition sizes before running it, and pre-aggregate per minute if one user dominates.
Failure modes I'd raise.
- Out-of-order or late events. Mobile clients buffer plays offline and upload hours later. A sorted-input assumption silently miscounts. Mitigation is a watermark, such as accepting events up to 1 hour late, with a counter on dropped records.
- Clock skew between client and server timestamps. Use server receive time for windowing when client clocks are unreliable, and say so.
- Duplicate delivery from at-least-once ingestion. Two copies of one play inflate the count. Deduplicate on
(user_id, track_id, ts)before the window. - Bots or scripted accounts producing thousands of plays per window. The deque grows with them, so cap or flag users above a threshold instead of letting one key dominate memory.
I'd finish by asking whether ties need a rule. Two users with the same peak count means the answer depends on whether I return the first one seen or all tied users.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Implement a function to return the top K tracks by play count efficiently.
Reported in Spotify Data Engineer Interview Experience (2025) - Aced (formerly Exponent)
The 90-second answer
I'd clarify three things first: is the input a stream of play events or an already aggregated table of (track_id, play_count) pairs, is it one machine or a partitioned dataset, and what should happen on ties. Assume events, too big for one machine's memory, ties broken by track_id so output is deterministic. Then the answer is a count followed by a bounded selection: count plays per track in O(N), then keep a min-heap of size K while scanning the distinct tracks, which is O(T log K) for T distinct tracks. Sorting all T tracks would be O(T log T), which is wasteful when K is 50 and T is tens of millions.
import heapq
from collections import Counter
def top_k_tracks(play_events, k):
counts = Counter(e["track_id"] for e in play_events)
# heapq.nlargest keeps a size-k heap internally; key includes track_id for stable ties
return heapq.nlargest(k, counts.items(), key=lambda kv: (kv[1], kv[0]))Python's heapq.nlargest runs in O(T log k) and returns results sorted descending. The Counter pass holds one integer per distinct track, so memory is O(T), not O(N). For a few tens of millions of distinct tracks this is a few GB in Python objects, so at Spotify scale the same logic moves into the warehouse.
Distributed version
On a partitioned store the trap is merging per-partition top-K lists. A track's plays can be split across partitions, so a track that is 3rd globally can be 40th on every single partition and disappear. Two correct options:
- Shuffle by
track_idfirst (hash partition), so each track's full count lives on one partition. Then each partition computes a local top-K and a final merge of P×K rows gives the answer. This is exact. - Compute full counts with a
GROUP BY track_idand applyORDER BY play_count DESC, track_id LIMIT K. Engines such as Spark implement this as per-partition top-K followed by a merge, but that is only exact after the aggregation has finished.
SQL equivalent, with an index-free pass on the warehouse:
SELECT track_id, COUNT(*) AS plays FROM play_events WHERE event_date BETWEEN ... GROUP BY track_id ORDER BY plays DESC, track_id LIMIT 50;
Failure modes
- Double counting from retried ingestion. Play events need a stable event_id, deduplicated before counting, or a retried batch inflates the top of the list.
- Skew. One viral track concentrates work on one reducer. Pre-aggregate with a combiner, or count per partition and sum.
- Late events. If the window closes before late events land, the ranking changes after publication. State the watermark and whether results are final.
- Ties at the boundary. If the K-th and K+1-th tracks tie, the output changes between runs unless the tie-break is part of the key.
Trade-off to state
Exact top-K needs full counts. If an approximate answer is acceptable for a live dashboard, a Space-Saving sketch uses O(K) memory and gives bounded error, but it cannot back a published chart without a stated error bound. I'd use exact aggregation for the weekly chart and the sketch only for real-time monitoring.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Walk me through how you would compute rolling 7-day active users.
Reported in Spotify Data Engineer Interview (2026) | DataDriven
The 90-second answer
First I'd pin down the definitions: a user is active on a day if they have at least one play event with that calendar date, using one timezone for the whole pipeline (UTC unless product says otherwise), and the 7-day window for date d is d-6 through d inclusive. The output is one row per date with the count of distinct user_id in that window. I'd also confirm whether late events are expected, because that decides whether the job reruns recent dates.
The trap is summing daily active counts. A user active on Monday and Wednesday gets counted twice, so a 7-day sum overstates the number. The count has to be distinct over the whole window, not summed across days.
The approach I'd take: first reduce raw events to one row per user per active day, then expand each user-day into the seven window ends it belongs to, then count distinct users per window end.
WITH daily AS (
SELECT DISTINCT user_id, CAST(event_ts AS DATE) AS dt
FROM play_events
WHERE event_ts >= TIMESTAMP '2026-01-01'
),
expanded AS (
SELECT user_id, EXPLODE(SEQUENCE(dt, DATE_ADD(dt, 6), INTERVAL 1 DAY)) AS window_end
FROM daily
)
SELECT window_end, COUNT(DISTINCT user_id) AS active_users_7d
FROM expanded
GROUP BY window_end
ORDER BY window_end;Trace with three users. Alice plays on Jan 1 and Jan 7. Bob plays on Jan 3. Carol plays on Jan 9. Alice's daily rows are (Jan 1) and (Jan 7). Exploding Jan 1 gives window ends Jan 1 to Jan 7. Exploding Jan 7 gives window ends Jan 7 to Jan 13. Bob's Jan 3 row gives window ends Jan 3 to Jan 9. For window end Jan 7, the distinct users are Alice (from both rows, counted once) and Bob. The result is 2, because Carol's Jan 9 activity falls outside the window ending Jan 7. A plain sum of daily counts over those seven days would have given 3 (Alice on Jan 1, Bob on Jan 3, Alice on Jan 7), which double-counts Alice.
Cost. Expansion multiplies rows by 7. If daily distinct user-days are around 200 million a day, a 30-day backfill is about 6 billion rows before expansion and 42 billion after. Two fixes: process in date-partitioned batches with a 6-day overlap so each batch only expands the rows it needs, and for dashboards where ±1% is fine, use HyperLogLog sketches (approx_count_distinct with a stated relative error) and merge sketches across days. Sketches cannot be subtracted, so a rolling window of sketches is recomputed from the seven daily sketches rather than updated incrementally.
Failure modes I'd check. Timezone mismatch between the event timestamp and the date partition shifts users across boundaries. Duplicate events from at-least-once ingestion are harmless here because of the initial DISTINCT, but only if the key is (user_id, date) and not a hash that includes event id. Late events change already-published windows; I'd publish with a watermark and restate the last 7 dates on each run. Sanity checks: the 7-day value must be at least the day's own DAU and at most the sum of the last seven DAU values, and it should move smoothly day to day unless a real event explains a jump.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16How would you calculate Daily Active Users (DAU) given a song_streams table?
Reported in Spotify Data Engineer Interview Questions and Loop Guide | prepare.fyi
The 90-second answer
First I'd pin down the definition, because DAU at Spotify is usually counted per user per calendar day in a fixed timezone, and a stream only counts toward DAU if it is a real play. I'd ask: is a stream a play that passed the 30-second threshold, and which timezone defines the day? Assuming a stream counts when ms_played >= 30000 and days are UTC, the metric is the number of distinct users with at least one qualifying stream on a given date.
The core query is simple. The hard part is making it correct on a table of billions of rows, and handling late-arriving and duplicate events.
-- Spark SQL / BigQuery-style, table: song_streams(user_id, track_id, stream_ts, ms_played, event_id)
SELECT
DATE(stream_ts) AS activity_date,
COUNT(DISTINCT user_id) AS dau
FROM (
SELECT DISTINCT event_id, user_id, stream_ts
FROM song_streams
WHERE ms_played >= 30000
AND stream_ts >= TIMESTAMP '2024-06-01'
AND stream_ts < TIMESTAMP '2024-07-01'
) s
GROUP BY DATE(stream_ts)
ORDER BY activity_date;The inner DISTINCT event_id removes duplicate delivery from at-least-once ingestion before the count, so a retried event does not inflate anything. The outer COUNT(DISTINCT user_id) is exact.
Scale and the exact-vs-approximate choice
At a few hundred million monthly users, COUNT(DISTINCT) over one day's partition is a shuffle on user_id. For a dashboard I'd use an approximate sketch such as HyperLogLog (APPROX_COUNT_DISTINCT, typical relative error around 1 to 2 percent) and say so. For a finance-reported or experiment-denominator number, I'd keep exact counts. A rough trace: 400M users with about 60M qualifying distinct users per day, shuffle partitioned on user_id across 2,000 partitions, so each partition handles about 30k keys. That runs fine as a daily batch.
Incremental computation
Recomputing every day from raw data is wasteful. I'd build a daily table keyed by (activity_date, user_id) with one row per active user, partitioned by activity_date. DAU is then COUNT(*) over one partition. Each day's job reads only the new partition. Late events arrive within a lateness window, say 48 hours, so the job reprocesses the last two partitions and overwrites them, keeping it idempotent.
| Approach | Cost per day | Exact | Handles late data |
|---|---|---|---|
| Raw scan + COUNT DISTINCT | full scan | yes | yes, rescan |
| Daily user table, reprocess 2 days | one partition plus 2 | yes | yes, overwrite |
| HyperLogLog sketch per day | one partition | ~1-2% error | merges across days |
Failure modes to name
- Timezone skew:
DATE()on a UTC timestamp puts evening listeners in the next day for markets east of UTC. Confirm the business definition before shipping. - Bot or test accounts inflating the count: filter on known internal and flagged accounts, and report the filtered count separately.
- Double counting across devices is not an issue here because DAU counts users, not sessions, but a
user_idthat is re-keyed after account merges will split one person into two. Join through the identity mapping before counting. - A silent drop in ingestion shows as a DAU dip. I'd alert on row counts per partition against a trailing seven-day baseline, so a broken pipeline is distinguishable from real engagement loss.
So: define the qualifying stream, dedupe on event_id, count distinct users per UTC day, store a daily user table so the metric is incremental, and keep an exact version alongside any sketch.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Design a real-time data pipeline to stream user-level event data from multiple devices to an analytics dashboard, supporting time-based aggregation and handling late-arriving events.
Reported in Spotify Data Engineer Interview Guide | DataDriven
The 90-second answer
First I'd pin the contract. Events are plays, pauses and skips from phones, desktops and smart speakers. The dashboard needs per-minute counts per track and per user, with a freshness target of about 60 seconds. I'd assume mobile clients batch uploads when offline, so I'd tolerate up to 60 minutes of lateness. I'd ask for peak event rate and whether the dashboard can show approximate distinct-user counts.
Devices post to an authenticated ingest service that stamps server receive time and writes to a Kafka topic partitioned by user_id, so each user's events stay ordered within one partition. A stream processor (Flink, or Dataflow on Beam) reads the topic, drops duplicates on event_id, assigns event time from the device timestamp, and aggregates into one-minute tumbling windows. Each window result is upserted into a serving store keyed by (window_start, dimension), which the dashboard reads. Raw events also land in the data lake so any window can be recomputed.
Late events. Event time is when the device says the play happened. Processing time is when we see it. The watermark is the max event time seen on a partition minus a 2-minute out-of-orderness bound, and the job uses the minimum across partitions. A window fires when the watermark passes its end. Events that arrive after that but within allowed lateness (60 minutes) update the window and re-emit it. Events beyond that go to a side output topic and get folded in by a nightly batch job.
Trace (hypothetical figures). Window 10:00 to 10:01 fires when the watermark reaches 10:01 at 10:03:10, emitting count 412 with version 1. At 10:05:40 an offline phone uploads 9 plays stamped 10:00:30. That is within allowed lateness, so the window re-emits 421 as version 2 and the upsert overwrites version 1. The version column stops an older emit from overwriting a newer one if the two race.
| Concern | Choice | Reason |
|---|---|---|
| Ordering | partition by user_id | per-user state stays local |
| Duplicates | dedupe on event_id, 24 h state | client retries |
| Late data | watermark + 60 min allowed lateness | bounded state |
| Too late | side output + nightly batch | exact totals without unbounded state |
| Serving | upsert on window and dimension, version column | safe re-emits |
Failure modes and detection. A stalled partition holds back the watermark, so no windows fire. Alert on watermark lag per partition and mark idle partitions so they stop blocking. Device clocks drift and push events into the wrong window. Compare device time with server receive time and alert when skew passes a threshold. A viral track makes one key hot in the aggregation. Pre-aggregate per partition before the global keyBy, and watch per-key throughput.
Trade-off. Exact per-user minute counts need a lot of state. If the dashboard can accept approximate distinct users, a HyperLogLog sketch per window is far cheaper and merges across partitions.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18Tell me about a time you disagreed strongly with a technical decision. What did you do?
Reported in Spotify Data Engineer Interview Questions and Loop Guide | prepare.fyi
The 90-second answer
I'll use a pipeline decision from my last role. The team wanted to move our daily listening-aggregates job from hourly Spark batch to a streaming job writing straight into the serving table, because a product team needed same-day numbers. I thought that was the wrong trade. Our input was late-arriving mobile events, sometimes 6 to 36 hours behind, and a streaming job would have pushed late corrections into finalised partitions with no clean way to restate them.
I didn't argue from preference. I wrote down the specific failure: a play recorded at 23:50 local time on a device that reconnected the next morning would land in the wrong day, and the serving table has no retraction path. Then I proposed a middle option: keep the batch job as source of truth, add a 2-hour micro-batch for the product team's freshness need, and mark those figures as provisional until the daily batch closes. I ran both on a week of replayed data and showed the drift numbers side by side.
We shipped the micro-batch with a provisional flag. The streaming design was dropped, and the product team got their number. Two months later a backfill of a bad client release would have corrupted the serving table under the original design; under the shipped design it was a rerun of one partition.
Why this works in a Spotify loop
The interviewer is checking three things: did you disagree on evidence, did you stay useful to the people who disagreed with you, and did you commit once the decision was made. Name the decision owner and what you did after it went the other way.
Trade-offs I'd raise if pressed
| Option | Freshness | Correctability | Operational load |
|---|---|---|---|
| Streaming into serving table | minutes | poor: no restatement path | high: state, watermarks, replay |
| Daily batch | ~24 h | strong | low |
| Hourly micro-batch with provisional flag | ~2 h | strong after batch close | moderate |
Watermark choice matters here: a 1 h allowed lateness would have dropped most of the 6 to 36 h tail, which is why I did not treat streaming as a simple upgrade.
What I would not say
Don't frame the story as being right and them being wrong. Say what you would check next time: I now ask for the late-data distribution before choosing an event-time strategy, and I write the correctability requirement into the design doc before the freshness requirement is discussed.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: