
Real Interview Questions for the Backend Software Engineer at Spotify
NewInterview Q&A
Q&A-1Find the longest substring without repeating characters.
Reported in Get a Job at Spotify: Interview Process and Top Questions
The 90-second answer
I'd use a sliding window with a hash map from each character to the index where it last appeared. I'll assume the input is a Python or Java string of length n, the answer is the length (I'll mention returning the substring at the end), and the alphabet is bounded by the character set, not by n. The window is [left, right]. When right reaches a character already inside the window, I move left just past its previous occurrence. The window never shrinks by more than it grows, so the whole thing is one pass: O(n) time, and O(k) space where k is the number of distinct characters seen.
The detail that matters is the guard. A character's last index can be older than the current window, and jumping left backwards would widen the window over a duplicate. So I only move left when the previous index is inside the window.
# Python 3.12
def longest_unique(s: str) -> int:
last = {} # char -> index of most recent occurrence
left = 0
best = 0
for right, ch in enumerate(s):
prev = last.get(ch)
if prev is not None and prev >= left:
left = prev + 1
last[ch] = right
best = max(best, right - left + 1)
return bestTrace on pwwkew
| right | ch | prev index | left | window | best |
|---|---|---|---|---|---|
| 0 | p | none | 0 | p | 1 |
| 1 | w | none | 0 | pw | 2 |
| 2 | w | 1 | 2 | w | 2 |
| 3 | k | none | 2 | wk | 2 |
| 4 | e | none | 2 | wke | 3 |
| 5 | w | 2 | 3 | kew | 3 |
The answer is 3. If the interviewer wants the substring, store best_start = left whenever best grows and slice at the end.
Why the guard matters
On abba without the prev >= left check, the second a finds prev = 0 and sets left = 1, giving a window bba of length 3. That is wrong: bba repeats b. With the guard, the second a leaves left at 2, and the answer is 2.
Alternatives
The brute force checks every start index and extends while characters are unseen, using a set. That is O(n²) time in the worst case and fine for a few hundred characters, but it's the first thing I'd rewrite. A sliding window with a plain set (remove from the left until the duplicate is gone) is also O(n) amortized and easier to read, at the cost of more removals. I'd pick the map version because it jumps left directly.
Edge cases I'd raise before coding
- Empty string returns 0; a string of one repeated character returns 1.
- Unicode: Python indexes code points, so
lenand the window count code points, not bytes. A UTF-8 byte-based solution gives wrong answers on non-ASCII input. JavaStringindexes UTF-16 code units, so an emoji takes two positions and can split a surrogate pair. Grapheme clusters (combining accents, some emoji sequences) are a separate problem that this algorithm doesn't solve. - If the alphabet is fixed and small (ASCII), an int array of size 128 or 256 replaces the map and removes hashing from the hot path.
Where this fails in production
If this runs over streamed text, the window state has to survive chunk boundaries, so last and left must carry across calls. Forgetting that gives answers that depend on how the input was split. I'd test with random strings against the brute force, plus the abba and pwwkew cases, and a property check that the returned window has no repeats.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Walk me through how you would analyze user website visit logs to find the most frequent sequence of three websites visited by any user.
Reported in Spotify Backend Engineer Interview (No Offer): I had a recruiter call
The 90-second answer
First I'd pin down the inputs. I'm assuming one row per visit with user_id, ts and site (normalised domain), and that a "sequence" means three consecutive visits by the same user, ordered by timestamp. I'm counting total occurrences across all users, not distinct users. Each of those changes the answer, so I'd confirm them. Then the approach is: partition by user, sort each user's visits by time, slide a window of three, and count the triples. The one thing that makes this hard at scale is that the counting must not cross user boundaries.
Single machine, streaming
If the log is already sorted by (user_id, ts), one pass with constant state per user is enough:
from collections import Counter
from itertools import groupby
def top_triple(rows):
# rows: iterable of (user_id, ts, site), sorted by (user_id, ts)
counts = Counter()
for _, visits in groupby(rows, key=lambda r: r[0]):
sites = [site for _, _, site in visits]
counts.update(zip(sites, sites[1:], sites[2:]))
return counts.most_common(1)groupby is what stops a triple spanning two users. Trace: user A visits [news, shop, mail, news, shop, mail]. The windows are (news,shop,mail), (shop,mail,news), (mail,news,shop), (news,shop,mail), so (news,shop,mail) gets 2 from this user. Unsorted input would make groupby split a user into several runs and undercount, so the sort is a precondition, not an optimisation.
Distributed
The log is too big for one machine, so: (1) shuffle by hash(user_id) so each user's whole history lands in one partition, (2) sort within the partition by ts, (3) emit triples and run a partial count per partition, (4) shuffle partial counts by hash(triple) and sum them, (5) take the global max. In Spark that is repartition on user_id, sortWithinPartitions, a mapPartitions for the window, then reduceByKey. Step 4 is the expensive one, because the number of distinct triples can be very large. If you only need the top one, a count-min sketch plus a small heap keeps memory bounded, at the cost of approximate counts that you'd have to report with an error bound.
Alternatives and when not to use them
If you need the answer repeatedly, precompute per-day triple counts and merge them, rather than rescanning raw logs. If users are rare and histories are short, a single hash map of counts beats a sketch. Don't use a global sort of all rows by ts alone, because it doesn't keep users contiguous and costs a full shuffle for nothing.
Failure modes and how I'd detect them
- Heavy users: one bot with 10M visits makes one partition far larger than the rest. Detect it from per-task input size and time skew in the Spark UI. Fix it by treating heavy users separately or by salting.
- Idle gaps chaining unrelated visits: a user who visits at 09:00 and again three days later should not form a triple across the gap. Enforce a session gap, e.g. split when the gap exceeds 30 minutes, and state it as an assumption.
- Duplicate log lines from retried collectors inflate counts. Dedupe on
(user_id, ts, site)before windowing, and check the duplicate rate against a known sample. - Clock skew across collectors reorders visits. Visits with equal or slightly out-of-order timestamps change the triples, so I'd state the ordering source and tolerance.
- URL variants (
www.,httpvshttps, query strings) split one site into several and reshape the top triple. Normalise to registrable domain before counting. - Ties: break them deterministically, such as lexicographically on the triple, so reruns give the same answer.
I'd finish by asking what the answer is for. A one-off report can run as a batch job. A product feature needs an incremental pipeline and an agreed definition of session.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Design a service that stores playlist cover images, including how an auditor would use it. Walk me through the design.
Reported in Spotify Backend Engineer Interview Experience
The 90-second answer
I'd split this into three pieces: immutable image bytes in object storage, a small metadata store that says which image is current for each playlist, and an append-only audit log that records every change. The auditor reads the audit log and the version history. They never touch the image pipeline.
Assumptions I'd state first: covers are uploaded by the playlist owner or by editorial tooling, traffic is read-heavy (every playlist view loads a cover, uploads are a tiny fraction), and auditors need to answer "who changed this cover, when, and what did it look like?" for any date in the retention window.
Storage model
Store each upload as an object keyed by its SHA-256 digest, for example covers/3a9f…e1.jpg. Content addressing makes writes idempotent: uploading the same bytes twice produces the same key, and nothing is overwritten.
| Table | Key fields | Notes |
|---|---|---|
cover_versions | playlist_id, version, sha256, uploader_id, created_at, mime, bytes | append-only, never updated |
playlist_cover | playlist_id, current_version | one row per playlist, the only mutable row |
cover_audit | event_id, playlist_id, actor, action, from_version, to_version, at, request_id | append-only, written in the same transaction |
Upload path
The client gets a presigned PUT URL, uploads to a staging prefix, then calls POST /playlists/{id}/cover with the digest. The server re-hashes the staged object, rejects a mismatch, checks magic bytes instead of trusting the Content-Type header, strips EXIF, and re-encodes to the sizes the apps request. Only then does it promote the object.
The promotion is one transaction: insert the cover_versions row, compare-and-set playlist_cover.current_version from the expected old version to the new one, and insert the audit row. If the compare-and-set fails, two writers raced, and the caller gets 409 and retries against the new version.
Trace
- t0: owner A reads playlist 91 at version 4.
- t1: owner A uploads digest
3a9f…, promotion setscurrent_version = 5where it is 4. Succeeds. - t2: editorial tool uploads
b71c…with expected version 4. The compare-and-set matches zero rows, returns409 version_conflictwith the current version 5. - The audit log holds exactly one new cover event, from version 4 to 5. The rejected write leaves nothing behind.
What the auditor gets
A read-only role with access to cover_audit, cover_versions and signed object reads. Queries are by playlist_id and time range, which the index on (playlist_id, at) serves directly. Each event links to the exact object by digest, so the auditor can show what was live at any moment. For legal holds I'd mark versions with a retention flag that the garbage collector respects. Auditors must not be able to edit or delete audit rows; I'd enforce that at the database permission level, not in application code.
Failure modes
- Orphaned blobs: the object uploads but the metadata transaction fails. A nightly job lists objects with no
cover_versionsrow older than 24 hours and deletes them. Detection: a count of unreferenced objects per day. - CDN serving the old cover after a replace: versioned URLs (
…/v5.jpg) avoid purges entirely. Detection: the cover age metric at the edge. - Audit gap: the app writes the version but drops the audit row. Because both happen in one transaction, this cannot happen. A reconciliation job still compares
playlist_coveragainst the latest audit event per playlist and alerts on any mismatch.
When not to build this
If the business only needs the current cover and no history, a single row with an object key is enough. The versioned design earns its cost only because the auditor requirement exists.
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 should happen when an upload or the processing step breaks halfway?
Reported in Spotify Backend Engineer Interview Experience
The 90-second answer
A listener should never reach half a track. The upload and the processing are separate state machines, and a track becomes visible only at READY. A broken upload resumes from the last committed part. A broken processing stage retries that stage alone, against the same input, and writes to a key that a retry can overwrite safely. Anything that exhausts its retries moves to FAILED with a reason, so nobody is left owning a track stuck in limbo.
Assumptions: uploads are multipart into object storage with strong read-after-write consistency (S3 has offered this since December 2020); each processing stage is a pure function of its input checksum; workers hold leases with heartbeats rather than assuming a dead worker stays dead.
Trace, with hypothetical figures: a 60-part upload fails at part 37 at 14:02. Parts 1 to 36 are committed. The client calls GET /uploads/{id}, receives next_part: 37, and re-sends 24 parts instead of 60. The server keeps received parts until CompleteMultipartUpload succeeds. A bucket lifecycle rule aborts incomplete uploads after 7 days, so orphaned parts stop costing money.
Processing: transcode job for track t_91, stage transcode_320, input checksum c3a9. Worker A takes a 5 min lease, heartbeats every 30 s, and crashes after 2 min. The lease expires and worker B picks the job up, writes tracks/t_91/transcode_320/c3a9.ogg, then commits with a conditional update: UPDATE stage SET status='done', version=4 WHERE track_id='t_91' AND stage='transcode_320' AND version=3. If worker A wakes and tries to commit, the version check rejects it. Writing the same key twice is harmless because the bytes are identical, and the conditional update stops a stale worker from overwriting a newer result.
| Failure | Behaviour | Detection |
|---|---|---|
| Upload stalls mid-part | client resumes from next_part | upload age, parts received vs expected |
| Worker dies mid-stage | lease expires, another worker retries | heartbeat gap over 2 min |
| Transient error (timeout, storage 503) | retry with exponential backoff and jitter, max 5 attempts | retry count per stage |
| Poison input (corrupt file, decoder crash) | after 5 attempts to DLQ, track FAILED with reason=decode_error, user asked to re-upload | DLQ depth, FAILED rate per release |
| Partial output written | never referenced, because READY is set only after every stage completes | orphan sweep in object store |
I would not retry a decode failure indefinitely. Separate retryable errors (network, throttling) from permanent ones (corrupt input), because retrying a permanent error only burns workers. For monitoring, watch the age of the oldest track in PROCESSING. A p99 of 90 s with a tail stuck at 20 min is the signal to act on, and the mean hides 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-5Find the median of all sliding windows of a given size within an array of numbers.
Reported in Spotify Backend Engineer Interview (No Offer): I had a recruiter call
The 90-second answer
I'd clarify three things first: whether the window size k is at most n, whether values can repeat, and whether the output for even k may be a float. Assume 1 <= k <= n, duplicates are allowed, and the median of an even window is the mean of its two middle values. Sorting every window costs O(n k log k). I'd keep two heaps instead: a max-heap lo for the lower half and a min-heap hi for the upper half, with len(lo) equal to len(hi) or one more. For odd k the median is lo[0]. For even k it is (lo[0] + hi[0]) / 2. Each step is O(log k), so the whole pass is O(n log k).
The catch is removal. When a value leaves the window, a heap can't delete an arbitrary element cheaply, so I use lazy deletion: record the value in a counter and pop it only when it reaches the top.
from collections import Counter
import heapq
def sliding_medians(nums, k):
lo, hi = [], [] # lo stores negatives (max-heap), hi is a min-heap
gone = Counter() # values removed from the window but still in a heap
n_lo = n_hi = 0 # live counts per side
def prune(h, sign):
while h and gone[sign * h[0]]:
gone[sign * h[0]] -= 1
heapq.heappop(h)
def rebalance():
nonlocal n_lo, n_hi
prune(lo, -1); prune(hi, 1)
if n_lo > n_hi + 1:
heapq.heappush(hi, -heapq.heappop(lo)); n_lo -= 1; n_hi += 1
elif n_lo < n_hi:
heapq.heappush(lo, -heapq.heappop(hi)); n_hi -= 1; n_lo += 1
prune(lo, -1); prune(hi, 1)
def add(x):
nonlocal n_lo, n_hi
prune(lo, -1)
if lo and x > -lo[0]:
heapq.heappush(hi, x); n_hi += 1
else:
heapq.heappush(lo, -x); n_lo += 1
rebalance()
def remove(x):
nonlocal n_lo, n_hi
prune(lo, -1)
gone[x] += 1
if x <= -lo[0]:
n_lo -= 1
else:
n_hi -= 1
rebalance()
out = []
for i, x in enumerate(nums):
add(x)
if i >= k:
remove(nums[i - k])
if i >= k - 1:
out.append(float(-lo[0]) if k % 2 else (-lo[0] + hi[0]) / 2)
return outTrace. Take nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3. Adding 1 and 3 gives lo = [1], hi = [3]. Adding -1 sends it to lo, which now has two elements, so rebalance moves the top 1 to hi. The sides are lo = {-1}, hi = {1, 3}, and the first window's median is lo's top plus the rule for odd k: 1.0. The output for the full input is [1.0, -1.0, -1.0, 3.0, 5.0, 6.0], which matches the reference result for this input (LeetCode 480).
Failure modes I'd check for:
- A missing
prunebefore reading a heap top returns an expired value. Detect it by comparing against a brute-forcesorted(window)on random inputs with many duplicates. - Lazy-deleted entries accumulate if prune never runs on the top. Heap size then grows past
k. Assertlen(lo) + len(hi) - sum(gone.values()) == kin tests. - Averaging two large integers overflows in fixed-width languages. In Java or C++ use
a + (b - a) / 2onlong. In Python it's exact, but a float result loses precision above 2^53.
When not to use it. For small k, keeping a sorted list with bisect.insort and bisect removal is O(n k) worst case but has a smaller constant, and it's easier to read under pressure. For very large k with many small updates, the two-heap approach is the right one. I'd say which regime applies before writing code.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Design a data structure to calculate the moving average of a stream of numbers.
Reported in Spotify Backend Engineer Interview (No Offer): I had a recruiter call
The 60-second answer
Before writing code I'd pin two things: is the window the last k values (count-based) or the last T seconds (time-based), and do values arrive in timestamp order? I'll assume count-based with fixed k and in-order arrivals, then say how the time-based version changes.
A ring buffer plus a running sum gives O(1) time per value and O(k) memory. Keep the buffer, a write index and the sum. Once the buffer is full, subtract the value being overwritten and add the new one.
class MovingAverage:
def __init__(self, k: int):
if k <= 0:
raise ValueError('window must be positive')
self._k = k
self._buf = [0.0] * k
self._n = 0 # values held, capped at k
self._i = 0 # next write slot
self._sum = 0.0
def add(self, x: float) -> float:
if self._n == self._k:
self._sum -= self._buf[self._i]
else:
self._n += 1
self._buf[self._i] = x
self._sum += x
self._i = (self._i + 1) % self._k
return self._sum / self._nTrace with k=3 and inputs 1, 2, 6, 3:
- add 1: n=1, sum=1, avg 1.0
- add 2: n=2, sum=3, avg 1.5
- add 6: n=3, sum=9, avg 3.0
- add 3: full, slot 0 held 1, so sum = 9 - 1 + 3 = 11, avg 11/3 ≈ 3.67 (window is 2, 6, 3)
| Approach | add cost | memory | when to use |
|---|---|---|---|
| recompute over a slice | O(k) | O(k) | k is tiny and the code must be obvious |
| ring buffer + sum | O(1) | O(k) | the default |
| time window: deque of (ts, x) + sum | amortised O(1) | O(events in window) | the window is in seconds, not items |
| EWMA | O(1) | O(1) | you want decay, not a hard window |
Failure modes
- NaN poisoning. One NaN added makes the sum NaN permanently, even after it is evicted, because NaN minus anything is NaN. Reject non-finite input at the boundary.
- Float drift. The running sum accumulates rounding error over a long-lived stream. For latency metrics, store integers (microseconds), or recompute the sum from the buffer with
math.fsumevery k adds so the error is bounded to one window. - Concurrency.
addupdates three fields together. Two threads interleave and corrupt the index. Use one writer per window, or a lock. At high per-key rates, shard by key so each shard has a single writer.
For a time window, such as p95 playback-start latency over the last 60 s, store (timestamp, value) pairs in a deque, subtract on eviction, and evict in both add and the read path so an idle stream still decays. Memory then scales with event rate. A hypothetical 2,000 events/s over 60 s is 120,000 entries per window, so one window per track and one window per service are very different costs. I'd state that number before anyone asks.
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 URL shortening service or a basic messaging queue.
Reported in Spotify Backend Engineer Interview Questions & Guide 2026
The 90-second answer
I'd take the URL shortener. Before drawing anything I'd confirm three numbers with the interviewer: write rate, read-to-write ratio, and how long links must live. Hypothetically: 1,000 new links per second at peak, a 100:1 read ratio, so 100,000 redirects per second, and links kept for 5 years. That is roughly 430 million new rows a day at the peak rate if sustained, so the store is a key-value or wide-column system with a cache in front, not a relational table on one primary.
The core is the key. A 7-character base62 code gives 62^7 = 3,521,614,606,208 (about 3.5 trillion) values, which is ample. I'd generate keys from a counter rather than random strings, so writes never need a collision check against the store.
import string
ALPHABET = string.ascii_letters + string.digits # 62 chars
def encode(n: int) -> str:
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out)) or "0"Each app host leases a block of 1,000 IDs from a central allocator (a sequence in the database or a coordination service), so creates need no cross-host round trip. The cost is that codes are guessable and sequential. If that matters, shuffle the ID with a reversible permutation (a keyed Feistel network or a bijective mix) before encoding.
Write path. POST /links validates the URL (scheme allowlist, length cap, a malware or abuse check that can be asynchronous), takes the next ID, writes code -> url, created_at, expires_at, and returns 201. A custom alias is different: it needs a unique constraint on the code column, and a duplicate returns 409.
Read path. GET /{code} checks the cache first, then the store, and redirects. The status code is a real decision:
| Choice | Browser caching | Click analytics | Use when |
|---|---|---|---|
| 301 | Cached, later hits skip your servers | Lost after first hit | Pure link rewriting, no stats needed |
| 302 | Not cached by default | Every hit reaches you | Stats matter, which is the usual product need |
I'd default to 302 and keep analytics off the redirect's critical path: emit a click event to a queue and return the redirect without waiting for it.
Failure modes I'd name.
- A viral link becomes a hot key. A single cache entry takes all reads. Detect it with per-key request rate; mitigate with a local in-process cache with a short TTL for hot codes, and request coalescing on miss so one miss fills the cache rather than a thousand.
- Cache outage pushes 100,000 reads per second onto the store. Size the store for that fallback or it falls over with the cache. Watch the store's p99 read latency and cache hit ratio together; a falling hit ratio shows the failure before errors do.
- ID block allocator is down. Hosts keep serving from their leased blocks, but a host restart loses the unused part of its block. That wastes IDs, which is harmless at 3.5 trillion, so I'd accept it rather than add a second coordinator.
- Expired links still resolve from cache. Put the TTL on the cache entry equal to the link's remaining life, or the cache outlives the business rule.
If they pick the queue instead, the same reasoning applies: partitioned log, consumer offsets, and at-least-once delivery with idempotent consumers. I'd only switch if the interviewer wants delivery guarantees explored more than storage.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Explain TCP versus UDP.
Reported in Spotify Backend Engineer Interview Questions | Dataford
The 90-second answer
TCP gives you an ordered, reliable byte stream. It sets up a connection, numbers every byte, retransmits what gets lost and slows down when the network is congested. UDP gives you independent datagrams with no connection, no retransmission and no ordering. It adds only a checksum, so the application decides what loss means. I pick TCP when a missing or reordered byte corrupts the result (HTTP bodies, database protocols, uploads). I pick UDP when a late packet is worth less than a fresh one (live telemetry, voice, games) or when I need to build my own reliability on top.
The cost of TCP is latency before the first byte. One round trip for the handshake, and another for TLS 1.3 on top of it.
| TCP | UDP | |
|---|---|---|
| Header | 20 bytes minimum | 8 bytes |
| Setup | 1 RTT (SYN, SYN-ACK, ACK) | none |
| Delivery | ordered, retransmitted | best effort, no retransmit |
| Boundaries | byte stream | one datagram per send |
| Congestion control | built in | none; the app must add it |
Trace: fetching a 2 MB audio segment at 80 ms RTT over HTTPS
TCP: SYN at t=0, SYN-ACK at 80 ms, ACK plus TLS 1.3 ClientHello sent together, server flight back at 160 ms, request at 160 ms, first byte at about 240 ms. QUIC (over UDP, HTTP/3) merges transport and TLS into one round trip, so the first byte lands near 160 ms, and 0-RTT resumption can remove it entirely (RFC 9000). These figures are hypothetical and assume no loss.
Failure modes I watch for
- TCP head-of-line blocking. One lost segment stalls every stream behind it. Detect it with retransmit rate and p99 latency per connection (
ss -tishows retransmits and RTT). - Retransmission timeouts that are too slow. RFC 6298 sets a 1 s RTO floor; Linux uses 200 ms. On a lossy mobile link that difference is visible.
- UDP silent loss. Nothing signals a drop, so I count sequence gaps on the receiver and alert on the gap rate.
- UDP fragmentation. A datagram above the path MTU (usually 1500 bytes on Ethernet) gets fragmented, and losing one fragment loses the whole datagram. I keep payloads under about 1200 bytes unless I have checked the path.
- TCP buffer bloat. Large send buffers hide congestion and inflate latency. Watch send-queue depth, not only throughput.
Where this lands at Spotify
Metadata calls, playlist writes and playback-state changes need every byte and every order, so they run over TCP with TLS. Anything where a stale update is worse than a dropped one is a candidate for UDP or QUIC, but only with an explicit loss policy and a metric that shows the loss rate. I would confirm with the owning team which transport their clients already negotiate before proposing a change.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Walk through the On-Call Case Study: Debugging a Misbehaving Production Server.
Reported in Spotify Backend Engineer Interview Experience
The 90-second answer
First I'd establish the symptom and the blast radius before touching anything. I'd ask: which signal fired (5xx rate, p99 latency, memory, queue depth), since when, is it every pod or a subset, and did anything deploy or change config in the last hour. Then I'd stop the bleeding if it's cheap to do so: roll back the last deploy, or drain the bad instance from the load balancer so the rest of the fleet keeps serving. Diagnosis comes second, because a misbehaving server that still takes traffic is a customer problem every minute.
Once traffic is safe, I work from the outside in. Dashboards first (request rate, error rate, latency per endpoint and per downstream dependency), then one instance compared against its healthy peers. A single bad pod out of forty usually means local state; a fleet-wide shift usually means a dependency or a change.
Worked trace (hypothetical figures)
At 14:05 p99 on the playlist-read endpoint rises from 120 ms to 2.4 s. Error rate goes from 0.4% to 9%. Fleet-wide CPU is flat, so this is not compute saturation. Per-dependency latency shows the metadata store p99 unchanged, but the HTTP client wait time on one pool climbs and sits at the cap. The pool is configured at 20 connections per pod. Thread dumps on a sampled pod show 60 threads parked in ConnectionPool.acquire. So requests queue for the pool, not the database. Why the pool is exhausted: a downstream call inside the request path now takes 1.8 s instead of 40 ms, so each connection is held 45 times longer. Throughput per pod does not change, yet concurrency demand multiplies.
The cause lines up with a 13:58 change that raised a timeout on that downstream from 500 ms to 5 s. The timeout change is the trigger; the pool sizing and the lack of a circuit breaker are why it cascades.
What I would do and say
Roll back the timeout, watch pool wait time return to near zero, then fix the design: a timeout budget per request that is shorter than the caller's own deadline, a circuit breaker on the downstream, and bulkheads so one dependency cannot consume the whole pool.
Failure modes I'd check for
Retry amplification: if clients retry on timeout, load on the slow dependency can double or triple. I'd check retry counters and whether retries carry a budget. GC pauses on one JVM instance: visible in GC logs as long stop-the-world pauses on that pod only, which points at local heap pressure rather than the shared system. Noisy neighbour on the host: CPU steal time on one node, checked against the instance's host metrics.
How it gets detected next time
Alert on pool wait time and on the gap between downstream latency and downstream timeout, not only on error rate, which lags by minutes. Error rate tells you users are hurting; pool wait tells you why before they do.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Describe how you would approach debugging a production incident involving high latency.
Reported in Spotify Backend Engineer Interview Questions & Guide 2026
The 90-second answer
First I pin down scope: which endpoint, which percentile (p50, p99 or both), since when, and whether it is one region, one service or all traffic. If users are hurting now, I mitigate before I diagnose. That usually means rolling back the last deploy or flipping the feature flag that changed, then shedding non-critical traffic if a dependency is saturated. I only go looking for root cause once the bleeding has stopped or I know the rollback will not change the picture.
Then I localize. Latency is a sum of time spent in each hop, so I walk the request path with distributed traces and compare p99 per span against the pre-incident baseline. The span that grew is the suspect. Service-level RED metrics (rate, errors, duration) tell me which service; saturation metrics (pool wait, queue depth, CPU throttling, GC pause time) tell me why.
Why tails explode. A request that fans out to 20 downstream calls, each with a p99 of 50 ms, has a probability of at least one slow call of 1 - 0.99^20, about 18%. So the caller's p99 is driven by the tail of its dependencies, not their averages. This is why a small slowdown in one shared dependency shows up everywhere.
Worked trace (hypothetical figures). At 14:05, after a deploy, playback-api p99 moves from 120 ms to 900 ms while p50 stays at 45 ms. That split is the first clue: a median that holds with a blown tail points to queueing or a subset of slow calls, not a uniformly slower code path. Traces show the catalogue call spending 700 ms waiting for a connection, not executing. The client pool is capped at 20 and all 20 are busy. The deploy added a metadata lookup inside a loop, so each request holds connections roughly three times longer. Fix: revert the loop, then fix the pool sizing and the timeout separately.
| Symptom | Likely cause | Check |
|---|---|---|
| p50 and p99 both up | slower code path or dependency | span diff against baseline |
| p50 flat, p99 up | queueing, pool wait, GC pauses | pool wait time, GC logs |
| latency up with error rate | timeouts and retries | retry count, timeout config |
| step change at deploy time | regression in the release | diff of changed calls |
| gradual rise under load | saturation, lock contention | CPU throttling, thread dumps |
Failure modes I watch for. Retry storms: three retries on a struggling dependency can multiply its load by up to 4x, which deepens the outage. Check that retries use jittered backoff and a budget. Missing timeouts: a call with no deadline holds a thread indefinitely and the pool drains. Cache stampede: an expiring hot key sends every request to the origin at once. Noisy neighbours on shared hosts show up as CPU steal or throttling without any code change.
What I would leave behind. A dashboard on the specific span and pool metric, an alert on pool wait time rather than only on end-to-end p99, and a note in the runbook on the rollback path. The postmortem should name the mechanism, not just the commit.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11How do you use AI tools today, at work and in personal projects?
Reported in Spotify: How You Use AI Tools as an Engineer and Drive Their Adoption on Your Team
The 90-second answer
I use AI tools for the narrow parts of backend work where I can check the output quickly, and I treat every result as a draft I have to verify. At work that means generating test cases for edge cases I might skip, a first-pass read of my own diffs before a human reviews them, drafting migration plans and runbook sections, and getting a quick explanation of code in services I don't own. I don't use them to make design decisions. In personal projects I use them to get up to speed on an unfamiliar library and to challenge a design I've already sketched, then I check the claims against the official docs.
| Task | Where AI helps | What I verify |
|---|---|---|
| Unit and edge-case tests | Enumerating boundary inputs | Tests fail on a deliberately broken version of the code |
| Diff review before PR | Catching missed error paths | Reviewer still signs off on the same lines |
| Library usage | Quick sketch of an API call | Signatures and defaults checked against the vendor docs and changelog |
| Runbook drafts | Structure and first wording | Every command run in staging |
Where it goes wrong. The failure I see most is plausible code that is subtly wrong. In one case I asked for a retry wrapper around POST /orders. The first draft retried on timeout without an Idempotency-Key, so a slow response could create two orders. The duplicate-order contract test caught it before review. The fix was to make the key mandatory in the wrapper's signature so the mistake can't compile. Generated code also tends to invent method names that don't exist in the version we pin, so I compile and run tests before reading the output closely.
Driving adoption on the team. I didn't start with a tool rollout. I started with three tasks where the check is cheap, then wrote a short shared prompt file in the repo with our conventions: error codes, logging fields, test style, and what not to paste. Over two sprints I compared review turnaround on PRs with generated tests against the prior two sprints. Turnaround dropped, but the sample was small and I said so rather than presenting it as a result. The guardrails mattered more than the prompts. No customer identifiers, no credentials, and no unreleased design docs go into any tool that security hasn't approved. I also made it explicit that a reviewer who didn't use AI on a change should still read it, so the team doesn't drift into approving code nobody has actually thought through.
If I were asked to go deeper, I'd talk about where I'd stop using these tools: anything involving concurrency, money movement, or auth logic, where a plausible wrong answer costs more than the time saved.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Tell me about a project where the requirements were unclear at the start or kept changing while you worked on it.
Reported in Spotify: Staying Productive When Project Requirements Were Unclear or Kept Changing
The 90-second answer
I'll use a playlist follower-count service I owned for about five months. The brief said "expose follower counts per playlist, near real time." Two weeks in, product clarified that a lag of up to 60 seconds was fine for ordinary playlists. Editorial then asked for exact counts on featured playlists. Those are two different consistency contracts, and I had built for neither.
I stopped estimating and wrote the open questions down with an owner and a date. That turned vague requirements into things I could wait for or push on.
| Open question | Owner | Answer | Resolved |
|---|---|---|---|
| Staleness for ordinary playlists | PM | 60 s acceptable | week 2 |
| Exact counts for featured playlists | Editorial lead | yes, for about 300 playlists | week 3 |
| Retention of raw follow events | Data platform | 90 days, down from indefinite | week 6 |
The design choice that made changes cheap was keeping the follow/unfollow event log as the source of truth, append-only and keyed by (playlist_id, user_id, seq). Counts are derived from it. Ordinary playlists read a materialized counter that is flushed every 60 seconds. Featured playlists get an exact count computed from the log with a bounded scan. When retention dropped to 90 days, the stored counters were unaffected, but exact recounts became impossible past that window. I made that explicit in the response with count_precision: "exact" | "approximate" and recount_window_days: 90, so clients never had to guess.
The flush cadence also decided the write load. Hypothetical figures, labelled as such: at 4,000 follow events per second, per-event counter writes would be 240,000 per minute. Flushing 16 shards every 60 seconds cuts that to 16 writes per minute, at the cost of up to a minute of staleness, which is the trade product had already accepted.
What I'd defend under follow-up
- The failure mode I watched for was a rewrite caused by a late requirement. Schema contract tests on the response meant a precision change was a field addition, not a breaking change.
- The derived counter can drift from the log if a flush fails. I alarmed on flush age above 120 seconds and ran a nightly reconciliation that recounted a 1% sample and paged if the mismatch passed 0.1%.
- Featured-playlist exact reads were gated behind a per-tier flag, so the expensive path could be turned off in one config change if the scan cost rose.
What I'd change
I accepted "near real time" as a verbal requirement for the first week and built against my own reading of it. The better move is to ask for a number on the first call: a staleness bound in seconds, a precision level, and a retention period. Every ambiguous adjective in a spec should come back as a number before any code depends on 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-13Design the friends listening sidebar for Spotify.
Reported in Spotify Software Engineer Interview Experience (2026) - Aced (formerly Exponent)
The 90-second answer
I'd split this into a write path that records what each user is playing, and a read path that assembles the sidebar when the app opens. I'd avoid fanning out every play event to every friend. Fanout on write is expensive for popular users, and a sidebar only matters while someone is looking at it. So the read path pulls, and a short-lived presence store makes the pull cheap.
First I'd clarify scope: is the sidebar only for currently playing tracks, or also recently played? Is it near-real-time (seconds) or eventually consistent (under a minute)? I'll assume near-real-time for active sessions, a 2-3 minute TTL for presence, and a cap of 200 friends rendered.
Write path. The playback service emits a heartbeat about every 30 s while a track is playing, with user_id, track_id, started_at and device_type. A presence service writes this to a key-value store (Redis or similar) as presence:{user_id} with a 150 s TTL. A stopped or expired key means the user is not listening. Heartbeats are idempotent, so a duplicate or out-of-order one is harmless if I compare started_at and keep the newer value.
Read path. When the sidebar loads, the client calls GET /v1/friends/activity?limit=50. The server gets the friend list from the social graph service (cached, since it changes slowly), then issues one batched MGET for presence:{friend_id} keys. Trace for a user with 180 friends: graph lookup 4 ms, MGET of 180 keys 2 ms, privacy filter 1 ms, response in about 10 ms at p50. The privacy filter runs at read time, so a friend who turned off sharing disappears on the next fetch without a separate invalidation.
Live updates. While the sidebar is visible, the client holds a websocket subscription. The server pushes changes for the friends shown, throttled to one update per friend every 5 s so a user who skips tracks rapidly doesn't flood the socket. Each push rechecks the privacy setting, which covers the case where someone unfollows or blocks mid-session.
Failure modes.
- Stale entries: if the heartbeat stops but the TTL hasn't expired, the sidebar shows a track that ended 90 s ago. Mitigate by showing 'last active' with a timestamp and dropping anything older than 150 s on the client.
- Presence store outage: return the sidebar with no activity rather than failing the whole app. Detect via error rate on the MGET and a fallback counter.
- Reconnect storm after a deploy: thousands of sockets reconnect together. Add jittered backoff and a snapshot endpoint so reconnects don't replay every event.
- Hot users: a celebrity's presence key is read by millions of clients. Cache it in a local tier with a 5 s TTL.
I'd monitor p99 read latency, the staleness distribution (age of the newest heartbeat per shown friend), and the rate of privacy-filtered rows, which catches bugs where sharing settings don't propagate.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Dedupe URL parameters. Walk me through how you would do it.
Reported in Spotify Software Engineer Interview Experience (2026) - Aced (formerly Exponent)
The 60-second answer
First I'd pin down what counts as a duplicate, because two readings are both common. Exact duplicate pairs, meaning the same key and the same value, get dropped. Repeated keys with different values stay, since ?tag=a&tag=b is a legal multi-valued parameter and dropping one would change what the server receives. I'd keep the first occurrence and preserve order, since order can matter to the server and to anything that signs the URL. I'd also confirm that keys are case-sensitive and that flag and flag= are treated the same way by the consumer.
The approach is to parse the query into ordered pairs, dedupe the pairs with a seen-set, and re-encode. The cost is O(n) time and O(n) space in the number of parameters.
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
def dedupe_query(url: str) -> str:
parts = urlsplit(url)
pairs = parse_qsl(parts.query, keep_blank_values=True)
unique = list(dict.fromkeys(pairs)) # keeps first occurrence, order preserved
return urlunsplit(parts._replace(query=urlencode(unique)))Trace (hypothetical input, Python 3.12):
https://x.com/s?q=a&tag=1&q=a&tag=2&tag=1&flag#top
parse_qslgives[(q,a), (tag,1), (q,a), (tag,2), (tag,1), (flag,'')].dict.fromkeysdrops the second(q,a)and the second(tag,1), leaving[(q,a), (tag,1), (tag,2), (flag,'')].urlencodegivesq=a&tag=1&tag=2&flag=.- The fragment
#topsurvives because I rebuilt the URL with_replace.
Note the side effect in step 3: a bare flag becomes flag=. If the consumer distinguishes the two, that is a bug, so I'd either test for it or keep the raw segment instead of re-encoding it.
Where it breaks
- Re-encoding changes bytes.
parse_qsldecodes+as a space, andurlencodewrites spaces as+, but%20in the input comes back as+. Two URLs can be semantically equal and still differ as strings, which matters for cache keys and signatures. - Reordering breaks signed URLs. If an HMAC covers the query string, deduping and reordering invalidates the signature. In that case, dedupe only with the signature computed over the canonical form the signer used, or don't touch the URL at all.
- Tracking parameters are a different problem. Stripping
utm_*orfbclidis a policy decision and is not the same as removing duplicates. I'd keep them separate so the function does one thing. - Percent-encoding of keys can hide duplicates, for example
a%20banda+b. Normalize decoding before comparing, not after.
Tests I'd write
Exact duplicates collapse. Same key with different values is kept. Order of first occurrence is preserved. Blank and bare keys survive. Fragments and ports are untouched. Unicode and encoded spaces round-trip. Empty query returns the URL unchanged.
If the interviewer pushes on scale, the answer is the same: this is a per-URL linear scan, so the cost is in the parsing, not the dedupe, and the realistic risk is correctness on encoding edge cases rather than speed.
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 detect a cycle in a linked list.
Reported in Get a Job at Spotify: Interview Process and Top Questions
The 60-second answer
I'd confirm first: singly linked list, each node has next, and the list ends in None unless it loops. I need a boolean, and I'd like O(1) extra space. I'd use Floyd's tortoise and hare: two pointers, one moving one step and one moving two. If the list has a cycle, the fast pointer laps the slow one inside the loop and they meet. If it doesn't, the fast pointer hits None.
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseTrace. List 1 -> 2 -> 3 -> 4 -> 2, where node 4 points back to node 2.
| step | slow | fast | note |
|---|---|---|---|
| start | 1 | 1 | |
| 1 | 2 | 3 | |
| 2 | 3 | 2 | fast went 3 -> 4 -> 2 |
| 3 | 4 | 4 | slow is fast, return True |
Why it terminates. Once both pointers are inside the cycle of length L, the gap between them shrinks by one every step, so they meet within L steps. Total work is O(n) time and O(1) space: one pass, two pointers, no allocation.
Comparisons. Use a hash set of visited node identities for O(n) space. It's simpler and fine for lists that fit in memory, but it breaks on very long chains. Marking visited nodes by mutating them is destructive and fails if the nodes are shared or read-only. I'd only pick the set if I needed the entry point too and the simpler code mattered more than memory.
Follow-up: where the cycle starts. After they meet, reset one pointer to head and advance both by one step at a time. They meet again at the cycle entry. The reason is the standard distance argument: the distance from head to the entry equals the distance from the meeting point to the entry, measured around the loop.
Failure modes I'd check.
- Comparing values instead of node identity. Two distinct nodes with the same value would give a false positive. Use
is, not==. - Dereferencing
fast.nextwithout checkingfastfirst. The loop guard has to test both. - A list mutated while it's being traversed by another thread. The result is undefined for that run, so take a snapshot or hold a lock.
Where this shows up in a Spotify backend. Consider a chain of play-queue or playlist-continuation records, where each item points to the next. A bad write that points an item back at an earlier one would make traversal spin forever. I'd run this check in a nightly integrity job or before serializing a chain, and I'd make sure the job has a step budget so a corrupt chain fails fast instead of hanging a worker.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Review this pull request for collaborative playlists: identify bugs and propose improvements.
Reported in Spotify Backend Engineer New Grad Interview Experience
The 90-second answer
I'd start by asking for the diff's target: is this the add-track path, the reorder path, or the collaborator-permissions change? I'll assume the PR adds POST /playlists/{id}/tracks and PATCH /playlists/{id}/tracks/{track_id} for reordering, backed by a playlist_tracks(playlist_id, track_id, position) table, with collaborators able to edit. Those are where the bugs usually sit.
The bugs I'd raise first, in order of damage:
-
Lost updates on reorder. If the handler reads the full track list, reorders in memory and writes back, two collaborators reordering at once silently overwrite each other. Fix: a
versioncolumn on the playlist andUPDATE playlists SET version = version + 1 WHERE id = ? AND version = ?, returning 409 when zero rows change. Clients sendIf-Matchwith the ETag they read. -
Duplicate tracks on retry. A mobile client that times out on
POST .../tracksretries and the track appears twice. Require anIdempotency-Keyand storekey to responsefor 24 h, or make the insert idempotent with a unique constraint on(playlist_id, track_id)if the product forbids duplicates. -
Position collisions. Integer positions with
position = indexmean an insert at position 5 must renumber every later row, and two concurrent inserts at 5 both succeed. Use fractional or lexicographic position keys (for example, a midpoint string between neighbours) so an insert touches one row. Renumbering becomes a background compaction job, not a request-path write. -
Permission check on the wrong object. Check that the caller is an owner or collaborator of the playlist on every mutating route, not just the one the PR touches. Watch for a removed collaborator whose token is still valid: the check must read current membership, not a claim cached in the JWT, or revocation lags until expiry.
-
Private playlists leaking through track endpoints.
GET /playlists/{id}/tracksshould apply the same visibility rule asGET /playlists/{id}. A common miss is authorising the playlist fetch and forgetting the child collection. -
Missing events. If the write commits and the event publish to the activity feed runs as a separate call, a crash between them drops the event. Write the event to an outbox table in the same transaction and let a relay publish it.
Trace for the reorder race, with the version guard:
A reads playlist v7, B reads playlist v7
A: UPDATE ... WHERE version = 7 -> 1 row, now v8
B: UPDATE ... WHERE version = 7 -> 0 rows -> 409 playlist_version_conflictWithout the guard, both updates succeed and the second erases the first's ordering with no error.
Improvements I'd propose beyond the fixes: a load test that runs concurrent reorders against one playlist at p99 and checks zero lost updates, a metric on 409 rate per playlist (a spike means a hot playlist, which may need a different write model), and an alert on outbox lag. I would not add a distributed lock: a row-level version check is cheaper, and a lock held across a network hop fails badly when the holder dies.
What I'd push back on in review: the PR mixes a permissions change with a reorder change. Split them, so the permissions change can be reverted without touching ordering.
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: