Skip to content
Tech Interview Prep

Top 100 Backend Software Engineer Interview Questions and Answers

The questions most likely to come up in your Backend Software Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.

Curated: · Written: · Reviewed:

Reviewed 100Review pending 0

100 questions · Flow follows Relevance until this set has a learning order.

Q&A-1Given an unsorted array of integers and a target, return the indices of two elements that sum to the target. Why would you use a hash map instead of sorting, and what do duplicates and empty input change?

The 60-second answer

I'd use a single pass with a hash map. Each element is checked against the map before it is inserted, so the map stores only earlier indices and the search is O(n) time and O(n) extra space. Sorting is O(n log n) and, more importantly, loses the original indices unless I sort (value, index) pairs, which adds O(n) memory anyway. Sorting wins only when I need all pairs, or when memory is tight and I can afford two pointers on already-sorted data.

Trace. Assume nums = [2, 7, 11, 15], target = 9, and that the caller wants indices of any one valid pair.

ivalueneed (target - value)in map before lookup?action
027nostore 2 -> 0
172yes, index 0return [0, 1]

Duplicates. Take nums = [3, 3], target = 6. Look up before inserting: at i = 1 the map holds 3 -> 0 and returns [0, 1]. If I inserted first, the single 3 would match itself and return [0, 0], which is wrong. For the single-element case [3], target = 6, the check must never pair an index with itself. If the problem asks for every pair, the map must store a list of indices per value, or a count, and the result can grow to O(n²) pairs, so the output size dominates the cost.

Empty and tiny input. An empty array or one with a single element has no pair. I return a defined sentinel (None, or a 4xx with code: no_pair_found if this sits behind an API) rather than an exception that a caller might not catch. The loop body never runs, so no special-case arithmetic is needed; the explicit check is for the contract, not the algorithm.

Failure modes I would watch. Hash maps keyed by client-supplied integers can be attacked with colliding keys. Python's dict and Java's HashMap randomise or tree-bin collisions, so the worst case is no longer the textbook O(n) per lookup, but a service handling untrusted batches should still bound the batch size. Memory is the other risk: at a hypothetical n = 10^6 the map holds a million entries, while the sort approach does about 20 million comparisons (log2 of 10^6 is roughly 20) and can run in place if indices are not needed. I'd pick the map for a request-scoped batch that needs original indices and fits in memory, and sort for a streaming or memory-capped job that only needs the boolean answer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2Why is the sliding-window solution for the longest substring without repeating characters O(n) rather than O(n²)?

Both pointers move only forward, and that is the whole argument. right visits each index once. left starts at 0 and never decreases, so it can advance at most n times over the entire run. Every character enters the window once and leaves at most once, which makes the total work linear even though the inner logic looks like it could restart the scan.

The map is what makes each step cheap. Storing the last index of each character gives an O(1) average lookup for whether the current character already occurs inside the window, and where. Without that, checking uniqueness would cost time proportional to the window size and the bound would collapse.

Python
def length_of_longest_substring(s: str) -> int:
    last = {}   # char -> index of its most recent occurrence
    left = 0
    best = 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

Trace on abcabcbb

rightchleft afterwindowlengthbest
0a0a11
1b0ab22
2c0abc33
3a1bca33
4b2cab33
5c3abc33
6b5cb23
7b7b13

right advances 8 times and left travels from 0 to 7, a total distance of 7. Fifteen pointer steps for eight characters sits inside the 2n bound. The loop body itself runs exactly n times.

no yes yes no right reads next character Seen inside window? Extend window, update best left jumps past previous occurrence More characters? Return best

Why brute force is different

A brute-force scan tries every start index and extends the end index, giving roughly n(n-1)/2 substrings to examine. Each examination also needs a uniqueness check, so the real cost is worse than the pair count alone suggests.

nBrute-force pairsSliding-window pointer moves
500about 125,000at most 1,000
100,000about 5,000,000,000at most 200,000

The gap is not a constant factor. The window discards the left part of the string permanently, so positions already passed are never reconsidered as a start again.

Where the bound breaks

The guard last[ch] >= left matters. Drop it and a stale occurrence can pull left backward. On abba, the final a was last seen at index 0, already outside the window, and assigning left = 0 + 1 would move left from 2 back to 1. The window would then contain a duplicate and the reported length would be wrong. Monotonicity is not a nice property of the algorithm in general. It depends on that check.

Space is O(k), where k is the number of distinct characters stored. That is at most min(n, alphabet size). For ASCII input it behaves as a constant, for arbitrary Unicode strings it grows with the distinct characters actually present.

Alternative with a set

Python
window, left, best = set(), 0, 0
for right, ch in enumerate(s):
    while ch in window:
        window.remove(s[left])
        left += 1
    window.add(ch)
    best = max(best, right - left + 1)

This version also runs in O(n). The while loop can iterate many times for a single right, but each iteration removes one character and advances left, and neither can happen more than n times in total. Amortised cost per character is constant.

Checks

InputExpected
------
``0
aaaa1
abba2
abcabcbb3
pwwkew3

The empty string and aaaa catch off-by-one errors in right - left + 1, and abba catches the backward jump described above.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3Walk me through why next-greater-element with a monotonic stack runs in amortized O(n), then say what changes if the input is circular and how equal values affect the stack discipline.

The 90-second answer

Each index enters the stack at most once and leaves at most once, so the total work across the loop is at most 2n stack operations. The inner while loop looks quadratic at first glance, but it never does more pops than there have been pushes. Amortized, each step costs O(1), so the whole pass is O(n) time and the stack holds at most n indices.

Two details decide whether the argument holds in practice: the comparison must be strict when you pop, and the stack must store indices, not values, so you can write the answer back to the right slot.

Python
def next_greater(nums):
    res = [-1] * len(nums)
    stack = []  # indices whose next greater element is still unknown
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            res[stack.pop()] = x
        stack.append(i)
    return res

Trace. nums = [2, 1, 2, 4, 3]

ixstack beforeactionstack afterres so far
02[]push 0[0][-1,-1,-1,-1,-1]
11[0]2 not < 1, push 1[0,1]same
22[0,1]pop 1 (1 < 2), res[1]=2; 2 not < 2, push 2[0,2][-1,2,-1,-1,-1]
34[0,2]pop 2 (res[2]=4), pop 0 (res[0]=4), push 3[3][4,2,4,-1,-1]
43[3]4 not < 3, push 4[3,4]same

Indices 3 and 4 never find a greater value, so they stay at -1. Five pushes and three pops: pops never exceed pushes.

Why strict. With <= the equal element at index 0 would be popped by index 2, which is wrong if you want the next strictly greater value. With < the value 2 at index 0 correctly waits. Choosing <= silently changes the answer on any input with duplicates, and a test suite with only distinct values will not catch it.

Circular input. If the array wraps, the next greater element for index n-1 may sit at index 0. Scan 2n positions with i % n, but push only during the first n. Pushing on both passes would duplicate indices and break the one-push-per-index bound.

Python
def next_greater_circular(nums):
    n = len(nums)
    res = [-1] * n
    stack = []
    for i in range(2 * n):
        x = nums[i % n]
        while stack and nums[stack[-1]] < x:
            res[stack.pop()] = x
        if i < n:
            stack.append(i)
    return res

For [1, 2, 1] this returns [2, -1, 2]. Index 2 is resolved on the second pass, when index 1 (value 2) is reached.

Failure modes and how to detect them. Pushing the same index twice gives correct answers for small inputs and slow growth on large ones; the stack length exceeds n, which an assertion or a metric on peak stack size will show. Using values in the stack rather than indices breaks as soon as duplicates appear, since you cannot tell which slot to fill. Returning the answer before the scan finishes is the streaming trap: the next greater element for an early index is unknown until a later value arrives, so an online version must delay output or accept a latency bound. If your service consumes a live feed, say so and state the delay explicitly.

When not to use it. If you need the k-th greater element or a window maximum, a monotonic deque or a segment tree fits better. For very small arrays a nested loop is clearer and fast enough, and it is the right answer to write first before optimizing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4Your playback service receives 50 million listening sessions a day as (user, start, end) tuples, and you need total covered time per user. Walk me through how you would merge the overlapping intervals and what the sort costs compared with the single pass after it.

The 90-second answer

Sort by start, then make one left-to-right pass. Keep the last merged interval; if the next interval starts at or before its end, extend its end with max, otherwise start a new one. Cost is O(n log n) for the sort and O(n) for the scan, so the sort dominates. Before sorting, I'd check whether the data already arrives ordered per user, because a clustered index on (user_id, start) makes the sort free.

Python
def merge(intervals):
    merged = []
    for s, e in sorted(intervals):
        if merged and s <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], e)
        else:
            merged.append([s, e])
    return merged

Why the merge condition is s <= last_end. After sorting, every interval that could overlap the current block starts no earlier than the block's start. So the only question is whether it starts before the block ends. For closed intervals, touching counts as overlap, so [1,5] and [5,8] merge. If your intervals are half-open [s, e), the condition becomes s < last_end, and touching intervals stay separate. Coverage totals are the same either way, but interval counts differ, so state which convention the sessions use.

Trace. Input [[9,12],[1,10],[2,3]] sorts to [1,10],[2,3],[9,12]. [1,10] opens the block. [2,3]: 2 <= 10, so end becomes max(10, 3) = 10. [9,12]: 9 <= 10, so end becomes 12. Output [[1,12]].

The failure mode that matters. Writing merged[-1][1] = e instead of max breaks on containment. Take [[1,10],[2,3],[11,12]]. The second interval sets the end to 3, so the third fails 11 <= 3 and the output is [[1,3],[11,12]]. The correct answer is [[1,10],[11,12]]. This passes a test with no containment and fails in production, so include a contained-interval case in the test suite.

Sort versus scan, with hypothetical numbers. Assume one shard holds 50 million tuples. Sorting costs about n log2 n = 50e6 × 25.6 ≈ 1.3 × 10⁹ comparisons. The scan does 5 × 10⁷ steps. The sort is roughly 25 times the work, and most of the wall-clock time goes there. Two ways to cut it:

OptionCostWhen it wins
Sort all, one passO(n log n)Unordered input, general purpose
Pre-sorted by (user, start) from the store, one passO(n)Data already clustered; check the index before assuming
Sweep over integer timestamps (bucket or difference array)O(n + T), T = time rangeSmall bounded ranges, e.g. seconds in one day (86 400 buckets)

For a per-user merge, sort within each user's group rather than globally. Groups are small, so the cost is close to the sum of k_i log k_i, which is much less than n log n when users are numerous.

Mutation. sorted() returns a new list, so the caller's input is untouched. Sorting in place with intervals.sort() changes the caller's data, and that is a surprise for shared inputs. Also reject end < start at the boundary, because a single bad tuple will silently produce an interval that absorbs its neighbours.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5Given an integer array, return every unique triplet of values that sums to zero. Walk me through a approach that runs in about O(n²), how you skip duplicates without dropping valid triplets, and when you would pick a hash-set variant instead.

The 2-minute answer

First I'd confirm that uniqueness means unique as value multisets, not index triples, and whether the array can be large enough that O(n²) is a problem. Assume n up to about 3,000 and int values, and sum in a wider type if the language would overflow. Sort the array in O(n log n). Then fix index i, and run two pointers lo = i + 1 and hi = n - 1 over the suffix. That makes the whole thing O(n²) time with O(1) extra space, apart from the output.

Python
def three_sum(a):
    a.sort()
    out = []
    n = len(a)
    for i in range(n - 2):
        if i > 0 and a[i] == a[i - 1]:
            continue
        lo, hi = i + 1, n - 1
        while lo < hi:
            s = a[i] + a[lo] + a[hi]
            if s < 0:
                lo += 1
            elif s > 0:
                hi -= 1
            else:
                out.append([a[i], a[lo], a[hi]])
                lo += 1
                hi -= 1
                while lo < hi and a[lo] == a[lo - 1]:
                    lo += 1
                while lo < hi and a[hi] == a[hi + 1]:
                    hi -= 1
    return out

Why the duplicate skips are safe. Duplicates can only produce repeated triplets if you reuse the same value at the same position in the sorted order. So there are two places to skip. The outer loop skips i when it equals the previous value, because the suffix search from that earlier i already covered every pair that the repeat would find. The inner loop skips after a match, moving lo and hi past equal values. The inner skip has to happen after you record the match, not before. If you skip first, [-1, -1, 2] loses its second copy of -1 as a valid lo and you miss a triplet only when the next value also matches.

Trace. Input [-4, -1, -1, 0, 1, 2], target 0, already sorted.

ia[i]lo, hisum at first stepaction
0-41, 5-3lo climbs to 5, no match
1-12, 50record [-1, -1, 2], lo to 3, hi to 4
1-13, 40record [-1, 0, 1], pointers cross
2-1skippeda[2] == a[1]
304, 53hi drops to 4, pointers cross

Result: [[-1, -1, 2], [-1, 0, 1]]. Two triplets, no repeats, and the second -1 is still used as a lo value.

Hash-set variant. For each i, scan j > i with a set of seen values: when -(a[i] + a[j]) is in the set, emit the triplet. It is still O(n²) time, but it does not need the sort, which matters when the input is streamed or cannot be reordered. The costs are real: the set costs O(n) extra space, the constant factors are worse from hashing and allocation, and deduplication needs a second structure, typically a set of sorted tuples. Duplicate handling becomes the main source of bugs. I'd keep the two-pointer version unless the array must stay in place or in its original order.

Failure modes. Forgetting to move both pointers after a match gives an infinite loop. Skipping duplicates before recording drops triplets. Summing in 32-bit ints overflows on inputs near the limit, and that only shows up on adversarial test data. Sorting a copy when the caller expects in-place mutation is a contract bug, not a correctness bug, and it should be stated in the signature.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6In binary search on int indices, what expression should you use for the midpoint of lo and hi so it cannot overflow?

The 60-second answer

Use mid = lo + (hi - lo) / 2. The naive (lo + hi) / 2 can overflow. When both bounds are large, the sum exceeds the type's maximum, and in a 32-bit signed int it wraps negative, so mid falls outside [lo, hi]. The difference hi - lo is never larger than hi when lo >= 0, so it fits, and adding it back to lo lands inside the range.

Worked example, Java int (maximum 2,147,483,647), hypothetical bounds:

FormlohiResult
(lo + hi) / 21,500,000,0002,100,000,000sum = 3,600,000,000 wraps to -694,967,296, so mid = -347,483,648
lo + (hi - lo) / 21,500,000,0002,100,000,000diff = 600,000,000, so mid = 1,800,000,000

The same fix applies to any fixed-width type, including C, C++, Java and Go. Python integers are arbitrary precision, so the naive form is correct there, but the habit still transfers when the logic is ported.

If you mention (lo + hi) >>> 1 in Java, say it works for non-negative bounds because the sum fits in 32 unsigned bits, and that it is less readable than the subtraction form. Name the rule you are applying in one line, then stop.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-7Reverse a singly linked list iteratively, then recursively. Walk me through the pointer order in each version, how deep the recursion goes, and which nil cases break.

The 90-second answer

I'd check the input contract first: is the list ever empty, can it contain a cycle, and is it long enough that recursion depth matters? Assuming an acyclic list of unknown length, the iterative version is the one I'd ship. It runs in O(n) time and O(1) extra space. The recursive version is shorter and reads well, but it uses O(n) call-stack frames, and in CPython 3.12 the default recursion limit is 1000, so a list of a few thousand nodes raises RecursionError unless you change the limit, which is a bad fix in a request path.

Iterative: the order matters

Python
def reverse(head):
    prev, cur = None, head
    while cur is not None:
        nxt = cur.next      # 1. save the rest of the list
        cur.next = prev     # 2. flip the link
        prev = cur          # 3. advance prev
        cur = nxt           # 4. advance cur
    return prev

The trap is swapping steps 1 and 2. cur.next = prev overwrites the only reference to the tail, and the loop silently returns a two-node list. Trace on 1 → 2 → 3: after the first pass, None ← 1 and cur is 2. After the second, None ← 1 ← 2 with cur at 3. After the third, prev is 3, which is the new head, and cur is None. Returning prev rather than head is the other common slip, since head is now the tail.

Recursive: the stack is the second data structure

Python
def reverse_rec(head):
    if head is None or head.next is None:
        return head
    new_head = reverse_rec(head.next)
    head.next.next = head   # the node after us points back to us
    head.next = None        # without this, we keep a cycle
    return new_head

Three nil traps here. Dropping head is None gives an AttributeError on the empty list. Dropping head.next is None gives the same error on a single node, because the recursive call returns None and you dereference it. Dropping head.next = None leaves 1 pointing at 2 while 2 points at 1, so the first traversal after reversal loops forever. Each frame holds head until the recursive call returns, so the O(n) stack is the memory cost that the iterative version avoids.

Failure modes and how to detect them

Run both versions against lengths 0, 1, 2 and 10^5. The first three catch the nil bugs. The last catches the stack bug: the recursive one fails with RecursionError while the iterative one passes. For a cyclic input, both loop forever, so put a visited-set guard or a Floyd cycle check in front of anything fed by untrusted data. Java behaves differently: its default thread stack is smaller and fixed per thread, so the failure point depends on frame size and JVM flags, and you should measure it rather than quote a number.

When I'd pick each

Iterative for production code paths and anything with unbounded input. Recursive only when the list is bounded by a known small constant and the code reads better that way. In an interview I'd write the iterative version first, then say that the recursive one is equally correct on small inputs and fails on large ones.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8A service walks a linked chain of records where a bad write can point a later record back at an earlier one. Explain how fast and slow pointers detect that cycle, why they meet, and why the second pointer restarts at head to find the entry node.

The 90-second answer

Use Floyd's algorithm. Advance slow by one and fast by two. If the chain ends, there is no cycle. If they become the same node, there is one. To find the entry node, reset one pointer to head, move both by one, and stop where they meet. That node is the first node of the cycle. Extra space is O(1), time is O(μ + λ), where μ is the distance from head to the entry and λ is the cycle length.

The fast pointer gains one node per step on the slow pointer, so once both are inside the cycle the gap closes by one every step and they must meet within λ steps. The restart works because of where they meet, not by coincidence.

Why they meet. Let the list be 1→2→3→4→5→6→3, so the entry is node 3 at index μ = 2 and the cycle length is λ = 4. After t steps, slow is at index t and fast at index 2t. Fast is in the cycle relative to slow once both are past μ, and the difference 2t − t = t must be a multiple of λ for them to coincide. The first such t with t ≥ μ is t = 4. Slow sits at index 4 (node 5), fast at index 8 (node 5). They meet at node 5.

Why the restart lands on the entry. At the meeting point, slow has walked t = 4 steps, and 4 is a multiple of λ. So the meeting node sits at cycle offset (t − μ) mod λ = (−2) mod 4 = 2 from the entry. Now move a pointer from head and a pointer from the meeting node, one step at a time. The head pointer needs μ = 2 steps to reach the entry. The meeting pointer after 2 steps is at cycle offset (2 + 2) mod 4 = 0, which is the entry. Both arrive at node 3 together. The argument holds for any μ and λ because t is always a multiple of λ at the first meeting.

Python
def cycle_entry(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            break
    else:
        return None
    slow = head
    while slow is not fast:
        slow = slow.next
        fast = fast.next
    return slow

Trade-offs. A visited set of node identities finds the entry in O(n) space with a simpler loop: the first node seen twice is the entry. It is the better choice when the chain is short or you need to report the whole path. Floyd's uses constant memory, which matters when chains are long and you process many at once, such as scanning a corrupt parent pointer structure in a batch job. Its cost is two passes and more care with edge cases.

Failure modes to name.

  • Checking fast.next before fast drops the nil guard and raises on even-length acyclic lists.
  • Comparing values with == instead of identity reports false cycles when records share a key.
  • Starting both pointers at head and checking equality before the first move returns head on every list.
  • Restarting both pointers at head instead of one returns head again, so the entry is never found.
  • Using the meeting node as the answer without the second pass returns a node inside the cycle, which is usually not the entry.

In production I would wrap this with a hard step limit or a visited count, so a bug in the write path that corrupts the structure fails loudly rather than spinning a worker.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9Your track-metadata service keeps an LRU cache of 10,000 entries in front of a database. Explain how get and put both run in O(1) using a hash map and a doubly linked list, and what the sentinel head and tail nodes remove from the eviction code.

The 60-second answer

Keep a hash map from key to node, and a doubly linked list ordered from most to least recently used. get looks the node up in the map, unlinks it and relinks it at the front. put does the same for an existing key. For a new key it inserts a node at the front and, if the cache is full, takes the node at the back, unlinks it and deletes its key from the map. Each step is a fixed number of pointer writes plus one hash operation, so both calls are O(1) expected. The expected qualifier matters: a hash map's worst case is O(n) under heavy collisions.

The list has to be doubly linked. The map gives you the node, but removing a node from the middle needs its predecessor, and only a prev pointer provides that without a scan.

Sentinels are two dummy nodes that are always present. Real nodes always sit between them, so every real node has a non-null prev and next. Unlink and push-front never test for an empty list, and never test whether the node being moved is the head or the tail. Those are the cases that otherwise produce null-pointer bugs in eviction.

Python
# Python 3.12
class Node:
    __slots__ = ('key', 'val', 'prev', 'next')
    def __init__(self, key=None, val=None):
        self.key, self.val = key, val
        self.prev = self.next = None

class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.map = {}
        self.head, self.tail = Node(), Node()
        self.head.next, self.tail.prev = self.tail, self.head

    def _unlink(self, n):
        n.prev.next = n.next
        n.next.prev = n.prev

    def _push_front(self, n):
        n.prev, n.next = self.head, self.head.next
        self.head.next.prev = n
        self.head.next = n

    def get(self, key):
        n = self.map.get(key)
        if n is None:
            return -1
        self._unlink(n); self._push_front(n)
        return n.val

    def put(self, key, val):
        n = self.map.get(key)
        if n is not None:
            n.val = val
            self._unlink(n); self._push_front(n)
            return
        if len(self.map) == self.cap:
            lru = self.tail.prev          # real node, never the sentinel
            self._unlink(lru)
            del self.map[lru.key]
        n = Node(key, val)
        self.map[key] = n
        self._push_front(n)

Without sentinels, _unlink needs guards for a missing prev or next, and _push_front needs a separate branch for the empty list. Every guard is a place to forget one.

Trace at capacity 2

StepCallList, MRU to LRUMap keys
1put(1,'a')11
2put(2,'b')2, 11, 2
3get(1)1, 21, 2
4put(3,'c')3, 11, 3 (2 evicted from tail)

Step 4 is the case to narrate: key 2 was the least recently used because get(1) moved 1 to the front, so eviction takes the node before the tail sentinel.

Failure modes and alternatives

get mutates the list, so a read-write lock does not help. Concurrent readers each rewrite pointers. Use one mutex, or shard the cache by key hash and accept that each shard has its own LRU order, which is an approximation. Under high read concurrency, the lock becomes the bottleneck long before the O(1) bound matters.

In Python, collections.OrderedDict with move_to_end and popitem(last=False) gives the same O(1) bounds with less code, and it is what I would ship. Write the linked list by hand only when the interviewer asks for it or when you need node-level control.

If reads dominate and lock contention is measured rather than assumed, CLOCK or sampled LRU avoids moving anything on a hit. You give up exact recency order, and you should say so.

To check the design under load, watch the cache hit rate and the p99 of put under contention, not the average. A lock held during an eviction shows up in the tail first.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10In a binary search tree, what must be true of the keys in a node's left subtree compared with the node's own key?

The 60-second answer

Every key in the left subtree of a node must be less than that node's key, and every key in the right subtree must be greater. That rule holds for the whole subtree, not only for the direct children. So a node's position is constrained by all of its ancestors, and any validity check has to respect that.

Why the local check fails

A check that only compares each node with its own left and right child can pass a tree that breaks the rule. Take this tree:

      10
     /  \
    5    15
        /
       6

At the root, 5 < 10 < 15 holds. At node 15, its left child 6 is less than 15, so that check passes too. But 6 lies in the right subtree of 10, so it must be greater than 10. It is not, so the tree is not a BST. The violation comes from an ancestor, and the local check never looks there.

Correct version (Python 3.12)

Python
def is_valid_bst(node, lo=None, hi=None):
    if node is None:
        return True
    if (lo is not None and node.val <= lo) or (hi is not None and node.val >= hi):
        return False
    return (is_valid_bst(node.left, lo, node.val)
            and is_valid_bst(node.right, node.val, hi))

The strict inequalities assume distinct keys. If duplicates are allowed, state where they go and use < or <= consistently. Use None as the sentinel rather than INT_MIN and INT_MAX, because a fixed-width integer can legitimately equal those limits.

Cost

Each node is visited once with O(1) work, so time is O(n). Space is the recursion depth, O(h): O(log n) for a balanced tree and O(n) for a skewed one. A skewed tree of a million nodes can exceed Python's default recursion limit of 1000, so an iterative version with an explicit stack is the safer choice there.

Alternative: inorder traversal

An inorder walk of a valid BST yields strictly increasing keys. Keep the previous value during the walk and reject any step where the current key is less than or equal to it. This is also O(n) time and O(h) space. Use it when you already have an in-order iterator. Use the bounds version when you need to report which node broke the rule.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11Given the root of a binary tree and two nodes p and q, both guaranteed to be in the tree, return their lowest common ancestor. Explain what each recursive call returns, then how your answer changes if every node has a parent pointer.

The 2-minute answer

First I'd confirm the inputs: are p and q guaranteed present, can they be equal, and is a node its own ancestor? I'll assume both are present, compared by node identity (never by value, since values can repeat), and a node counts as its own ancestor. Then the recursion: each call returns the LCA candidate found in its subtree, or null if none of p and q is there.

Python
def lca(root, p, q):
    if root is None or root is p or root is q:
        return root
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    if left and right:
        return root
    return left or right

The return value means: non-null means 'I found p or q, or the answer, somewhere below me'. When both children return non-null, the current node is the split point and is the LCA. When only one side returns non-null, that value propagates up unchanged, because it is either the answer already found or a single target still waiting for its partner.

Trace. Tree: 3 has children 5 and 1; 5 has children 6 and 2. Call lca(3, 5, 1). At node 5, the call returns 5 (it is p). At node 1, it returns 1 (it is q). Node 3 sees both non-null and returns 3.

Failure modes.

  • If p or q is not in the tree, the function still returns the other target, which is wrong. Either verify membership in a second pass, or count matches and return null when the count is below 2.
  • If p is an ancestor of q, the function correctly returns p, because p is returned at its own frame before its children are examined. A candidate who writes it as a 'both sides non-null' check only will miss this.
  • Cost is O(n) time and O(h) stack, where h is height. A degenerate tree of 100,000 nodes will overflow Python's default recursion limit of 1000. Use an explicit stack or raise the limit deliberately.

With parent pointers. The recursion is no longer needed. Walk from p to the root, recording each ancestor in a set. Then walk up from q and return the first node already in the set.

Python
def lca_parents(p, q):
    seen = set()
    x = p
    while x is not None:
        seen.add(x)
        x = x.parent
    x = q
    while x is not None and x not in seen:
        x = x.parent
    return x

That is O(h) time and O(h) space. If space matters, use depth equalisation: compute each node's depth by walking up, lift the deeper node until depths match, then step both up together until they meet. That is O(h) time and O(1) extra space. The trade-off is that you must trust parent pointers stay consistent. A stale pointer after a rebalance or a partial update produces a wrong answer with no exception, so I would validate invariants (parent.left or parent.right is the child) in tests.

In a backend setting this shows up as finding the shared fan-out point of two spans in a distributed trace, where spans carry parent ids. The recursion needs the whole tree in memory; the parent-pointer version works on a single span's chain, which is usually what production has.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12Count the islands in a 1000 by 1000 grid of land and water cells with BFS versus DFS. How do you mark visited cells, how deep does recursion go, and what does each approach keep in memory?

The 90-second answer

Treat each land cell as a node and each 4-directional land neighbour as an edge. Scan the grid in row-major order; every time you hit an unvisited land cell, you have found a new island, so increment the count and flood-fill its component. The two approaches differ only in the container that holds the frontier: DFS uses the call stack or an explicit stack (LIFO), BFS uses a queue (FIFO). Both visit each cell once, so both are O(R·C) time, about 10^6 cell visits here.

The real difference shows up in memory and in recursion depth. A naive recursive DFS on an all-land 1000 by 1000 grid nests one frame per cell in the worst snake-shaped island, so depth can reach about 10^6. CPython's default recursion limit is 1000 and the default C stack on Linux is around 8 MB, so the recursive version crashes long before it finishes. Java and C++ fail the same way, just later. BFS never recurses, so its depth is zero.

Visited marking

Do not use a separate visited set for a 10^6-cell grid unless you must. Mutate the grid instead: set a land cell to water ('0') the moment you enqueue or push it. That marks it visited at push time, not pop time. Marking at pop time is the classic bug: the same cell gets pushed by several neighbours and the queue or stack grows to several times R·C entries.

Python
from collections import deque

def num_islands_bfs(grid):
    R, C = len(grid), len(grid[0])
    count = 0
    for r in range(R):
        for c in range(C):
            if grid[r][c] != '1':
                continue
            count += 1
            grid[r][c] = '0'          # mark on enqueue
            q = deque([(r, c)])
            while q:
                y, x = q.popleft()
                for ny, nx in ((y+1,x),(y-1,x),(y,x+1),(y,x-1)):
                    if 0 <= ny < R and 0 <= nx < C and grid[ny][nx] == '1':
                        grid[ny][nx] = '0'
                        q.append((ny, nx))
    return count

The iterative DFS is identical except q.pop() replaces popleft(). The recursive version is the one to reject for this input size.

Memory, with real figures

Let the grid be 10^6 cells, all land, the worst case for frontier size.

ApproachCall depthFrontier worst caseExtra memory (approx.)
Recursive DFSup to ~10^6 framesn/a10^6 frames × ~100 B each ≈ 100 MB, far beyond an 8 MB stack
Iterative DFS (stack)0up to ~10^6 entries~8 MB of (int,int) pairs, about 16 MB in Python objects
BFS (queue)0one diagonal wavefront, ~2000 cellsa few KB

The BFS frontier is bounded by the wavefront width, roughly the grid's diagonal (about 2·1000 cells), because it expands in layers. The DFS stack has no such bound: it can hold nearly every land cell on a large island. So BFS is the safer default when islands are large and you want predictable memory. Those frontier figures are hypothetical worst cases for an all-land grid, chosen to show the scaling.

When I'd pick each

Use iterative BFS for large, blob-like islands where memory must stay small. Use iterative DFS when you only need component membership and the code is simpler, and accept the stack growth. Never use recursive DFS on a grid this size. If you can only mutate the input grid by convention, copy it or track visited in a bitset (one bit per cell, about 125 KB for 10^6 cells) instead of a hash set of tuples, which would cost tens of MB.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13Your dispatch service runs shortest-path queries on a road graph with 2 million nodes and 6 million edges. Explain how Dijkstra with a binary heap and lazy deletion reaches O(E log V), and why one negative edge can make the returned distances wrong.

The 90-second answer

Assume a single-source query on non-negative weights, a binary heap of (dist, node) pairs, and an adjacency list. Dijkstra settles nodes in increasing distance order. Each pop yields the closest unsettled node, and its distance is final because every remaining path must pass through a frontier node whose distance is at least as large. Relaxing an edge u→v may lower dist[v], so push the new pair.

A binary heap has no decrease-key in the standard library, so lazy deletion pushes a fresh entry instead and skips stale ones on pop. Each successful relaxation pushes at most one entry, so the heap holds at most E entries. Push and pop cost O(log E), and E ≤ V², so log E ≤ 2 log V, which gives O(E log V) overall.

Negative edges break the settle-once argument. A settled node is assumed final, but a later path through a negative edge can lower its distance. The code below still updates dist for an already-settled node, but it never re-expands that node's out-edges, so every descendant keeps a distance computed from the old value. The result is wrong without any error.

Trace

Directed graph: A→B (1), A→C (2), C→B (−2), B→D (1). True shortest distances: B = 0 (via A→C→B), D = 1 (via A→C→B→D).

StepPopActionheap afterdist
0nonepush A=0(0,A)A=0
1(0,A)settle A; relax B→1, C→2(1,B),(2,C)B=1, C=2
2(1,B)settle B; relax D→2(2,C),(2,D)B=1, D=2
3(2,C)settle C; relax B: 2−2=0 < 1, so B=0 and push(0,B),(2,D)B=0, D=2
4(0,B)B already settled, skip(2,D)B=0, D=2
5(2,D)settle DnoneB=0, D=2

The function returns B=0, which is correct, but D=2 when the true value is 1. The fix to B came too late: B's out-edge was already relaxed with its old distance, and the stale (0,B) entry is skipped.

Python
import heapq

def dijkstra(adj, src):
    dist = {src: 0}
    heap = [(0, src)]
    settled = set()
    while heap:
        d, u = heapq.heappop(heap)
        if u in settled:
            continue
        settled.add(u)
        for v, w in adj[u]:
            nd = d + w
            if nd < dist.get(v, float('inf')):
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist

Alternatives and when not to use Dijkstra

  • Bellman-Ford handles negative edges in O(V·E) and detects negative cycles with a V-th relaxation pass. On a 2M × 6M graph that is roughly 1.2×10¹³ relaxations, so it only suits small or sparse subgraphs.
  • Johnson's algorithm runs one Bellman-Ford pass to compute potentials, reweights every edge to be non-negative, then runs Dijkstra from each source. It fits all-pairs queries with negative weights and no negative cycles.
  • A* with an admissible heuristic keeps the non-negative requirement but usually settles far fewer nodes on road graphs.

Failure modes to name

  • Heap growth: lazy deletion can hold up to E entries, so memory is O(E) rather than O(V). Watch heap size on dense graphs.
  • Silent wrong answers: negative weights raise no exception. Validate weights at ingest, because one bad feed row can corrupt every route that uses that edge.
  • Missing settled check: without it, stale entries re-expand nodes and the work multiplies.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14For the top k most frequent elements in an array, what is the time complexity of a size-k min-heap approach, and is it linear in n when k is small?

Short answer: O(n log k) time, and yes, it is effectively linear in n when k is small, because log k barely grows.

Clarify first: the input is an array of n integers, counts are unknown up front, and d is the number of distinct values, which can be as large as n. Counting with a hash map costs O(n) expected time and O(d) space.

Selection: keep a min-heap of at most k (count, value) pairs. For each distinct value, push its pair; if the heap now holds k+1 items, pop the minimum. Each push or pop costs O(log k), so selection is O(d log k) time and O(k) extra space. Total: O(n + d log k), which is O(n log k) since d is at most n.

Trace with nums = [4,4,4,1,1,2], k = 2. Counts: {4:3, 1:2, 2:1}. Push (3,4); push (2,1), size is 2; push (1,2), size is 3, pop the minimum (1,2). Result {4,1}.

Why small k makes it linear in practice: with k = 10, log2(10) is about 3.3, so each heap operation is a few comparisons. Bucket sort by frequency avoids the log term entirely at O(n) time, but needs n+1 bucket slots. Pick the heap when memory must stay O(k) or counts arrive as a stream. Failure mode to name: if k grows toward d, the log k term stops being negligible, and quickselect on the counts (O(d) expected) becomes the better choice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15Latencies arrive as a stream of 32-bit integers and you must report the median after every insert, without storing a sorted array. Design it with two heaps: state the invariant, the insert and query costs, and the rebalance cases, including duplicates.

The 60-second answer

Keep lo, a max-heap holding the smaller half, and hi, a min-heap holding the larger half. Maintain two invariants: every value in lo is less than or equal to every value in hi, and len(lo) equals len(hi) or len(hi) + 1. The median is lo.top when the count is odd, and (lo.top + hi.top) / 2 when it is even. Reading the median is O(1). Each insert does a constant number of heap operations on heaps of size at most n, so insert is O(log n) and the structure uses O(n) memory.

The insert procedure. I push the new value into lo unconditionally, move lo.top to hi, then move hi.top back to lo only if hi became larger. That looks like it skips case analysis, and it does: pushing into lo and then moving its maximum keeps the ordering invariant without comparing against the current medians first. The cost is up to three heap operations per insert, all O(log n).

StepInputlo (max-heap)hi (min-heap)Median
15{5}{}5
22{2}{5}3.5
38{5, 2}{8}5
44{4, 2}{5, 8}4.5

Step 3 shows the size fix: after moving 8 into hi, hi has two elements and lo one, so 5 moves back. Check against the sorted data 2, 4, 5, 8: median 4.5, as the table says.

Cases a candidate should name. If the new value is below lo.top, it lands in lo and the procedure pushes the old maximum up. If it is above hi.top, it goes to hi via lo and the minimum of the upper half is correct by construction. If it falls between the two tops, it still passes through lo and comes back out as needed. Duplicates are safe because the invariant uses <=: a value equal to the boundary can sit in either heap and the median is unchanged.

Failure modes. Forgetting the size fix lets the sizes drift apart. The median then reads a top that is one position off, which passes small tests and fails on long streams. Detect it with a property test against a sorted-array oracle using random inputs with many duplicates. The second failure is overflow: (lo.top + hi.top) / 2 wraps when both values are near 2^31. Compute lo.top + (hi.top - lo.top) / 2, or widen to 64 bits. Also decide what integer division does with negative values in your language, because truncation toward zero and flooring give different medians on negative input.

When not to use it. Two heaps cannot delete. A sliding-window median needs lazy deletion with per-value counters, or an order-statistic tree. If latencies come from a bounded range, such as 0 to 60000 ms, a Fenwick tree over buckets gives O(log V) updates and quantile queries, and supports removal. For production p99 dashboards over unbounded traffic, an HDR histogram or t-digest bounds memory and gives approximate quantiles, which is usually the right trade.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16Walk me through the house robber problem: given non-negative house values where no two adjacent houses can both be robbed, define the DP state, write the recurrence, reduce the memory from a full table to two variables, and then explain why the same trick fails for coin change.

The 90-second answer

State: best[i] is the maximum loot from houses 0..i with no two adjacent robbed. Recurrence: best[i] = max(best[i-1], best[i-2] + v[i]). Either skip house i, or take it and add the best from i-2 or earlier. Base cases: best[-1] = 0, best[-2] = 0. Time O(n), memory O(n) for the table.

Each best[i] reads only the two previous values, so the table can collapse to two variables. Keep prev2 (best through two houses back) and prev1 (best through one house back).

Python
def rob(v):
    prev2 = 0  # best through i-2
    prev1 = 0  # best through i-1
    for x in v:
        cur = max(prev1, prev2 + x)
        prev2, prev1 = prev1, cur
    return prev1

Trace on v = [2, 7, 9, 3, 1]:

xprev2 + xcurprev2 afterprev1 after
20 + 2 = 2202
70 + 7 = 7727
92 + 9 = 1111711
37 + 3 = 10111111
111 + 1 = 12121112

Answer 12 (houses 0, 2, 4: 2 + 9 + 1). The tuple assignment matters: prev2 must take the old prev1 before prev1 is overwritten, which Python's simultaneous assignment guarantees.

Why coin change does not collapse the same way. Minimum coins for amount a is dp[a] = min(dp[a - c] + 1) over every coin c <= a. The offsets are the coin values, not 1 and 2. With coins [1, 2, 5], dp[11] reads dp[10], dp[9] and dp[6]. Two variables cannot hold that.

What does shrink: you only need the last max(coin) values, so a ring buffer of size max(coin) + 1 replaces the O(amount) array. For coins [1, 2, 5] that is 6 slots instead of 12. For a coin set with a 10,000 denomination and amount 10^6 the saving is real; for [1, 2, 5] it is trivial.

Trace for [1, 2, 5], amount 11: dp runs 0, 1, 1, 2, 2, 1, 2, 2, 3, 3, 2, 3. Answer 3 (5 + 5 + 1).

Failure modes to name

  • Unreachable amounts. Use amount + 1 as the infinity sentinel rather than float('inf') in an integer path, and return -1 when dp[amount] > amount. Adding 1 to a near-maximum integer sentinel overflows in fixed-width languages and gives a wrong minimum.
  • Coins larger than the amount. The inner loop must skip them, not index negative.
  • Greedy as a shortcut. Taking the largest coin first fails on [1, 3, 4] with amount 6: greedy gives 4 + 1 + 1 (3 coins), the optimum is 3 + 3 (2 coins).

Complexity: time O(amount × number of coins) for both the table and the ring buffer. Memory is O(amount) for the table and O(max coin) for the ring buffer. The ring buffer applies to min-count, not to counting combinations, where the iteration order changes.

Trade-off to say out loud. House robber is a fixed-width dependency, so two variables is exact. Coin change depends on a variable-width window, so the honest memory reduction is a window sized by the largest coin, and you should say so before the interviewer asks.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17Your ranking service needs the length of the longest strictly increasing subsequence of a 200,000-element integer array, and a teammate proposes the tails array. Explain how the tails array achieves O(n log n), why its contents do not give you the subsequence itself, and how you would recover an actual subsequence without going back to O(n²).

The 60-second answer

Keep an array tails where tails[k] is the smallest possible last value of an increasing subsequence of length k+1 seen so far. The array is always sorted, so for each incoming value x I binary-search for the first position with tails[pos] >= x (strict increase means >=, so equal values replace rather than extend). If pos is past the end, append; otherwise overwrite tails[pos] = x. The answer is len(tails). Each element costs one binary search, so the total is O(n log n).

The length is right, but tails is not a subsequence. Overwrites destroy history: after [3, 1, 2], tails is [1, 2], which happens to be a valid subsequence here, but after [1, 3, 2, 4], tails is [1, 2, 4] while the value 2 came from a different branch than 1. Only the lengths of the best chains are preserved, not the chains.

Trace on [3, 10, 2, 1, 20] (strict):

xbinary search postails after
30 (append)[3]
101 (append)[3, 10]
20 (overwrite)[2, 10]
10 (overwrite)[1, 10]
202 (append)[1, 10, 20]

Length 3. The real answer 3, 10, 20 is not what tails holds: tails currently says 1, 10, 20, which is also valid here, but that is luck of the data.

Recovering the sequence. Store two extra arrays alongside tails: for every element index i, prev[i] = the index of the element that was at tails[pos-1] when i was placed, and tailIdx[k] = the index currently sitting in tails[k]. When you append or overwrite at pos, set prev[i] = tailIdx[pos-1] (or -1 if pos == 0) and tailIdx[pos] = i. At the end, start from tailIdx[len-1] and follow prev back. Space is O(n), time stays O(n log n), and the reconstruction is O(n). Overwritten entries are safe to lose from tails because prev already recorded the link that a later extension needs.

Check with the trace: prev for the 20 (index 4) points to the element at tails[1] when it was placed, which is 10 (index 1). prev of 10 is index 0 (3). Walking back gives 3, 10, 20, a real subsequence.

Why not just keep full lists? Copying the best chain at every step is O(n²) in the worst case, and it still does not give you the O(n log n) bound.

Pitfalls.

  • Using > instead of >= for the binary search silently computes the non-strict answer. Test with [2, 2, 2]: strict gives 1.
  • Forgetting prev updates on overwrite breaks reconstruction in a way that only shows on inputs with decreases.
  • Python's bisect_left gives strict-increase behaviour; bisect_right gives non-decreasing.

In an interview I would state the length version first, then say the reconstruction costs two extra arrays and no complexity change.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18For an order endpoint, which status code should a successful POST that creates a new order return, and what header should point to the new resource?

The 30-second answer

A successful POST /orders that creates a new order returns 201 Created, with a Location header pointing at the new resource, for example Location: /orders/42. The body can carry the representation of the created order. 200 OK is for requests that succeeded without creating a resource, such as a GET, a PATCH that returns the updated order, or a replayed idempotent request if you choose to return the stored result as 200.

Why the split matters

201 tells the client that a new resource now exists at a known URL, so it can store that URL and fetch it later without guessing. A 200 on a create leaves the client to parse the body for an id. Both are 2xx, so a generic success check treats them the same, but client code that caches or links to the new resource depends on Location.

SituationStatusHeader
order created201Location: /orders/42
order read or patched200none needed
cancel accepted, processed later202status or cancellation resource URL
idempotent retry of a completed create201 (or 200)same Location as the first response

Idempotent retries. A client times out after 2 s and retries POST /orders with the same Idempotency-Key. Trace: request 1 stores key → (order_id 42, response) and returns 201 with Location: /orders/42. The retry finds the stored key and replays the same response, so the client sees the same order id and does not create a duplicate. Pick one status for replays and document it, since RFC 9110 does not force either choice.

When not to use 201. If the create is asynchronous and the order is not yet persisted when you respond, return 202 Accepted with a status resource instead. Do not return 201 with a Location that will 404 for several seconds.

Failure mode. A client that treats any 200 as "safe to cache by URL" and any 201 without Location as an error will misbehave. Check that your create path always sets Location, and that integration tests assert the header, not only the status.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-19A client talks to your API through a load balancer that retries on timeout. For PUT, POST and PATCH, what can it retry safely, and what exactly happens when a retried POST is applied twice?

The 90-second answer

Retry safety is a property of the method's semantics, not of the transport. RFC 9110 defines PUT as idempotent: a request that replaces the representation at a known URL leaves the same state whether it runs once or five times. GET, HEAD, OPTIONS and DELETE share that property. POST is not idempotent by definition, and PATCH is not required to be (RFC 5789 says so explicitly). So a retried PUT is safe, a retried PATCH is safe only if its operations are themselves idempotent, and a retried POST creates a second resource unless the server deduplicates it.

The assumption I'm making: retries happen because the client never saw a response, so it cannot know whether the first attempt committed.

PUT. PUT /playlists/pl_91af with a full body is safe to replay. The second request overwrites with identical content. The trap is a PUT that generates server-side side effects, such as appending a play event or incrementing a version counter. The state converges, but the side effects don't.

PATCH. PATCH with JSON Merge Patch (RFC 7396) {"title":"Late Set"} is idempotent. JSON Patch (RFC 6902) [{"op":"add","path":"/tracks/-","value":…}] is not: each replay appends another track. Gate retries on If-Match: <etag>, so a replay after someone else's edit fails with 412 rather than silently clobbering.

POST with an Idempotency-Key. The server must make the key insert and the business write atomic. Trace, with two requests racing on the same key:

StepRequest ARequest B (retry, 900 ms later)Stored row
1inserts key, status in_progresskey k1, in_progress
2inserts order 42arrives, key exists, in_progress
3updates key to completed, stores 201 bodyreturns 409 already_in_progress (or waits)key k1, completed
4retries after step 3, replays stored 201

Two failure modes break this. First, if the response is stored in a separate write after the order commit, a crash between them leaves an order with no recorded response, and the retry creates order 43. Store the response in the same transaction as the order. Second, keys expire. A retry after the TTL (Stripe-style keys commonly live 24 h) is indistinguishable from a new request. Detect it by monitoring duplicate customer_id plus identical body within a window, and set the TTL longer than your worst client retry horizon.

Also fingerprint the request. Same key with a different body is a client bug, and replaying the old response silently hides it. Reject it with a 4xx and a distinct code.

When not to use keys. If the server assigns no identity and the client can name the resource, switch to PUT /orders/{client_id}. That moves idempotency into the URL and removes the dedupe table entirely. Use it for anything with a natural client-side key, and keep POST plus key for actions like payments where the server must own the id.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20Your playlist service pages through 80 million tracks per playlist. Compare offset and cursor pagination: what does a deep OFFSET cost, and what happens to a client's cursor when rows are inserted while it is paging?

The 60-second answer

Offset pagination makes the database read and discard the first N rows on every request, so page cost grows with the page number. Keyset (cursor) pagination stores the sort key of the last row returned and seeks past it through an index, so each page costs about the same wherever it sits. Inserts are the other difference. An offset is a position, so an insert before the client's position shifts every later row and the client sees a duplicate. A keyset cursor is a value, so the same insert is invisible to the page boundary.

Assumptions: PostgreSQL 16, playlist_tracks with 80 million rows across playlists, sorted by (added_at, track_id), a btree index on (playlist_id, added_at, track_id), page size 50.

Deep offsets

SQL
SELECT track_id, added_at FROM playlist_tracks
WHERE playlist_id = $1
ORDER BY added_at, track_id
LIMIT 50 OFFSET 2000000;

The index delivers rows in order, but the executor still walks 2,000,050 index entries and throws 2,000,000 away. Hypothetical figures: 2 µs per visited entry gives about 4 s for page 40,001, against roughly 100 µs for page 1. Offset also cannot be served from a single consistent snapshot across requests, so each page is a fresh walk.

Keyset

SQL
SELECT track_id, added_at FROM playlist_tracks
WHERE playlist_id = $1 AND (added_at, track_id) > ($2, $3)
ORDER BY added_at, track_id
LIMIT 50;

The row-value comparison matches the index prefix and seeks straight to the boundary, so the cost is O(log n + 50) per page. Encode the last (added_at, track_id) as an opaque base64 token and validate it on the way in.

Concurrent inserts, traced

StepOffset resultKeyset result
Page 1 returns rows 0 to 49, last is R50okcursor = R50
Client-supplied added_at earlier than R50 is insertednonenone
Page 2 requestedstarts at old row 49, so R50 repeatsstarts after R50, no repeat
Row deleted before page 2rows after it shift up, one is skippedno effect

So offset gives duplicates on insert and misses on delete. Keyset gives neither for the rows already behind the cursor. Rows inserted ahead of the cursor do appear on later pages, which is what a live feed should do.

Keyset failure modes

  • Non-unique sort key: ties at the boundary get skipped or repeated. The track_id tiebreaker fixes this only if it is unique within the playlist.
  • Nullable sort column: NULL never compares as greater or less, so rows vanish from the page sequence. Make the column NOT NULL or sort with an explicit NULLS LAST and matching predicate.
  • Mutable sort column: if added_at is updated, a row can move across the cursor and repeat or disappear. Sort by an immutable key, or accept and document the gap.
  • Detection: log page depth and per-page latency, and keep a contract test that pages through a fixture while inserting into it.

When not to use keyset

Clients that jump to arbitrary page N, or a UI that shows an exact total, do not fit a cursor. Cap offset depth (return 400 beyond a limit), and get the total from COUNT(*) only if you can afford a full index scan, or use an estimate from planner statistics and label it as an estimate.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21Your playlist PATCH endpoint receives valid JSON where tempo is the string "fast" instead of a number. Which status code do you return, and what must the body contain so the client can fix that field?

The 90-second answer

Return 422 Unprocessable Content with a problem-details body. The request is syntactically valid JSON, so 400 would tell the client the server could not parse what it sent, which is false. RFC 9110 defines 422 for a well-formed request whose content fails the server's semantic rules, and a string where tempo should be a number fits that exactly. I keep 400 for decoder failures: a missing brace, a trailing comma, or a body the parser cannot read at all.

The mechanism is two stages. The framework first decodes bytes into a document, and that step can only fail as a syntax error, so 400 fits there. The handler then checks the parsed document against the schema, and the failure belongs to a specific field. Many decoders collapse both stages into one error, which is how teams end up returning 400 for a type mismatch. Split them in the error path.

InputStageStatuscode
{"tempo": 120,decoder400malformed_json
{"tempo": "fast"}schema check422validation_failed
{"tempo": 120} sent as text/plainmedia check415unsupported_media_type

The body is problem details (RFC 9457, which replaces RFC 7807), served as application/problem+json:

{"type":"https://api.example.com/problems/validation-failed","title":"Request failed validation","status":422,"code":"validation_failed","errors":[{"pointer":"/tempo","code":"wrong_type","detail":"expected number"}]}

The pointer is a JSON Pointer (RFC 6901), so the client can highlight the exact input. Clients branch on code and errors[].code, never on detail, which is human text and may change.

Trade-off. Hand-written validation keeps your codes stable but costs maintenance on every endpoint. A schema-driven validator gives consistent messages for free, but its default wording leaks into the contract. Either way, map validator keywords onto your own fixed code set and freeze that set with contract tests.

Failure mode and detection. A jump in 400 responses on one route after a client release usually means the client now sends a body the server cannot decode, for example a changed encoding. Watch the 400 to 422 ratio per route on a dashboard so the change shows up within a day of the release.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22Why can't you revoke a JWT on the server the way you delete a session cookie's row?

The 60-second answer

A session cookie carries an opaque ID. The server holds the session row, so logout deletes that row and the next request fails the lookup.

A JWT is self-contained. The API verifies its signature and reads its claims without touching a store, so the server keeps no record that the token exists. There is no row to delete. Until exp passes, a validly signed token is accepted.

That is the rule to state first: revocation needs server-side state, and a stateless token has none. Making a JWT revocable means adding that state back, usually as a denylist keyed by jti, which costs a lookup on each request.

PropertySession cookieJWT (access token)
Server holds per-token stateyes, the session rowno
Logout takes effect on next requestyes, delete the rowno, unless denylisted
Per-request store readonenone

Trace. A user logs out at 10:00:00 with an access token whose exp is 10:15:00. A request at 10:00:30 carrying that token still passes: the signature is valid and exp is in the future. Nothing on the server knows about the logout.

Storage. Session cookies should be HttpOnly, Secure and SameSite, which keeps script from reading them. Tokens in localStorage are readable by any injected script.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23Your API issues OAuth 2.0 access tokens to a single-page app using the authorization code flow with PKCE. Explain what the code verifier protects against that the redirect URI check does not, and where the access and refresh tokens should live in the browser and on your backend, with the reasons.

The 90-second answer

PKCE binds the authorization code to the client instance that started the flow. The client generates a random code_verifier, sends code_challenge = BASE64URL(SHA256(code_verifier)) with code_challenge_method=S256 on the authorize request, and presents the raw verifier at the token endpoint. The redirect URI check stops the code going to the wrong place. It does nothing about a code that is already in the wrong place. PKCE covers that case: an attacker who intercepts the code through a malicious app that registered the same custom scheme, a logged URL, or a hostile browser extension cannot exchange it, because they never saw the verifier.

For a public client (an SPA or native app with no secret), the verifier is the only proof of possession the token endpoint gets. Without it, the code is a bearer credential for a few minutes.

Tokens: the access token should not sit in localStorage or any JavaScript-readable store if you can avoid it. Any XSS then exfiltrates a token that works from any machine until expiry. The stronger pattern is a backend-for-frontend: the BFF runs the code exchange with the verifier, keeps the refresh token server-side, and gives the browser an HttpOnly; Secure; SameSite=Strict session cookie. The SPA then calls the API through the BFF, which attaches the access token. If you must hand the access token to the browser, keep it in memory only, keep its lifetime short (5 to 15 minutes), and do not issue a refresh token to the public client at all, or use rotation with reuse detection (OAuth 2.0 Security BCP, RFC 9700, requires this for public clients that get refresh tokens).

The exchange, step by step

StepWhoWhat crosses the wire
1clientverifier = 43–128 unreserved chars, from a CSPRNG
2client → ASGET /authorize?response_type=code&client_id=…&code_challenge=E9Mrozo…&code_challenge_method=S256&state=…
3ASstores code → (challenge, client_id, redirect_uri, expiry), redirects with code
4client → ASPOST /token with grant_type=authorization_code, code, code_verifier, redirect_uri
5ASrecomputes SHA256(verifier), compares to stored challenge, returns tokens

Trace with a hypothetical attacker: the attacker gets code=X from a leaked redirect. They post code=X to /token with a verifier they guessed. The AS hashes the guess, it does not match E9Mrozo…, and the response is 400 invalid_grant. The legitimate client's verifier was 256 bits from a CSPRNG, so guessing it is not a realistic route.

Failure modes to check

  • plain method: if the AS accepts code_challenge_method=plain or silently falls back to it when the method is missing, the challenge equals the verifier and the attacker who sees the authorize URL wins. Reject anything but S256.
  • Verifier reuse across flows: generate a fresh verifier per authorization request, store it with the in-flight state, and discard it after the exchange.
  • Code replay: the AS must consume the code on first use and revoke tokens already issued from it if it is presented twice. Detection shows up as invalid_grant on the second request plus a revocation event in the audit log.
  • state is for CSRF on the redirect, not for code interception. Keep it, but do not confuse the two.

When not to rely on PKCE alone

If the client is a confidential server-side app, use a client secret or private_key_jwt as well. PKCE is additive and RFC 9700 recommends it for all clients, but the secret is what authenticates the client itself.

Specs: RFC 7636 (PKCE), RFC 9700 (OAuth 2.0 Security Best Current Practice, January 2025). Versions and defaults here assume those documents.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24A handler loads an order by the id in the URL, and the caller is authenticated but may belong to a different tenant. Compare fetching the order and then comparing its tenant to the caller's, with putting the tenant predicate in the WHERE clause. What is the main trade-off in IDOR exposure, and what does the caller see for a foreign id?

The 90-second answer

Put the tenant predicate in the query. SELECT id, status, total_cents FROM orders WHERE id = $1 AND tenant_id = $2 returns zero rows for another tenant's order, and the handler maps zero rows to the same 404 order_not_found it returns for an id that does not exist. The fetch-then-compare alternative loads the row by id and checks order.tenant_id == caller.tenant in code. It works, but it puts the authorization decision in every code path that reads orders, and one path that forgets the if leaks the row. The main trade-off is that the query-side check makes the safe behaviour the default, at the cost of every query on the table carrying the tenant argument.

Assumptions: the caller is already authenticated, and the policy is "same tenant". Role checks (a viewer may not cancel) still belong in the handler after the row is found.

PlacementWhat a foreign id returnsFailure you will see
Fetch by id, compare in codethe row is loaded; a 403 or 404 depends on the brancha second handler reads the row and skips the compare
Predicate in WHEREzero rows, identical to a missing ida query written without the tenant argument, silently cross-tenant

Trace. Tenant t_17 requests GET /orders/42. Order 42 belongs to t_99.

SQL
SELECT id, status, total_cents FROM orders WHERE id = 42 AND tenant_id = 't_17';
-- 0 rows

A request for order 999, which does not exist, produces the same zero rows and the same status and body. An attacker enumerating ids cannot tell the two apart. The fetch-then-compare version instead distinguishes them: a 403 on order 42 confirms the id exists.

Writes. UPDATE orders SET status = $3 WHERE id = $1 AND tenant_id = $2, then check rows_affected. Zero means the caller cannot touch that order, and the handler should not run a follow-up read that reveals whether the row exists.

The cost on the query side. A missed predicate is a silent cross-tenant read, so the defence is a repository layer that requires the tenant argument, not a comment in the handler. Row-level security (PostgreSQL CREATE POLICY ... USING (tenant_id = current_setting('app.tenant_id'))) moves the guarantee into the database, but it requires setting a session variable per connection, so pooled connections must reset it on checkout.

Detection. Write one test per endpoint that creates two tenants and asserts that a cross-tenant read or write returns the same status as a nonexistent id. Log zero-row writes with the tenant id and alert when that rate rises for one tenant, since that pattern is what enumeration looks like.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25Your orders table has a nullable customer_id column. A teammate writes SELECT id FROM customers WHERE id NOT IN (SELECT customer_id FROM orders) to find customers with no orders, and it returns zero rows in production. Explain why, and rewrite the query so it behaves correctly.

The 90-second answer

The subquery returns a set that contains NULL. x NOT IN (…) is defined as x <> v1 AND x <> v2 AND …. If any v is NULL, x <> NULL evaluates to UNKNOWN, not TRUE. TRUE AND UNKNOWN is UNKNOWN, and WHERE keeps only TRUE rows. So every customer is filtered out, and the query returns nothing, not the customers without orders.

The fix is an anti-join. Use NOT EXISTS, which tests for the absence of a matching row and never compares against a NULL value. LEFT JOIN … WHERE o.customer_id IS NULL is the other common form, and it also avoids the problem.

SQL
SELECT c.id
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);

If you must keep NOT IN, filter the NULLs out of the subquery: WHERE customer_id IS NOT NULL. That is correct but fragile, because the next person who drops that predicate reintroduces the bug.

Mechanism, with a trace

Assume customers has ids 1, 2, 3 and orders.customer_id holds 1, NULL.

Check for customerc.id <> 1c.id <> NULLCombined
2TRUEUNKNOWNUNKNOWN, dropped
3TRUEUNKNOWNUNKNOWN, dropped
1FALSEUNKNOWNFALSE, dropped

No row survives. Adding more non-NULL orders does not help; one NULL poisons the whole predicate.

Comparing the options

  • NOT EXISTS: NULL-safe, and the planner usually produces an anti-join (hash or merge) with an index on orders(customer_id). Stops at the first match per customer.
  • LEFT JOIN … IS NULL: same semantics here, but it can duplicate rows if the join condition is not unique on the left side, and reviewers find the intent less obvious.
  • NOT IN with IS NOT NULL: correct only while the filter stays in place. Some engines also handle it poorly in the plan.
  • EXCEPT: set semantics treat NULLs as equal, so it returns customers with no orders, but it deduplicates and compares whole rows, so it only fits when the selected columns match.

Failure modes to check

The bug is silent. Empty results look like a valid answer. Detect it by comparing row counts from NOT EXISTS and NOT IN on the same data, and add a test with a NULL foreign key in the fixture. Check the column's nullability in the schema before writing any NOT IN against it, because a NOT NULL constraint would make the original query safe.

When not to use NOT EXISTS: never a reason to avoid it. The one case to watch is a correlated subquery on a huge table without an index on the join column, where the plan degrades to nested loops.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-26In a LEFT JOIN, what is the difference between putting a right-table condition in the ON clause versus the WHERE clause?

The short answer

A condition in ON decides which right-hand rows can match. A left-side row with no match still comes back, with NULLs on the right. A condition in WHERE runs after the join, on the NULL-extended rows. An unmatched left row has NULL in the filtered column, the comparison is unknown, and WHERE drops it. The LEFT JOIN behaves like an INNER JOIN.

Trace it. Assume customers has ids 1, 2, 3, and orders has one paid order for customer 1 and one refunded order for customer 2. Customer 3 has no orders.

SQL
-- A: filter in ON
SELECT c.id, o.id
FROM customers c
LEFT JOIN orders o
  ON o.customer_id = c.id AND o.status = 'paid';

-- B: filter in WHERE
SELECT c.id, o.id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'paid';
CustomerA: ON filterB: WHERE filter
11, paid order1, paid order
22, NULLdropped
33, NULLdropped

In A, customers 2 and 3 survive because the join keeps every left row and only restricts matching. In B, customers 2 and 3 get NULL in o.status, and WHERE keeps only rows where the condition is true. Row count drops from 3 to 1 with no error.

Why it bites in production. Reporting queries often start as LEFT JOINs so that customers without orders appear with zero counts. Someone later adds AND o.status = 'paid' to the WHERE clause, and the zero-count rows disappear. Nothing fails. A dashboard simply shows fewer customers.

Fixes.

  • Move the predicate into ON when you want to filter the right table but keep left rows. Query A does this.
  • Use an INNER JOIN when you truly want inner-join semantics, so the intent is visible.

Detection. Compare row counts before and after a change to the join or filter, and write a test with a left row that has no match.

The rule holds in PostgreSQL, MySQL and SQLite. Confirm against your engine's documentation if you rely on a non-standard mode.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-27Your orders table has 400 million rows and the hot query is `WHERE tenant_id = ? AND status IN ('open','held') AND created_at >= ? ORDER BY created_at DESC LIMIT 50`. Design the composite index: which columns, in what order, and what does the leftmost prefix rule let the planner do with your other single-column indexes?

The 90-second answer

Put the equality column first, then the column you sort on, and keep the range predicate last among the filters. For this query that is (tenant_id, created_at), with status handled as a filter or appended as a third column only if it is needed to avoid a table lookup. The reason is that a B-tree can seek to a single point on a leading equality, then read a contiguous run in index order. A range predicate on a column ends the seek: anything placed after it can only be checked, not used to narrow the scan.

The leftmost prefix rule says an index on (a, b, c) can serve predicates on a, on a and b, or on a, b and c. It cannot serve a predicate on b alone, or c alone, as a seek. So the single-column indexes you already have on tenant_id and created_at are mostly redundant once the composite exists, and keeping them costs write amplification on every insert.

Why the order matters: a worked trace

Assume (hypothetical figures) 400M rows, 2,000 tenants, a tenant with 200,000 rows, and about 3% of those open or held.

IndexSeekRows read from indexSort needed
(tenant_id, status, created_at)tenant + status IN list (2 seeks)~12,000 matches, merged across two rangesyes, merge of two sorted runs or a sort
(tenant_id, created_at)tenant, then walk backwards from neweststops after ~50 matches if status is cheap to check on the rowno
(created_at, tenant_id)range on created_atevery row in the window across all tenantsyes, and scans far more

With (tenant_id, created_at), the planner walks the index backwards from the newest entry for that tenant, applies the status check to each row it fetches from the heap, and stops after 50 qualifying rows. If the selected status is rare among recent rows, it fetches more rows before the limit is hit. That is the failure mode to watch: a tenant whose recent orders are almost all closed forces a long walk with a heap fetch per row. You see it as high Buffers/shared hit counts with few returned rows in EXPLAIN (ANALYZE, BUFFERS).

Putting status before created_at looks attractive for the filter, but IN with two values is two seeks, each returning results in created_at order, so the database must merge them to honour ORDER BY. That merge is cheap for two values and costly for a long list.

Covering and the lookup cost

If the query selects only id, status, created_at, appending status as (tenant_id, created_at, status) allows an index-only scan, provided the visibility map is current. In PostgreSQL that means recent vacuum; in MySQL InnoDB it means the secondary index already carries the primary key, so (tenant_id, created_at, status) is covering for id automatically. Adding columns widens every index entry and every insert pays for it, so do this only for the hot read.

Alternatives and when not to use them

  • Partial index WHERE status IN ('open','held') is smaller and fits in memory if those states are a small fraction. It is wrong if the query's status set varies per request.
  • A separate index on created_at alone is useful only for cross-tenant jobs; for this query it forces a scan of every tenant's rows in the window.
  • Range on the leading column (created_at >= ? first) turns the index into a global time scan. Do not do it for a multi-tenant table.

What to check before shipping

Run EXPLAIN for the three most common tenant shapes: a small tenant, a median tenant, and the largest tenant. Confirm the plan is an index scan with no Sort node for each. Confirm the write cost: measure insert p99 before and after, since every extra index is one more B-tree insert per row.

The leftmost prefix rule is a property of the B-tree's sort order, not a planner preference. Once you can state which predicates are seeks and which are filters for a given column order, the index choice follows from the query rather than from guesswork.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-28Your orders table has 400 million rows. Hot query: SELECT id, status, total_cents FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20. Which single index lets the planner use an index-only scan, and when does an INCLUDE column pay for itself?

The 90-second answer

An index-only scan needs two things. First, every column the query touches (select list, WHERE, ORDER BY) must be available in the index, so the executor never reads the heap for values. Second, the visibility map must mark the heap pages as all-visible, so the executor can skip the per-row visibility check that forces a heap fetch. The first is a schema decision I make. The second is a VACUUM property I have to monitor.

The query selects id, status and total_cents, so all three must be in the index. A plain (customer_id, created_at DESC) index covers the access path but not the select list, and forces a heap fetch for every returned row. I'd add the output columns with INCLUDE: CREATE INDEX CONCURRENTLY orders_cust_recent ON orders (customer_id, created_at DESC) INCLUDE (id, status, total_cents);. Putting them in the key would also work, but it changes what the tree is sorted by, and that matters for the trade-off below. Note that the primary key index on id does not help here. The planner needs one index that carries all five columns.

Why the planner needs the columns in the index

The key columns give you the seek and the ordering. Included columns are stored only in leaf tuples. They are not part of the btree ordering and cannot be used as search or sort keys. So for WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20 the scan descends on customer_id, walks backwards along created_at, stops after 20 rows, and reads id, status and total_cents from the leaf. No sort node, no heap.

If the visibility map is stale, the plan still says Index Only Scan but EXPLAIN (ANALYZE, BUFFERS) shows a nonzero Heap Fetches: line. That number is the check I'd put on a dashboard. A table with heavy inserts and few vacuums can show most heap pages as not all-visible, which makes the index-only plan barely better than the plain index.

Trace (hypothetical figures, PostgreSQL 16)

IndexPlanHeap fetchesp99 for LIMIT 20
(customer_id, created_at DESC)Index Scan20 per call2 ms
same plus INCLUDE (id, status, total_cents), table vacuumedIndex Only Scan00.6 ms
same plus INCLUDE (id, status, total_cents), table not vacuumed for a weekIndex Only Scan17 per call1.4 ms

The third row is the one that surprises people. The plan is the same, the index is the same, and the visibility map is the only thing that changed.

When INCLUDE pays for itself

The INCLUDE version wins on three counts. It keeps the tree shallower and smaller, because the included columns do not add to the comparison key. It keeps the ordering semantics of the key clean. And it lets you add output columns without changing what the index searches on. It stops paying when the included columns are wide or change often. Every UPDATE that touches status now touches an indexed column, so HOT updates are lost and every status change writes to this index as well. If status changes several times per order, that write amplification can cost more than the read saving.

The rule I use: include columns that are read on the hot path, are small, and are stable. Leave out large columns such as JSON payloads. For those, a plain index plus a heap fetch is cheaper than a fat index that every write has to maintain.

Failure modes I'd check

First, a query that later adds a column to the select list silently drops back to a heap fetch. A regression test that asserts Index Only Scan in the plan catches it. Second, an index created without CONCURRENTLY blocks writes on a table this size, so it must be built concurrently. Third, autovacuum falling behind on a write-heavy table, which shows up as rising Heap Fetches and is fixed with per-table vacuum settings rather than by changing the index.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-29Your GET /orders endpoint runs 51 SQL statements for a page of 50 orders, each customer lookup differing only in its id. How would you confirm the N+1 pattern from the logs, and how would you fix it with a join or a batch fetch?

The 90-second answer

The log shows one query for the page and one query per row for the customer. That is N+1: 1 + 50 = 51 statements where two would do. I would confirm it from the log first, then fix it with a batch fetch. A join is fine for a to-one relation like customer, provided the query has no LIMIT over joined rows and the nullable foreign key is handled.

Detecting it from logs

Group statements by request id, replace literals with placeholders, and count repeats of the same template.

req=a91 SELECT id, customer_id, total FROM orders WHERE status = ? LIMIT ?
req=a91 SELECT id, name FROM customers WHERE id = ?   (params: 17)
req=a91 SELECT id, name FROM customers WHERE id = ?   (params: 22)
... 48 more, same template

The signal is one template repeated roughly N times per request, with bind parameters that vary and a count that tracks the page size. Latency that grows linearly with limit points the same way.

Fix A: join

SQL
SELECT o.id, o.total, c.id AS customer_id, c.name
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'open'
ORDER BY o.id
LIMIT 50;

One round trip. The LEFT JOIN matters because customer_id is nullable: an inner join silently drops orders with no customer. The join is safe here only because customer is to-one, so each order appears exactly once and LIMIT 50 still counts orders. Add a to-many join such as order items and the same statement returns one row per item, so the page comes back short.

Fix B: batch fetch

SQL
SELECT id, name FROM customers WHERE id = ANY($1);  -- $1 = distinct customer ids from the page

Two round trips total, whatever the page size. No row multiplication, so LIMIT keeps its meaning. The costs are a second round trip and an IN list that must be deduplicated and chunked for very large pages.

Arithmetic, with hypothetical figures

Assume 0.4 ms per same-AZ round trip including parse. The N+1 path spends about 51 × 0.4 ≈ 20 ms in round-trip overhead alone. Two round trips spend about 0.8 ms. The database work may be similar, so the saving is mostly network and parse cost, and it grows with page size.

ORM equivalents

  • SQLAlchemy: selectinload(Order.customer) issues the batch IN query; joinedload issues the join.
  • Django: select_related('customer') is the join for to-one relations; prefetch_related('customer') is the batch fetch.

Failure modes to name

  • A join over a to-many relation with LIMIT returns short pages, which clients see as 37 orders on a page of 50.
  • A batch fetch with an unbounded IN list hits parser or plan limits on a very large page.
  • An N+1 that appears only for some callers, because a serializer touches a relation conditionally, escapes a happy-path test. Count queries for each response shape.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-30In PostgreSQL, does REPEATABLE READ allow phantom reads, and why or why not?

Short answer: No. PostgreSQL's REPEATABLE READ takes one snapshot at the first statement of the transaction and every later statement reads from that snapshot. Rows that another transaction inserts and commits after that point stay invisible, so a range query returns the same set when re-run. The SQL standard lets REPEATABLE READ permit phantoms; PostgreSQL does not, so its REPEATABLE READ behaves as snapshot isolation.

Where each anomaly sits. READ COMMITTED takes a new snapshot per statement, so it allows non-repeatable reads and phantoms. REPEATABLE READ prevents both for reads. Lost updates are a separate case: REPEATABLE READ does not let two read-modify-write transactions silently overwrite each other. If the second transaction tries to update a row that a concurrent transaction already changed and committed, PostgreSQL aborts it with SQLSTATE 40001, 'could not serialize access due to concurrent update', and the application must retry. READ COMMITTED does not raise that error on a plain read-then-write, so the lost update happens unless you use SELECT ... FOR UPDATE or an atomic update.

Trace (hypothetical data, tenant 7 has 10 open orders):

StepTransaction A (REPEATABLE READ)Transaction B
1SELECT count(*) FROM orders WHERE tenant_id = 7 returns 10
2INSERT a tenant 7 order, COMMIT
3same SELECT returns 10
4COMMIT

At READ COMMITTED, step 3 returns 11. That difference is the phantom.

Lost update in code. Under READ COMMITTED, this pattern loses a debit when two requests run together:

SQL
-- app reads balance = 100, computes 50, writes it back: both requests write 50
SELECT balance FROM accounts WHERE id = 1;
UPDATE accounts SET balance = 50 WHERE id = 1;

The fix is to let the database do the arithmetic in one statement: UPDATE accounts SET balance = balance - 30 WHERE id = 1 AND balance >= 30, then check the affected row count. With SELECT ... FOR UPDATE the second transaction blocks until the first commits, then reads the new value.

When REPEATABLE READ is not enough. Write skew is the anomaly it still allows. Two transactions each read a set of rows, decide based on it, and write disjoint rows, so neither sees a conflict. Example: two on-call doctors each check that the other is on call, then both go off call. Use SERIALIZABLE (SSI), which detects the dangerous structure and aborts one transaction with 40001, or make the constraint explicit with a unique index or an exclusion constraint.

Failure mode to watch. Under REPEATABLE READ and SERIALIZABLE, any 40001 error is a retry signal, not a bug. Code that does not retry will show intermittent failures under load that look like data corruption but are not.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-31Two doctors are on call and the rule is that at least one must always be on call. Two requests each take their own doctor off call at the same moment on PostgreSQL REPEATABLE READ. Walk me through how the rule breaks, why no row is written twice, and the two fixes you would ship with their costs.

The 90-second answer

This is write skew. Both transactions read a snapshot in which two doctors are on call, each checks the rule (count is at least 1), and each writes a different row. Snapshot isolation only detects conflicts when two transactions write the same row, so both commit and nobody is covering the shift. I would fix it with SERIALIZABLE and a retry loop where the team can absorb retries. Where they cannot, I would put the invariant on a single parent row and have every leave transaction take a write lock on that row before it reads the count. Under REPEATABLE READ that lock must be a write, not a bare SELECT ... FOR UPDATE, or the second transaction keeps its stale snapshot.

Trace

Schema: oncall(doctor_id int primary key, team_id int, on_call bool) with doctors 1 and 2 both true on team 7.

stepT1 (Dr 1 leaves)T2 (Dr 2 leaves)
1BEGIN (snapshot taken at first statement)BEGIN (snapshot taken at first statement)
2SELECT count(*) FROM oncall WHERE team_id=7 AND on_call → 2SELECT count(*) FROM oncall WHERE team_id=7 AND on_call → 2
3UPDATE oncall SET on_call=false WHERE doctor_id=1UPDATE oncall SET on_call=false WHERE doctor_id=2
4COMMIT okCOMMIT ok

Zero doctors on call. Neither transaction wrote a row the other wrote, so there was no write-write conflict to abort on. Each snapshot only saw its own doctor's update, and each count was correct for the snapshot it read.

Fix 1: SERIALIZABLE with retry. PostgreSQL implements SERIALIZABLE with SSI since 9.1. It records rw-antidependencies (T1 read a row T2 wrote, and the reverse), finds the dangerous cycle at commit, and aborts one side with SQLSTATE 40001. The client must retry the whole transaction, so the retry loop belongs in one shared helper, not at each call site. Costs: false positives on unrelated rows that share index or page predicates, extra retries under contention, and a predicate-lock footprint that grows with the number of concurrent serializable transactions.

Fix 2: materialise the conflict on a parent row. Create coverage(team_id int primary key, version bigint not null default 0). Every leave transaction starts with a write to that row, then does the count and the update:

SQL
BEGIN ISOLATION LEVEL REPEATABLE READ;
UPDATE coverage SET version = version + 1 WHERE team_id = 7;  -- first statement, takes the row lock
SELECT count(*) FROM oncall WHERE team_id = 7 AND on_call;
UPDATE oncall SET on_call = false WHERE doctor_id = 1;
COMMIT;

The second transaction blocks on the UPDATE coverage until the first commits. When it proceeds under REPEATABLE READ, its snapshot predates the first commit, and PostgreSQL raises 40001 (could not serialize access due to concurrent update) because the row it is updating was changed by a committed transaction it cannot see. The client retries, the new snapshot shows one doctor on call, and the rule holds. Under READ COMMITTED the same pattern also works without the retry: SELECT ... FOR UPDATE on the coverage row, then the count, because each statement takes a fresh snapshot after the lock is granted. Pick one; mixing them across code paths is how this breaks.

Costs: every leave for a team serialises, so throughput per team is one commit at a time. That suits a rota, and it is wrong for a hot global counter. Locking only the doctor rows does not work, because a doctor added to the rota mid-transaction is a phantom that neither transaction sees.

Failure modes and how to detect them. Retry storms under SERIALIZABLE show as a rising rate of 40001 in application logs, which should be a metric, not something you grep for. Lock waits on coverage show in pg_locks with granted = false and as p99 growth on the leave endpoint. Deadlocks happen if one code path locks doctor rows before coverage and another does the reverse, so the rule is coverage first, always.

What does not fix it. A unique partial index can enforce at most one on-call row per shift. It cannot enforce at least one, so it does nothing for this rule. A check constraint is per row and has the same problem. Anything that checks a rule across rows needs either serializable execution or a lock on a row that all the participating transactions must write.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-32Two transfer requests run concurrently. One locks account A then B, the other locks B then A. Explain the wait-for cycle that causes the deadlock, then the lock ordering rule that removes it, and how you would apply that rule when the set of accounts is only known after reading the request.

The 90-second answer

A deadlock needs a cycle in the wait-for graph: T1 holds A and waits for B, while T2 holds B and waits for A. Neither can proceed, and neither releases what it holds. The fix is a global total order on lock keys. If every transaction acquires locks in ascending key order, a cycle cannot form, because a cycle would need some transaction to wait for a smaller key while holding a larger one.

In a transfer service the account set is only known once the request is parsed, so I collect the ids first, deduplicate, sort, then lock each one in that order. Ordering alone is not enough in practice, so I also retry the whole transaction on the database's deadlock error.

The trace (hypothetical timings)

t (ms)T1 (transfer A to B)T2 (transfer B to A)
0UPDATE accounts SET ... WHERE id = A (locks A)
1UPDATE accounts SET ... WHERE id = B (locks B)
2UPDATE ... WHERE id = B blocks, waits on T2
3UPDATE ... WHERE id = A blocks, waits on T1
4cycle T1 to T2 to T1 existscycle exists
1000detector picks a victim, returns 40P01

Postgres checks for cycles after deadlock_timeout, which defaults to 1 s, so the stall is visible as a one second pause before the error. MySQL InnoDB detects the cycle immediately on the blocking lock request and rolls back one victim, returning error 1213.

Applying the rule

Python
def transfer(conn, src, dst, cents):
    keys = sorted({src, dst})
    with conn.transaction():
        for k in keys:  # ascending id, always
            conn.execute('SELECT id FROM accounts WHERE id = %s FOR UPDATE', (k,))
        conn.execute('UPDATE accounts SET balance = balance - %s WHERE id = %s', (cents, src))
        conn.execute('UPDATE accounts SET balance = balance + %s WHERE id = %s', (cents, dst))

I lock with one statement per key rather than ORDER BY id FOR UPDATE over an IN list, because the locking order then does not depend on the query plan. Locking explicitly before any update also means the sorted order is the lock order, not just the order of the writes.

Failure modes and how to see them

  • Locks held across a network call. If the transaction calls the payments provider while holding account locks, the wait-for chain includes an external dependency the database cannot see, and you get stalls rather than deadlock errors. Keep the external call outside the transaction.
  • Ordering only within one code path. A batch job that locks accounts by a different key, such as customer_id, reintroduces the cycle. Document the ordering in one place and reuse the helper everywhere.
  • Index and gap locks. InnoDB locks index ranges, so two transactions locking different ids can still conflict on a range scan. Ordering by primary key does not cover a range UPDATE that locks gaps.
  • Retries without backoff. Retrying immediately makes the same two transactions collide again. Retry a bounded number of times with jittered backoff, and only for the deadlock error code.

Detection: Postgres logs each deadlock with both statements when log_lock_waits is on, and pg_locks joined to pg_stat_activity shows the chain while it is happening. InnoDB keeps the last deadlock in SHOW ENGINE INNODB STATUS. A rising deadlock count after a deploy usually means a new code path breaks the order.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-33Your order service lets several agents amend the same order at once. At what contention level does optimistic locking beat pessimistic row locking, and what does each conflicting retry cost you?

The 60-second answer

Pessimistic locking wins when conflicts are frequent and the work inside the lock is long. Optimistic locking wins when conflicts are rare and the work is short and free of side effects. The crossover is set by the per-attempt conflict rate and the hold time. Under optimism, every conflict throws away the work done since the read, so the retry cost is that wasted work plus whatever side effects you already triggered.

Mechanism

Pessimistic: SELECT ... FOR UPDATE takes a row lock that stays until commit. A second writer blocks, and its latency is the remaining hold time of the first.

Optimistic: read a version column, then write with a compare-and-set.

SQL
UPDATE orders SET status = 'held', version = version + 1
WHERE id = 42 AND version = 7;
-- rows affected = 0 means someone committed first

Trace: A and B both read version 7. A's update matches one row and commits, so the version becomes 8. B's update matches zero rows. B re-reads, sees version 8, reapplies its change, and retries the update with version 8.

Cost model

Let W be the work inside the transaction and p the probability that an attempt conflicts. With independent retries, the expected attempts per success are 1 / (1 - p). Expected wasted work per success is W × p / (1 - p).

A hypothetical example: W = 4 ms, so one hot order handles at most 250 serialized writes per second under pessimism. If 50 writers arrive together, the last one waits roughly 200 ms. Under optimism with p = 0.2, each success costs about 1.25 attempts, so 5 ms of expected work, and nobody queues. At p = 0.8 the same workload costs 5 attempts per success, and pessimism is cheaper.

Per-attempt conflict rate pExpected attempts per successBetter fit at W = 4 ms
under 0.1about 1.1optimistic
0.3 to 0.51.4 to 2optimistic if W stays short and retries are capped
over 0.7over 3pessimistic, or queue writes per order

The thresholds are rules of thumb. Measure p from rows-affected-zero rates, not from intuition.

Retry cost is not only CPU

A retry that re-runs a payment-provider call or sends an email has no safe undo. Move side effects after commit, through an outbox, so the retry loop touches only the database. Bound retries at 3 to 5 with jittered backoff, or a hot row becomes a retry storm.

Failure modes and detection

  • Lost update: the WHERE version = ? clause is dropped in one code path. Detect it with a test that runs two concurrent amends and asserts one fails.
  • Starvation: one writer keeps losing on a hot row. Detect it from the retry-count histogram and the p99 retry depth.
  • Pessimistic deadlock: two transactions lock rows in opposite order. PostgreSQL aborts one with SQLSTATE 40P01. MySQL InnoDB reports 1213. Fix it with a consistent lock order.
  • Long waits: MySQL InnoDB's innodb_lock_wait_timeout defaults to 50 s. PostgreSQL's lock_timeout defaults to 0, which means no limit, so set it explicitly.

State the crossover you measured, and say which side of it the order-amend path sits on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-34In a transactional outbox, why must the business row and the event row be written in the same database transaction?

The 60-second answer

The outbox exists so that a state change and the event announcing it cannot disagree. If I write the order row to the database and then publish OrderPlaced to Kafka as a separate step, either step can fail alone. A crash after the commit and before the publish loses the event. A publish that succeeds followed by a failed commit announces an order that does not exist. Neither database nor broker can join both writes in one atomic unit, so I stop trying to.

Instead I insert the event into an outbox table inside the same transaction as the business write. Both rows commit or neither does. The event is now durable exactly when the state change is.

SQL
BEGIN;
INSERT INTO orders (id, customer_id, status, total_cents)
  VALUES (42, 'c_8f21', 'placed', 4999);
INSERT INTO outbox (id, aggregate_id, event_type, payload, created_at)
  VALUES (gen_random_uuid(), 42, 'OrderPlaced',
          '{"order_id":42,"total_cents":4999}', now());
COMMIT;

A separate relay process then reads unpublished rows and pushes them to the broker. The relay is what turns this into delivery, and it is where the guarantee gets its shape.

Trace of a crash

StepActionBusiness rowOutbox rowBroker
1COMMITcommittedcommittednone
2relay reads row, publishescommittedcommittedOrderPlaced
3relay crashes before marking row sentcommittedcommittedOrderPlaced
4relay restarts, reads row again, publishes againcommittedcommittedOrderPlaced x2
5relay marks row sentcommittedsentOrderPlaced x2

Step 3 to 4 is the at-least-once. The event is never lost, because it was durable before any publish. It can be sent twice, because the relay marks the row only after the broker acknowledges, and a crash in between leaves it unmarked.

Why at-least-once and not exactly-once

The relay has no way to know whether the broker received a publish whose acknowledgement it never saw. Retrying is the only safe move, so duplicates are the price. Consumers must be idempotent: deduplicate on the event id in a processed-events table, or make the handler naturally idempotent (an upsert keyed on order_id). Kafka's idempotent producer only removes duplicates on its own partition and session, so it does not change this for an external consumer.

Alternatives and when not to use the outbox

  • Change data capture (Debezium tailing the WAL or binlog) removes the polling relay and gives lower latency. It still needs the outbox table, because raw table changes leak internal schema. Use it when polling load or latency matters.
  • Polling the business table for changed rows misses deletes and cannot see intermediate states. Avoid it for events.
  • Dual writes with a compensating job are what the outbox replaces. Skip the pattern entirely if the consumer tolerates loss and the event is only telemetry.

Failure modes to name

  • Relay falls behind: outbox rows with sent_at IS NULL grow, and the age of the oldest unsent row climbs. Alert on that age, not the row count.
  • Outbox table bloat: sent rows accumulate, slowing the relay's scan. Delete or partition by day after sending.
  • Out-of-order publish: two relays or retries can reorder events for one aggregate. Partition the broker topic by aggregate_id and keep one relay per partition, or carry a version and let consumers ignore stale ones.
  • Payload drift: the event is written inside the transaction, so schema changes to the payload need the same versioning discipline as any API.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-35A client retries POST /payments after a timeout and gets a 409 on the second attempt while the first is still in flight. Walk me through what your idempotency key store must hold, what you replay when the first request later succeeds or fails, and how long you keep each key.

The 90-second answer

The store needs one row per (tenant, key) with a request fingerprint, a state (in_progress, completed), the stored status and body once finished, and timestamps. The fingerprint is a hash of the method, path and canonicalised body, so a reused key with a different payload is rejected with 422 idempotency_key_reused instead of silently returning someone else's charge.

When the retry arrives while the first request is still running, the server cannot replay a response that does not exist yet. It returns 409 request_in_progress with Retry-After, and the client retries with the same key. I would not block the second request on a lock held across the payment provider call, because a stuck worker then pins a connection for the full provider timeout.

Replay rule. Store the response only when the outcome is a durable business result: 2xx, and 4xx validation failures that do not depend on transient state. Do not cache 5xx or 429. If the first attempt died mid-flight (process crash after the provider charged but before the response was saved), the key stays in_progress until its lease expires. The reconciler then asks the provider by our own reference id, not by the key, and writes the true outcome. Replaying a stale in_progress as success is the failure to avoid.

Trace.

tEventKey row
0 msrequest 1 inserts key, fingerprint a9e1, lease 30 sin_progress
900 msclient times out at 800 ms, sends request 2row found, same fingerprint
900 msserver returns 409 request_in_progress, Retry-After: 1unchanged
1.2 srequest 1 gets provider success, writes 201 bodycompleted, status 201
2.0 srequest 3 (retry)replays stored 201 with same body

Expiry. Keep completed keys for at least as long as the longest client retry window plus reconciliation lag. For payments I use 24 h for replay and keep the payment record itself as the durable dedupe source beyond that. Expiring a key does not make a retry safe by itself: after expiry, a retry with the same key is a new request, so the business uniqueness constraint (for example a unique provider reference per order) must still reject the duplicate.

Alternatives. Client-generated keys versus server-derived keys: derived keys avoid trusting clients but cannot distinguish two intentional identical payments, so the client key is usually right. Storing the key in Redis is fast but loses in-flight state on eviction; a relational row in the same transaction as the business write avoids that gap.

Failure modes to check. A key reused across tenants without tenant scoping collides. A lease that expires while the provider call is still running allows a second charge, so the lease must exceed the provider timeout. Monitor the count of in_progress rows older than the lease: it should be zero except during deploys.

Assumptions: PostgreSQL-backed store, provider supports lookup by our reference id.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-36Your listening-events table in DynamoDB is keyed by track_id, and one viral track takes 6,000 writes per second while the table's total capacity is ample. Why does that throttle, and how would you redesign the key without breaking the plays-per-track-per-hour query?

The 90-second answer

Adaptive capacity moves throughput between partitions, but it cannot split one partition key value. Every item with track_id = T lives on one partition, and each partition has a per-partition write limit of 1,000 WCU per second (check the current DynamoDB quotas page, since these limits change). Six thousand writes per second to one key needs six partitions' worth of writes, and that one key cannot be spread. I would make the key carry a shard suffix so the write load fans out across keys, then accept that reads become a scatter-gather.

Sharding: pk = TRACK#<track_id>#S<n> where n = hash(user_id) mod 10. Ten shards put 600 WCU per second on each key, under the limit with headroom. The sort key stays HOUR#<yyyy-mm-ddThh>#<event_id>, so the hourly query stays a key-range read.

Trace, with hypothetical figures:

StepPartition keyLoad per key
beforeTRACK#T6,000 WCU/s, throttled above 1,000
afterTRACK#T#S0 … S9600 WCU/s each
read one hour10 Query calls, sum results10 requests per dashboard refresh

Reading one hour means ten Query calls with sk begins_with HOUR#2026-11-25T14, run in parallel. At 21.6 million events per hour (6,000 × 3,600), summing 10 paginated result sets is not a dashboard-sized problem, but it is a cost you pay on every read.

The better fix for this query is to stop writing raw events to the hot key at all. A stream processor (Kinesis Data Analytics or a Flink job) aggregates plays into one-minute buckets per track and writes one UpdateItem ADD per track per minute. That is 60 writes per track per hour, not 21.6 million, and the dashboard reads a single item per minute. Keep the sharded raw table only for the replay and audit path, where scatter-gather is acceptable.

When not to shard: if the key's traffic is below about 1,000 WCU, sharding only adds read cost. Shard count is also a decision you cannot easily undo. Changing N means writing new items under a new scheme and migrating readers, so pick it from measured peak rather than from a round number.

Failure modes and detection. The symptom is ProvisionedThroughputExceededException on a table with spare capacity; CloudWatch WriteThrottleEvents shows it, but it does not say which key. Use CloudWatch Contributor Insights on the table to find the top partition keys, which names the hot track_id directly. A second failure: a bad hash function (for example, hashing a field with low cardinality) gives you 10 shards with 9 of them idle. Check per-shard write counts after rollout, not just the aggregate.

The mistake I would correct in a candidate: choosing the key from the entity you think of as primary, rather than from the access pattern and the write distribution. Write the query first, then check that no single key value carries more than the per-partition limit at peak.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-37Your track-metadata cache runs Redis at its maxmemory limit with session keys that have TTLs and catalog keys that do not. Compare allkeys-lru with volatile-lru: what does each evict, and how does memory pressure show up in latency?

The 90-second answer

Both policies approximate LRU by sampling, not by keeping an exact recency list. The difference is the candidate set. allkeys-lru may evict any key. volatile-lru may evict only keys that have an expiry set. In our cache that means allkeys-lru can evict catalog keys with no TTL, while volatile-lru protects them but can run out of candidates and start failing writes with OOM. Memory pressure then shows up first as eviction work on the write path, and as latency spikes when the evicted values are large.

Config and what to watch

maxmemory 12gb
maxmemory-policy volatile-lru
maxmemory-samples 5

The default maxmemory-samples is 5. Redis samples that many candidate keys from the eligible set, keeps a small pool of the best candidates across evictions, and evicts the one with the oldest idle time. Raising the sample count improves LRU accuracy at the cost of more CPU per eviction.

PolicyCandidate setUnder pressure with no TTL keys leftProtects
allkeys-lruevery keykeeps evicting, never OOMsnothing in particular
volatile-lrukeys with an expirywrites return OOMkeys without TTL
noevictionnonewrites return OOMeverything

Trace. Assume 12 GiB maxmemory, 9 GiB of session keys with EX 1800, and 3 GiB of catalog keys with no TTL. Under volatile-lru, once sessions fill their 9 GiB and new session writes push memory over the limit, the server samples only session keys. Catalog data stays put. Now suppose a deploy stores 2 GiB of unexpiring feature counters. The eligible set shrinks to sessions, and if sessions are not in the candidate set anymore, the next SET returns OOM command not allowed. Under allkeys-lru the same deploy silently evicts catalog entries, and the miss rate on the metadata path climbs without any error.

TTL matters for a second reason. Expired keys are removed lazily on access and by active expiry, which samples keys about 10 times per second by default (hz 10). If expired keys are still in memory when the limit is hit, eviction may remove live keys first even though dead ones are waiting to be reclaimed. Check expired_keys and evicted_keys in INFO stats together to see which path is doing the work.

How pressure appears in latency. Eviction runs synchronously on the command that pushes memory over the limit. That write pays for DEL on every key it evicts. Small keys cost microseconds. A hypothetical 40 MB hash freed in one DEL blocks the event loop for milliseconds, and every client queued behind it waits. In a hypothetical load test, p99 for GET goes from 0.4 ms to 6 ms during eviction bursts that include large hashes. Two checks follow from this. Use UNLINK or enable lazyfree-lazy-eviction so large values are freed in a background thread; the default for this setting varies by version, so verify it for yours. Also count client output buffers and replication backlog, which count toward maxmemory and can trigger eviction without any key growth. LATENCY DOCTOR with latency-monitor-threshold set reports which event (eviction-cycle, expire-cycle, fork) caused a spike.

When I would choose which. I would use volatile-lru when mixed TTL and non-TTL data share one instance and the non-TTL data is more expensive to rebuild than to keep, and I would alert on OOM errors as a capacity signal. I would use allkeys-lru when every key is a rebuildable cache entry and availability of writes matters more than keeping any particular key. Mixing non-TTL keys that must survive (locks, counters) into a allkeys-lru instance is the common mistake, and moving them to a separate instance is usually cheaper than tuning the policy.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-38You have a consistent hash ring with 9 cache nodes holding 10 million keys. You add a 10th node. Roughly what fraction of keys change owner, and what do virtual nodes change about the load on each node?

The 90-second answer

About one tenth of the keys move, so roughly 1 million of 10 million, because the new node takes over one arc of the ring and nothing else changes. Virtual nodes do not change how many keys move. They make each node's share of the ring close to 1/N, so no single node ends up with a lopsided arc.

The ring maps both keys and node names onto the same hash space. A key belongs to the first node clockwise from its hash. When node 10 is inserted at position p, it only takes keys whose hashes fall between p and its predecessor on the ring. Those keys were on its successor, and only those move. Every other key keeps its owner.

Why not modulo. With owner = hash(key) mod N, going from 9 to 10 nodes keeps a key in place only when h mod 9 == h mod 10. That is roughly 1 key in 10, so about 90% move. A cache that loses 90% of its entries on a scale-out event is a stampede waiting to happen.

Worked trace (hypothetical figures). Keys hash to a 32-bit space of 4,294,967,296 positions. Nine nodes each hold one point. Node 10 lands at position 1,000,000,000 and its predecessor sits at 900,000,000. Keys hashing into (900M, 1,000M] move from their old successor to node 10. If that arc is about 1/10 of the ring, about 1 million of the 10 million keys move, and the other 9 million stay put.

Why one point per node gives skew. With one point per physical node, arc lengths are close to random. For N random points the largest arc is about (ln N)/N of the ring, so with N = 10 the busiest node owns about 2.3 times its fair share. Load is skewed before traffic even starts.

What virtual nodes change. Each physical node is placed at V points on the ring, for example 256. Its share is then a sum of V arcs, and the relative standard deviation falls roughly as 1/sqrt(V). For V = 256 that is about 6%, so the busiest node is typically within a few tens of percent of the mean instead of 2.3 times it. The cost is memory and lookup: 100 nodes at 256 points is 25,600 ring entries, found with a binary search in about 15 comparisons.

Setup (10 nodes)Max node share vs meanRing entries
1 point per nodeabout 2.3x10
256 points per nodeabout 1.1x2,560

Failure modes to name.

  • Removing a node moves only its keys, to its successor. That successor then carries double load until the node returns, so size for the worst single failure.
  • Heterogeneous hardware: give a larger machine more virtual points, proportional to capacity. Equal V with unequal boxes recreates the skew.
  • Virtual nodes fix arc skew, not hot keys. One popular track ID still lands on one node.
  • Replication: a key is usually stored on the next R distinct physical nodes clockwise, so skip virtual points that belong to a node already chosen.

Detection. Export keys and requests per physical node, and alert on max over mean. A ratio above about 1.3 for a sustained window points to too few virtual points or a hot key, and the two need different fixes.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-39After a customer places an order, the confirmation page reloads from a read replica and shows no order, and it appears only on refresh. Reads go to replicas by default. Design the fix so a session always sees its own writes, and say what it costs the primary and the replicas under load.

The 90-second answer

Read-your-writes is a per-session guarantee, not a global freshness target. Pinning every read to the primary for a fixed window after a write works, but it moves the whole post-write read load onto the primary. I would carry a write position instead. After the commit, the API returns the commit LSN to the client or stores it in the session. Each later read routed to a replica first checks that the replica has replayed at least that LSN. If it has not, the read goes to the primary.

Assumptions: PostgreSQL 16 streaming replication, asynchronous replicas, a stateless API tier with a session store, and reads that are mostly scoped to the caller's own data.

Trace (hypothetical figures)

TimeEvent
t=0 msPOST /orders commits on primary at LSN 0/5A3F1C0; response carries token
t=40 msGET /orders/42 routed to replica r2, which reports replay LSN 0/5A3E000. Behind the token, so the read goes to primary
t=180 msSame read, replica r2 now at 0/5A40000. Ahead of the token, so served from the replica

The check on the replica is a single comparison:

SQL
SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn;

If that returns false, route to primary. Do not sleep and retry on the replica unless the added latency is inside your budget.

Alternatives

ApproachPrimary loadGuaranteeFailure mode
Pin all reads to primary for 5 s after a writeHigh during write burstsTime-based; wrong whenever lag exceeds 5 sA lag spike returns stale reads silently
LSN token checkOnly the stale fractionExact for that sessionToken lost if the session store lags; fall back to primary
Synchronous commit to one replicaEvery write waits a round tripStrong for readers on that replicaWrite latency and availability tied to that replica

A time pin is acceptable only when your measured lag stays well under the window at p99. Otherwise it is a guess.

Failure modes and how you see them

  • Replay stalls behind a long query on the standby (conflicts under max_standby_streaming_delay). Every token check starts failing and traffic lands on the primary. Watch replay_lag in pg_stat_replication and alert on the fraction of reads that fall back.
  • Failover promotes a replica that is behind the token. LSNs are only comparable within one timeline, so after promotion the old token means nothing. Re-read from primary until a new token is issued.
  • Second devices have no token. A new device sees the replica state, which is correct under the guarantee you actually offered. Say this to product rather than promising cross-device consistency.

I would ship the token approach and keep the time pin as the fallback when the session store is unavailable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-40A key is replicated on N=5 nodes and you use W=3 for writes and R=3 for reads, so R + W > N. Explain why any read quorum must overlap any successful write quorum, and walk through which replica a read can use to find the new value.

The 90-second answer

With N=5, a write is acknowledged by a set of 3 replicas (the write quorum). A read contacts a set of 3 replicas (the read quorum). Two subsets of 5 elements, each of size 3, must share at least one member, because 3 + 3 = 6 > 5. Pigeonhole: the 3 read nodes can include at most 2 nodes outside the write set, so at least one read node is in the write set. That shared node holds the new version, so the read can see it.

The overlap is necessary but not sufficient. The read receives three versions and must pick the newest one. It does this by comparing a version number or timestamp attached to each value. If the write set and read set overlap, the newest version is present among the responses; the reader's job is to select it.

What the overlap does not give you: it says nothing about a write that was never acknowledged. A write that failed after reaching two replicas leaves those two holding a newer value. A later read that happens to include both of them and a third stale node will return the newer value, while another read that avoids them returns the old one. Callers should not treat a failed write as either applied or not applied.

Trace with real numbers

Nodes A to E, key balance, version 1 = 100 on all five. Client writes balance=70 as version 2.

StepEventABCDE
1write v2 sent to all five
2A, B, C acknowledgev2v2v2v1v1
3write quorum met, client gets successv2v2v2v1v1

Read with R=3 hits D, E and A: returns A's v2 because the highest version wins. Read hitting D, E and nothing from {A,B,C}? Impossible, since only two nodes lie outside the write set, so any read of three must include one of A, B, C. That is the pigeonhole argument in action.

Take-away: the overlap guarantees the newest acknowledged value is among the responses. Reading the newest version out of those responses is a separate step, and whether a reader sees a write that is still in flight is a separate question again.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-41Your consumer group has 12 partitions and 12 consumers, and one consumer restarts. Explain how partitions are reassigned during the rebalance and why the group stalls, then say whether a restarted consumer will reprocess records, and why.

The 90-second answer

With 12 partitions and 12 consumers, each consumer owns one partition. When one consumer goes away, the group coordinator starts a rebalance. Consumers stop fetching, give up their partitions, rejoin, and the group leader computes a new assignment. The 11 survivors end up holding 12 partitions between them, so one of them owns two. The stall is the rebalance itself, and it touches the whole group, not just the restarted instance.

Whether records get reprocessed depends on where the committed offset sits relative to the work that actually finished. A restart resumes from the committed offset, so anything processed after the last commit runs again.

Assignment and the stall

The eager protocol (RangeAssignor and RoundRobinAssignor, and the default assignor before Kafka 3.0) revokes every partition before reassigning any of them. CooperativeStickyAssignor revokes only the partitions that have to move.

Trace with 12 partitions, C7 crashes at t=0:

StepEagerCooperative sticky
Crash detectedt=0 + session.timeout.ms (default 45 s)same
Revokeall 11 live consumers drop their partitionsonly C7's partition is revoked
Assign12 partitions reassigned1 partition moves to a consumer that now holds 2
Processing gapall 12 partitions paused1 partition paused

Hypothetical figures: 45 s detection plus about 2 s to rejoin means the 11 healthy consumers stall for roughly 47 s under eager assignment. Cooperative assignment confines the gap to one partition, though the group still runs two rebalance rounds.

Detection is the slow part. A killed process is not noticed until session.timeout.ms expires. A clean shutdown that calls close() sends a leave request, and the rebalance starts immediately.

Will the restarted consumer reprocess?

Yes, if its last commit lags its last processed record. Compare two commit orders:

// commit after processing (at-least-once)
for record in poll():
    handle(record)
    commit_sync({tp: record.offset + 1})

// commit before processing (at-most-once)
for record in poll():
    commit_sync({tp: record.offset + 1})
    handle(record)

In the first version, a crash between handle and the commit replays that record on the next owner. In the second, a crash between the commit and handle loses it. Neither ordering prevents duplicates and losses at the same time. Only a sink that deduplicates lets you keep at-least-once without visible duplicates.

Rebalances add a second path to duplicates. If a consumer is revoked mid-batch, its uncommitted records go to the new owner. Committing synchronously in onPartitionsRevoked shrinks that window to the work still in flight.

The third path is the one teams miss. If handle runs longer than max.poll.interval.ms (default 300 s), the consumer is removed from the group even though its process is alive. That triggers another rebalance, and the batch it was holding gets replayed. The signal in the logs is consumer left group (or the equivalent client message) with no restart nearby, followed by duplicate-key errors downstream.

Failure modes to name

  • Rebalance storms: a consumer whose handle exceeds max.poll.interval.ms cycles in and out, and each cycle stalls the group. Detect with rebalances per minute.
  • Duplicate writes after a failed commit: the sink accepted the write but the offset commit failed. Detect with duplicate rates keyed on the event id.
  • Lag steps at each rebalance: detect with consumer lag per partition rising in a step at every rebalance.

For routine restarts, set group.instance.id (static membership). The coordinator keeps the partition reserved for that consumer for session.timeout.ms, so a quick restart does not trigger a rebalance and the partition does not move.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-42Kafka orders records within a partition, so if a consumer must see one order's events in order, what should the producer use as the record key?

The 60-second answer

Use the order id as the record key. Kafka guarantees order only within a single partition, and the producer picks the partition from the key, so every event that shares an order id goes to the same partition. The consumer reads that partition in offset order, so events for one order arrive in the order they were appended.

The guarantee is per key, not per topic. Events for order 42 and order 43 can land on different partitions and interleave in any order relative to each other, and the consumer has no way to recover a relationship between them.

KeyOrdering the consumer can rely on
order_idall events for one order, in append order
nullno per-entity ordering
random UUID per eventno ordering at all

Trace, with hypothetical offsets:

send(key=order_42, 'created')  -> partition 5, offset 118
send(key=order_43, 'created')  -> partition 9, offset 77
send(key=order_42, 'paid')     -> partition 5, offset 119

The consumer on partition 5 always sees created before paid. Partition 9 says nothing about the order of order 42's events.

Failure modes

  • Retries can reorder records. With enable.idempotence=false and more than one in-flight request per connection, a failed batch can be retried after a later batch has succeeded, so paid can land before created. The idempotent producer, the default since Kafka 3.0, preserves order across retries.
  • Changing the partition count remaps keys, because the partition is the hash of the key modulo N. Order 42 can move to a different partition mid-stream, and its older events stay behind. Plan partition counts up front or plan a migration.
  • Parallel processing inside one consumer breaks order even though Kafka delivered it in order. Handing records of one key to a thread pool, or committing offsets before processing finishes, can reorder or replay work for that key.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-43Your order-fulfilment consumer reads from a standard SQS queue, and handlers take anywhere from 5 to 90 seconds. How do you set the visibility timeout, what happens to a message whose handler outlasts it, and how do you make the consumer correct when the same message is delivered twice?

The 90-second answer

Standard SQS is at-least-once. A message can be delivered more than once, and two consumers can hold the same message at the same time. So the visibility timeout is not just a retry delay. It is the lease that decides when a second copy appears, and the consumer must be correct even when that lease expires while the first handler is still running.

I size the timeout from the handler's p99.9 duration plus margin, then extend it while work is in progress with ChangeMessageVisibility. I make the side effect idempotent on a business key with a conditional write, and I never treat the delete as proof that the work happened.

Sizing it. Default is 30 s, range 0 to 43,200 s (12 h). Here the p99 is 80 s, so 30 s guarantees duplicates. Hypothetical figures: 2% of 1 million messages a day exceed 30 s, so about 20,000 duplicate deliveries a day, each doing the fulfilment call again. Set the base timeout to roughly 1.5 times p99.9 (say 120 s) and heartbeat every 40 s:

Python
import threading, boto3
sqs = boto3.client("sqs")

def heartbeat(queue_url, handle, stop, every=40, extend_to=120):
    while not stop.wait(every):
        sqs.change_message_visibility(QueueUrl=queue_url,
            ReceiptHandle=handle, VisibilityTimeout=extend_to)

Batches are the trap. ReceiveMessage can return 10 messages. Each one's clock starts at receive, not when your loop reaches it. If you process them serially at 20 s each, the last one has about 200 s of work behind it, and a 120 s timeout expires before it starts. Either receive one message per worker, or extend every outstanding handle while the batch drains.

Trace. Worker A receives message m1 at t=0 with a 120 s timeout. Its handler stalls on a GC pause and the heartbeat misses. At t=120 m1 becomes visible. Worker B receives m1 with a new receipt handle, and its call to the fulfilment API succeeds. At t=130 A resumes, finishes, and calls DeleteMessage with its old handle. SQS accepts the delete for a stale handle only in the sense that it may do nothing useful, so the delete is not a reliable ownership check. The state store is.

Idempotent consumer. Key the work on the order id and an operation name, not the message id, because the producer may re-send with a new message id.

StepActionWhy
1INSERT ... (op_key, state='running', lease_until=now()+120s) ON CONFLICT DO NOTHINGclaim the work
2if conflict and state='done', delete message and returnduplicate of finished work
3if conflict and lease_until in future, return without deletinganother worker owns it; SQS redelivers later
4if lease expired, UPDATE ... WHERE lease_until < now() with a new owner tokentakeover with fencing
5call downstream with Idempotency-Key: op_keydownstream dedupes too
6UPDATE state='done' WHERE owner_token = $meonly the current owner may finish

The fencing token matters. Without the WHERE owner_token check, the paused worker A in the trace would mark done after B has already written.

Failure modes to name. A downstream call that succeeds but times out before the response leaves the row stuck in running until the lease expires; that is acceptable, and the downstream idempotency key makes the retry harmless. A handler that fails repeatedly should hit a redrive policy with maxReceiveCount (say 5) and go to a dead-letter queue; alarm on DLQ depth and on the ratio of duplicate-detected messages to total, since a rising ratio means the timeout is too short.

When not to use this. If the work needs strict ordering per order, use a FIFO queue with a message group id; FIFO deduplication uses a 5-minute window on MessageDeduplicationId, which covers producer retries but not consumer redelivery, so the consumer checks above still apply.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-44Your payment client retries on timeout with exponential backoff, and during an outage every client retries in lockstep. Explain why full jitter spreads the load better than adding a small random offset to a fixed backoff, then say how a retry budget stops the retries from multiplying across the call chain.

The 90-second answer

First I'd clarify the scale: how many clients, what the downstream capacity is, and whether the calls are idempotent. Retries are only safe on idempotent operations or with an idempotency key, so I'd assume the payment create carries one.

Pure exponential backoff, sleep = base * 2^attempt, makes every client that failed at the same moment wake up at the same moment. The outage ends, and the backend gets a synchronized spike at each backoff tick. A small offset (base * 2^attempt + rand(0, 50 ms)) keeps the clients in the same window, so the spike is only slightly smeared.

Full jitter draws the whole sleep uniformly: sleep = random(0, min(cap, base * 2^attempt)). The arrivals spread across the whole interval instead of clustering at its start. The AWS architecture write-up that popularised this compared it on simulated contention and found full jitter cut total client work and completion time substantially against the no-jitter and equal-jitter variants. Treat that as a directional result from one simulation, not a figure to quote.

Retries still multiply. If each of three tiers retries 3 times, one user action can produce 3 x 3 x 3 = 27 attempts at the bottom tier. A retry budget caps that: each client allows retries only while retries are a bounded fraction of recent requests, for example retries may not exceed 10% of successful traffic over a 60 s window, with a small floor so low-traffic clients can still retry. Above the budget, the call fails fast.

Trace (hypothetical figures)

Base 100 ms, cap 10 s, 1,000 clients fail at t=0.

AttemptFixed backoff arrivalsFull-jitter arrivals
1 retryall 1,000 at 100 msuniform over 0-100 ms, about 10 per ms
2 retryall 1,000 at 300 msuniform over 0-200 ms, about 5 per ms

Fixed backoff produces a 1,000-request spike. Full jitter produces roughly 10 requests per millisecond.

Trade-offs and failure modes

  • Full jitter gives the lowest average wait variance-free latency for a single client is worse than fixed backoff, since sleeps can be near zero. Accept that for the fleet-level win.
  • Detection: watch retry ratio, the count of retries divided by first attempts, and the arrival histogram at the server. A flat spike at one timestamp means jitter is missing.
  • Budget exhaustion shows up as a rise in fast-fail errors. Set the budget too tight and a transient blip becomes a user-visible failure.

Say when not to use retries: when the downstream is already overloaded and the error is a 429 or 503 with Retry-After, honour the header before any local backoff.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-45A hot cache key expires and 2,000 requests per second miss at once, all querying the database for the same row. Explain how request coalescing and a Redis SET NX lock differ in what they protect against, and which one you would ship first.

The 60-second answer

The stampede is many concurrent misses on one key recomputing the same value, so the database does N times the work it needs. Coalescing and a lock both collapse that work, but they operate at different scopes, and the scope decides which one fixes the problem.

Assumptions: 40 app instances behind a load balancer, a shared Redis cluster, and a query that takes about 150 ms against the primary.

Request coalescing (single-flight). Inside one process, the first miss registers an in-flight future under the cache key, and every other miss for that key waits on it. In Go this is singleflight.Group. It needs no network round trip and cannot fail in Redis. Its limit is scope: with 40 instances, each process still sends one query, so the database sees about 40 queries per expiry instead of 2,000. Failure mode: if the loader hangs, every waiter inherits the hang, so the loader needs a deadline shorter than the caller's.

Redis lock (SET NX PX). Across processes, the first miss runs SET lock:key <token> NX PX 5000. The winner queries, writes the value, and releases the lock with a compare-and-delete script that checks the token. Losers sleep with jitter and re-read the cache. Trace: instance A takes the lock at t=0, writes at t=150 ms. Instance B misses at t=40 ms, finds no lock, retries after 60 ms of jitter, and reads the fresh value at t=100 ms. Failure mode: if A dies before writing, waiters stall for the full 5 s TTL. Release with a plain DEL and you can delete another holder's lock after your own expired.

Which first. Ship coalescing first. It is cheap, local, and removes the within-process herd that usually dominates on a hot key. Then add the Redis lock if the database still sees one query per instance on every expiry and the query is expensive enough to matter. Measure it: database query count per expiry event and lock wait time, both of which should appear in your dashboards.

ApproachScopeQueries per expiry (40 instances)Main risk
Coalescingone processabout 40none in Redis, hung loader blocks waiters
Redis lockclusterabout 1holder dies, waiters stall up to 5 s

Jitter the TTLs too, so keys written together do not expire together.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-46Your order service writes to a cache in front of the database. Explain the difference between write-through and write-back caching, and say which one can lose acknowledged writes if the cache node crashes.

The 60-second answer

Both policies put a cache in front of a database and both acknowledge writes from the cache, but they differ in when the database sees the write. With write-through, the write goes to the cache and the database synchronously, and the client gets its acknowledgement only after the database commit succeeds. With write-back (write-behind), the write goes to the cache, the client is acknowledged immediately, and the cache flushes the dirty entry to the database later, in the background.

The durability consequence follows directly. Under write-through, an acknowledged write is already in the database, so a cache crash loses at most cache contents, which can be rebuilt. Under write-back, an acknowledged write exists only in the cache until the flush runs. If the node dies in that window, the write is gone even though the client was told it succeeded. That window is the durability loss window.

Trace with real figures (hypothetical)

The database commit takes 8 ms. The flush interval is 500 ms and the cache holds 2,000 dirty entries at a crash.

StepWrite-throughWrite-back
client write arrives at t=0cache set, DB commit startscache set, dirty bit set
client ackt=8 ms, after DB committ=0.2 ms
DB has the rowyes, at t=8 msnot yet, up to 500 ms later
cache node crashes at t=300 msnothing acked is lostup to 300 ms of acked writes are lost

Write-back's acknowledgement is roughly 40 times faster in this case, and the price is up to one flush interval of acknowledged data at risk per crash.

When each is acceptable

Write-through is the default for anything where an acknowledged write must survive a cache failure: orders, payments, inventory decrements, anything a customer was told succeeded. You pay the database latency on every write and you get no write amplification savings.

Write-back is acceptable when the loss window is either zero in effect or cheap to lose: counters or view counts where an approximate total is fine, derived data that can be recomputed from an event log, or telemetry. It is also acceptable when the cache is itself replicated with synchronous acknowledgement to a second node, which shrinks the window to the replication lag, though that adds its own cost and failure modes.

A write-back design is only defensible if you can name the bound: how often dirty entries flush, how many may be dirty at once, and what you do on restart (replay from a log, or accept loss and alert). If you cannot state that bound, use write-through.

Failure modes to name

If the flush fails repeatedly, dirty entries accumulate until the cache evicts them; without a rule for eviction of dirty entries, eviction silently drops writes. Detect this with a dirty-entry gauge and flush-error counter alarmed well below the cache capacity. Write-through has its own failure: a database slowdown now slows every client write, so the cache stops shielding the database from write latency. Detect it with p99 write latency measured at the cache layer, not only in the database.

Write-through does not remove the need for cache invalidation on other paths, and it is a common mistake to assume it does.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-47Your track-metadata service reads through Redis and updates Postgres on writes. Under concurrent readers, a stale title can stay cached for hours. Compare delete-then-write with write-then-delete, walk through the interleaving that breaks each one, and say what you would ship.

The 90-second answer

Neither order is safe alone. The race is between a reader that fills the cache after a miss and a writer that invalidates it. The reader's SELECT and its SET are two steps, and nothing ties the SET to the version the reader saw. Assumptions: Postgres is the source of truth at READ COMMITTED, the cache is cache-aside, catalog keys have a 24 h TTL, and the invalidating DEL can fail or be delayed.

Delete-then-write (invalidate, then update the row):

tWriterReaderRedis track:42
0DEL track:42(empty)
1GET misses(empty)
2SELECT title → Old(empty)
3UPDATE, COMMIT New(empty)
4SET track:42 OldOld

The cache holds Old until the TTL expires. The window covers the writer's whole transaction, so this order is worse.

Write-then-delete (commit, then DEL):

tWriterReaderRedis
0GET misses(empty)
1SELECT → Old(empty)
2COMMIT New(empty)
3DEL track:42(empty)
4SET OldOld

Still stale. The window is now the reader's gap between SELECT and SET. Hypothetical figures: a 2 ms gap is normal, but a GC pause or a stalled connection makes it 300 ms wide. The DEL already ran before the SET, so it cannot help.

Write-then-delete narrows the window and is the order I keep, but it does not close the race on its own.

Fix: a monotonic version counter that survives deletes

Do not rely on a version stored inside the value. A DEL removes that value, and then a stale fill has nothing to compare against. Keep the version in its own key, which DEL never touches:

  • Reader: GET track:42:ver (call it v) before the SELECT, then SELECT, then fill only if the counter still equals v.
  • Writer: COMMIT, then INCR track:42:ver, then DEL track:42.

The fill is an atomic Lua script:

local v = redis.call('GET', KEYS[2]) or '0'
if v ~= ARGV[1] then return 0 end
redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])
return 1

KEYS[1] is the value key, KEYS[2] the counter, ARGV[1] the version the reader captured, ARGV[2] the payload and ARGV[3] the TTL.

Trace: the reader captures v=5, reads Old, and stalls. The writer commits New, INCRs to 6 and DELs. The reader's script sees 6 ≠ 5 and returns 0. A reader that captured 6 after the INCR also started after the commit, so its SELECT returns New. Either way the stale value is never written.

Two constraints make this hold. The counter key must not expire, or a reset to 0 could match an old captured value. Its memory cost is one small key per cached entity. The INCR must run whenever the DEL runs, so put both in one MULTI or retry the pair together.

Lease tokens are the alternative, from the lease design in Facebook's memcache work. A miss hands out a token, a DEL voids outstanding tokens, and a SET with a voided token is rejected. It needs the same atomic check on the server side and is a little more machinery. Choose it if you already run a cache that supports it natively.

Delayed double delete (DEL, commit, DEL again after a delay) is common but relies on a delay longer than the worst reader gap, which is a guess, and it doubles invalidation load on hot keys. Avoid it as the primary fix.

Failure modes to monitor

  • A DEL is lost in a network blip. The TTL is the only backstop, so a 60 s TTL on mutable fields bounds the damage. A 24 h TTL is far too long for a title that can change.
  • A stampede after a hot key is invalidated. Use single-flight so 5,000 readers do not all query the primary at once.
  • Sampled read-back: compare Redis with Postgres for 0.1% of reads and alert on mismatches that persist past the TTL. This catches races the design missed.

What I ship: write-then-delete, the version-counter fill with the Lua check, a 60 s TTL on mutable metadata, and CDC-driven invalidation so the INCR and DEL are ordered and retried.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-48Your API allows 100 requests per second per API key with bursts up to 200. Compare a token bucket and a leaky bucket for enforcing that: which one gives you the burst allowance you want, what state you store per key, and what that state costs across 5 million active keys?

The 90-second answer

A token bucket fits this limit. It holds up to capacity = 200 tokens and refills at rate = 100 tokens per second. Each request removes one token, and a request with no token is rejected (429). A client that has been idle accumulates tokens up to 200, so it can send a burst of 200 at once, then falls back to 100 per second.

A leaky bucket is a queue drained at a fixed rate. Requests enter the queue and leave at 100 per second. Its output is smooth, which is useful for protecting a downstream that cannot take bursts, but it does not grant a burst allowance. If you want to let clients spike and still hold the average, you need the token bucket. If you want to flatten traffic before it hits a fragile dependency, you need the leaky bucket, usually with a bounded queue.

Per-key state

For a token bucket you store two values per key: the token count and the timestamp of the last refill. Refill is computed lazily on each request:

tokens = min(capacity, tokens + (now - last) * rate)
last = now
if tokens >= 1: tokens -= 1; allow
else: deny

That is two numbers, about 16 bytes as a pair of 64-bit values, plus the key and hash-table overhead. With 5 million active keys, the raw payload is about 80 MB, and with a typical Redis hash entry overhead of roughly 60 to 80 bytes per key, expect about 400 to 500 MB. A leaky bucket that queues requests stores the queue itself, which grows with the burst size and the number of waiting requests, so its per-key cost is larger and unbounded unless you cap the queue.

Trace

Key k has 200 tokens at t=0. Sending 201 requests at t=0: the first 200 are allowed and tokens fall to 0; request 201 is denied. At t=0.5 s, refill adds 50 tokens, so 50 more requests pass. The long-run rate stays at 100 per second, and the burst is capped at 200.

Failure modes

  • Clock skew across gateway nodes. If each node computes now locally, a key can get more or fewer tokens depending on which node serves it. Use a shared store with a single time source, or accept the error and size the limit with headroom.
  • Non-atomic read-modify-write. Two concurrent requests can both read 1 token and both spend it. Use a Lua script or an atomic operation in Redis.
  • Hot keys. One key sending at 10,000 requests per second still costs one bucket update per request, so the store load scales with traffic, not with the number of keys.

Detect these by comparing the admitted request count per key against the configured rate in a sampling job, and by alerting on 429 rate per key spike.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-49Your gateway allows 100 requests per rolling 60 seconds per API key. Compare a sliding window log with a sliding window counter: what does each store per key, and how large can the counter's error get?

The 90-second answer

A sliding window log keeps the timestamp of every accepted request for the key and counts those inside the last 60 s. It is exact. A sliding window counter keeps two integers, the count in the current fixed window and the count in the previous one, and estimates the rolling count as estimate = prev × (1 − f) + curr, where f is the fraction of the current window already elapsed. It is approximate, and the approximation assumes the previous window's requests were spread evenly across that window.

The log is the right choice when the limit is small, the traffic per key is low, and an exact answer matters for billing or abuse decisions. The counter is the right choice when keys are numerous and the limit is large.

Worked trace (hypothetical figures). Limit 100 per 60 s. The previous window saw prev = 90. Now is 15 s into the current window, so f = 0.25, and 30 requests have arrived, so curr = 30.

  • Counter estimate: 90 × 0.75 + 30 = 97.5, so one more request is allowed.
  • Exact count, log version: suppose the 90 earlier requests all landed in the last 15 s of the previous window. The rolling interval now covers t = 15 s to 75 s, so all 90 still count. Exact = 90 + 30 = 120. The counter under-counts by 22.5 and admits requests the limit forbids.
  • Opposite case: if those 90 landed in the first 15 s of the previous window, they have all slid out. Exact = 30, and the counter over-counts by 67.5, rejecting traffic the limit allows.

Bounding the error. The true previous-window contribution a lies between 0 and prev. The estimate uses prev × (1 − f), so the signed error is prev × (1 − f) − a, which is at most prev in magnitude. With prev ≤ limit, the counter's error is bounded by the limit itself. That is the number to quote: a worst-case error of up to 100 requests at a 100-request limit, and it shrinks only when the previous window was lightly used.

Sliding logSliding counter
State per keyup to limit timestamps2 integers plus window id
Memory at 1 M keys, limit 100, 8 B per timestampabout 800 MBabout 16 MB
Accuracyexacterror up to limit in theory
Write cost (Redis)ZREMRANGEBYSCORE + ZADD, O(log N)INCR on the window key

Failure modes to name.

  • Clock skew between gateway nodes. Timestamps from different hosts put the same request in different windows. Take time from one source, such as the Redis server clock, rather than from each gateway.
  • Non-atomic check-then-increment. Two gateways read curr = 99 and both admit. Do the read, the compare and the write in one Lua script.
  • Log growth on rejected traffic. Store only accepted requests, or the log fills with requests the client was already refused.
  • Idle keys. A counter key with a 2-window TTL must survive long enough to be read as prev, or the estimate silently drops to zero.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-50When an open circuit breaker's wait period ends, how many trial requests does it let through in the half-open state, and what decides whether it closes again?

The 60-second answer

A closed breaker lets calls through and counts outcomes in a sliding window. When the failure rate crosses a threshold, it opens and rejects calls locally, without touching the dependency. After the wait it moves to half-open and admits a fixed number of trial calls, N, set by configuration rather than by traffic. The decision is then made from those N calls: if the failure rate over them is below the threshold, the breaker closes; if it is at or above the threshold, the breaker reopens and the wait starts again.

Resilience4j 2.x defaults are a 50% failure-rate threshold, a 60 s open wait and 10 permitted calls in half-open (permittedNumberOfCallsInHalfOpenState). Check these against the version you run, because other libraries differ.

StateCallsLeaves when
Closedpass through, outcomes counted in a sliding windowfailure rate at or above threshold, then Open
Openrejected immediately, no dependency callwait elapsed, then Half-open
Half-openat most N probes admittedN calls complete: failure rate below threshold, then Closed; otherwise Open

A stricter policy is also common and is a design choice, not Resilience4j's default: reopen on any single failed probe. It suits a dependency that is only partly recovered, because one bad probe is enough evidence. The price is that one transient timeout can keep a healthy dependency out for another full wait. Name which policy you are describing when you answer.

Trace (N = 5, threshold 50%, wait = 30 s, hypothetical figures for a lyrics lookup)

t=0s    closed, window at 60% failures                 -> OPEN
t=0-30s 1,000 requests rejected in under 1 ms each     backend sees 0 calls
t=30s   half-open, probes 1-5 admitted
        results: ok, timeout after 2 s, ok, ok, ok
        failure rate 1/5 = 20%, below 50%             -> CLOSED

Under the strict any-failure policy the same trace reopens at probe 2 and the wait restarts at t=30s. Both outcomes are defensible; the candidate should say which one the system uses and why.

A probe counts as a success only if it returns without error inside the call timeout. Many setups also count calls slower than a slow-call threshold as failures, so a dependency that answers in 9 s is treated as down even though it returns 200.

Flapping

Flapping means the breaker keeps cycling Open, Half-open, Open. Causes:

  • A small N gives a noisy estimate. With N = 2, one lucky pair of successes against a dependency at 50% health closes the breaker, and the next burst of traffic reopens it.
  • A short wait means probes arrive while the dependency is still recovering, so each cycle hits it with a fresh probe burst.
  • Every reopen restarts the wait from scratch, so the breaker never gets a stable window in which to observe recovery.

Fixes, roughly in order of payoff:

  • Raise N to 5 to 10, so the failure-rate estimate has enough samples.
  • Back the wait off exponentially after consecutive reopens, with a cap.
  • Add jitter to the wait, so a fleet of instances does not probe at the same instant.
  • If you need the strict policy, accept the longer outage it causes after a single transient timeout.

Each fix has a cost. More probes means more load on a sick dependency in half-open, and with a slow dependency the breaker can take up to N times the call timeout before it decides. Longer waits lengthen the outage your users see after the dependency has recovered.

Other failure modes

  • Counting 4xx responses as failures opens the breaker on client mistakes. Count only timeouts, connection errors and 5xx responses.
  • Every instance has its own breaker, so each one judges the dependency from a small local sample. Breakers in different pods can disagree about state for a while, and no single instance sees the fleet-wide failure rate.
  • Rejected calls need a fallback or a clear error. Otherwise an open breaker turns a partial outage into a total one for the caller.

Detection

Alert on state transitions per minute per breaker (more than two or three per minute suggests flapping), on any breaker that stays Open longer than its wait plus one probe timeout, and on the rejected-call counter against total calls. Those three signals show whether the breaker is protecting the dependency or hiding a recovery.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-51Your checkout request carries a 2 s deadline from the client and fans out through three services, and each hop currently sets its own fixed 2 s timeout. Walk me through what goes wrong, and how you would propagate the remaining budget instead, including what each hop does with it.

The 60-second answer

A fixed timeout per hop is a guess about how long that hop should take, made without knowing how long the caller can still wait. Propagate the remaining budget with every call instead, and let each service derive its own timeout from what is left. The client's 2 s then governs the whole chain, and each hop reserves a slice of it for its own work.

Trace with a 2000 ms client deadline

Gateway receives the request at t=0 and spends 100 ms on auth. It calls Checkout at t=100 with 1900 ms remaining. Checkout spends 150 ms, so it arrives at Pricing at t=250 with 1750 ms remaining. Checkout keeps 50 ms to build its response and gives Pricing a 1700 ms timeout.

Pricing is slow. Under fixed timeouts, Pricing runs its own 2 s clock from t=250, so it cannot give up before t=2250. Gateway gives up at t=2000, but Pricing keeps working and Checkout keeps waiting. The chain consumes work for about 250 ms after the caller has left.

HopFixed timeoutRemaining budget
Gateway to Checkout2000 ms1900 ms
Checkout to Pricing2000 ms1700 ms
Pricing gives upt=2250t=1950
Checkout returns errort=2250+t=1950, 50 ms to spare

Mechanism

You can pass an absolute deadline or a remaining duration. Absolute timestamps need clocks synchronised within a margin you can tolerate, and a skewed host either times out early or runs long. Durations avoid that, because each hop converts them using its own monotonic clock. gRPC does this: the client writes grpc-timeout as the remaining time at send, using units such as m for milliseconds, and the server starts its deadline on arrival.

The duration form has a bias. Transit time is invisible to the receiver, so it sets a deadline one network hop too generous. Budget a margin for this, typically a few milliseconds inside a datacentre, and make it a measured number.

Failure modes and how you detect them

  • Budget already spent: remaining is zero or negative. Fail before sending. Count deadline_exceeded_before_send per service; a rising count means upstream is slow, not downstream.
  • Margin too small: the server finishes after the client cancels. Watch the gap between client-side cancellations and server-side success logs for the same request id.
  • Hidden timeouts: a client library default overrides the context deadline. Log the effective timeout on each outbound call once at startup and in a sampled trace.
  • Retries that restart the clock: a retry must draw from the remaining budget, not get a fresh timeout. Cap attempts so the last attempt still has a useful minimum.
  • Cancellation not propagated: setting the deadline without cancelling child calls on parent expiry leaves orphan work. In Go, pass the request context to every outbound call and check ctx.Err() before expensive steps.

When not to use it

Fire-and-forget work enqueued to a broker has no caller waiting, so a deadline on the enqueue says nothing about the job. Long-running jobs need their own progress checkpoints. Propagating a deadline does not make a slow dependency faster; it only ensures slowness fails at the budget the client set.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-52Your Postgres pool went from 20 to 60 connections per instance to fix p99 latency, and throughput fell while database CPU stayed under 40%. Using Little's law, what should the pool size have been, and why did more connections reduce throughput?

Assume one application instance talks to one primary with 8 vCPUs, and use hypothetical figures that match the symptoms: 1,200 requests/s at peak, each holding a connection for 12 ms when the database is not contended. Little's law, L = λW, gives the mean number of busy connections as 1,200 × 0.012 = 14.4. A pool of 20 therefore runs at 72% mean utilisation. That is close to the right size. At peak bursts the arrival rate is not flat, so a pool of 20 will queue occasionally and p99 will suffer, but tripling it to 60 does not fix that queue. It moves the queue inside the database.

The error is treating W as fixed. W is the time a backend spends on the query, including time spent waiting for locks, buffer pins, WAL and the scheduler. Once active backends pass roughly twice the core count, here about 16, each additional backend mostly waits and contends. Context switches rise, cache locality falls, and lock and LWLock waits lengthen. The query that took 12 ms now takes, say, 30 ms. Little's law then demands 1,200 × 0.030 = 36 busy connections to sustain the same arrival rate, and the pool fills with backends that are waiting rather than working. Throughput falls because useful work per backend falls faster than backend count rises. Database CPU can stay under 40% while this happens because the backends are not burning CPU. They are parked in wait events, and the fleet average also hides a single hot core or a contended lock.

Pool capMean busy backends (L)Hold time (W)What happens
2014.412 msOccasional pool queue at burst peaks, database mostly productive
6036.030 msBackends wait on locks and buffers, throughput drops, p99 rises
Pool cap raised to 60 More active backends Lock and buffer contention Hold time W rises Little's law demands more connections Pool fills with waiting backends New requests queue at pool

Size the pool from the database budget, not from the application tier. For this 8-core primary, cap total server connections across all instances near 16 to 24, then divide that budget by the number of instances. With 10 instances, that is about 2 server connections each, which is why a transaction-mode pooler such as PgBouncer sits in front of Postgres: hundreds of client connections multiplex onto a small server pool, and the cap is enforced in one place. If the fleet instead opens 10 × 60 = 600 direct connections, it also hits the default max_connections of 100 and fails at connect time before latency is even measured.

Check the diagnosis with pg_stat_activity while load is running:

SQL
-- PostgreSQL 15 and later
SELECT wait_event_type, wait_event, count(*) AS backends
FROM pg_stat_activity
WHERE state = 'active'
GROUP BY wait_event_type, wait_event
ORDER BY backends DESC;

If LWLock, Lock or IO dominate after the pool increase, and query duration in pg_stat_statements rose while the arrival rate stayed flat, contention is the cause. The fix is to lower the pool cap back toward the Little's law figure with headroom for bursts, set a short acquire timeout so overload fails fast instead of queuing without bound, and attack W itself with indexes or query rewrites. A larger pool only helps when W is stable and the database has spare concurrency to give.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-53A worker service's goroutine count climbs steadily for a day until memory runs out. A pprof dump shows thousands of goroutines parked on a channel send. How would you find the leak, and how does context cancellation fix it?

The 90-second answer

A goroutine leak here is a sender blocked forever on out <- ev. The receiver has returned, usually on an error path or after its own context ended, so nothing will ever receive. The Go runtime does not reclaim a parked goroutine, and its stack and everything it references stay alive. I find it from the goroutine profile, confirm the growth with a metric, and fix it by making every blocking channel operation also wait on ctx.Done(), with the context passed down from the request or the worker's owner.

Finding it

Fetch /debug/pprof/goroutine?debug=2 from a pod that has been up for hours and look for repeated stacks. A leak shows up as one stack repeated thousands of times, with state chan send and the same file and line:

4120 @ 0x43a1d6 0x4f7e2c
#   runtime.gopark
#   runtime.chansend
#   service/worker.(*Pool).produce+0x9c   worker/pool.go:88

Then confirm the slope. Export runtime.NumGoroutine() as a gauge and plot it against queue depth and request rate. A flat line under load with a rising baseline means a leak, not a traffic spike. In tests, goleak.VerifyNone(t) from go.uber.org/goleak fails the test if goroutines outlive it, which catches the pattern before it ships. Take two profiles ten minutes apart and diff them if the stacks are mixed.

The broken shape

Go
func produce(out chan<- Event) {
    for {
        ev, err := next()
        if err != nil { return }
        out <- ev // blocks forever once the consumer has gone
    }
}

If the consumer returns early on a timeout, out <- ev never completes. Every such call leaves one goroutine behind, along with the ev it holds.

The fix

Go
func produce(ctx context.Context, out chan<- Event) error {
    for {
        ev, err := next()
        if err != nil { return err }
        select {
        case out <- ev:
        case <-ctx.Done():
            return ctx.Err()
        }
    }
}

The rule is that every send and every receive in a goroutine has a path to exit. The receiver side needs the same treatment: for ev := range in only ends when the sender closes in, so a sender that dies without closing leaks the receiver. Close a channel only from the goroutine that owns sends on it.

Trade-offs

A buffered channel is not a fix. It moves the block to the moment the buffer fills, so the leak appears later and under load, which is harder to reproduce. Use the buffer for throughput and keep the ctx.Done() arm regardless. errgroup.WithContext gives you the cancellation wiring for a set of workers: the first error cancels the group context, and every select in the workers unblocks.

Failure modes to name

  • A select on ctx.Done() that is missing from one of several send sites. The leak still happens at the one site, so audit all of them.
  • A context that is never cancelled, such as context.Background() passed into a request-scoped worker. The Done arm is dead code.
  • Cancellation that is observed but the goroutine keeps running work after it. Check ctx.Err() between expensive steps, not only at the channel.

After the fix, the goroutine count should drop to a steady level that tracks in-flight work, and the chan send stack should disappear from the profile.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-54ReentrantLock.tryLock(timeout, unit) gives back a boolean instead of blocking forever. What does it return when the timeout expires, and why can't synchronized do the same?

The 60-second answer

When the timeout expires, tryLock(timeout, unit) returns false and the thread does not hold the lock, so the caller must not call unlock(). synchronized has no timed acquire: a thread that tries to enter a monitor blocks until it gets the monitor, with no deadline and no way to give up. That is why a service holding a reservation lock can answer a request with a 503 after 200 ms instead of stacking threads behind a stalled holder.

Checking the claim. The JDK 21 ReentrantLock javadoc defines the timed form as returning true if the lock was acquired and false if the waiting time elapsed before acquisition. The lock is not held on false, so the unlock() belongs inside the if, not in finally.

Java
ReentrantLock lock = new ReentrantLock(true); // fair
if (lock.tryLock(200, TimeUnit.MILLISECONDS)) {
    try {
        reserveStock(sku, qty);
    } finally {
        lock.unlock();
    }
} else {
    throw new ServiceUnavailableException("stock lock busy"); // 503
}

Three differences a candidate should name

FeaturesynchronizedReentrantLock
Timed acquirenotryLock(time, unit)
Interruptible while waitingnolockInterruptibly() and timed tryLock
Fairness optionno (monitor order unspecified)new ReentrantLock(true)
Releaseautomatic on block exitmanual, always in finally

A thread blocked on entry to a synchronized block ignores Thread.interrupt(). With lockInterruptibly() or timed tryLock, interrupt throws InterruptedException and the thread leaves the queue. That matters when a request is cancelled by a client disconnect.

Fairness costs throughput. The default ReentrantLock barges: a newly arriving thread can take a free lock ahead of queued threads. A fair lock hands it to the longest waiter, which bounds tail latency for every waiter but adds a context switch per handoff under contention. Use it when starvation shows up in your metrics, not by default. Note that the untimed tryLock() barges even on a fair lock, while the timed form respects fairness.

Failure modes to name

  • Forgetting the if check and calling unlock() after a failed tryLock, which throws IllegalMonitorStateException.
  • Holding the lock across a remote call. A 200 ms timeout does not help if the holder is waiting on a database for 5 s.
  • On Java 21 through 23, a virtual thread that enters a synchronized block pins its carrier thread. JEP 491 removes that pinning in JDK 24, so a ReentrantLock is the safer choice for virtual-thread services on those older releases.

Detection: a rising count of tryLock false returns on the reservation path, or thread dumps showing many threads in ReentrantLock.lock or Object.wait, points to a stalled holder rather than a slow lock.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-55Your order-scoring handler is pure Python, about 40 ms of CPU per request, running in a container limited to 2 CPUs on a 16-core host under Python 3.12. Threads stall at one core, and a 16-worker process pool breaks p99 under load. Walk me through the worker count you would choose, what os.cpu_count() reports here, and what you would ship.

The 90-second answer

The container gets 2 CPUs of quota, not 16. Threads cap the handler at one core because of the GIL, and a 16-worker process pool does not fix it either: the 16 workers share a 2-CPU CFS quota, so they get throttled in bursts and p99 spikes even though average CPU looks fine. I would ship 2 worker processes (or 3, if measurement shows the pipe I/O leaves cores idle), sized from the quota rather than the host core count, and I would change the pool so that a quota change cannot silently resize it.

What the numbers say

On 3.12, os.cpu_count() returns 16 because it reads the host, not the cgroup. Sizing a pool from it is the first mistake.

Capacity with 2 cores of quota and 40 ms per request:

2 cores / 0.040 s = 50 req/s at 100% CPU. At a 70% utilization target, that is about 35 req/s.

CFS enforces the quota per period. With cpu.max = 200000 100000, each 100 ms period grants 200 ms of CPU across all processes in the container. Sixteen busy workers consume that in 12.5 ms of wall time, then sit throttled for the remaining 87.5 ms of the period. A request that arrives during the throttle waits up to 87.5 ms before its CPU slice runs, which is a p99 hit with no visible change in average utilization.

Trace with 16 workers, hypothetical: 16 requests arrive at t=0, each needing 40 ms. Total CPU is 640 ms, so the quota releases 200 ms per period. The batch finishes around t=320 ms. With 2 workers, the same 16 requests finish in 16 x 40 / 2 = 320 ms, and nothing is throttled, so the first finishes at 40 ms and the median is far lower.

Interacting constraints

  • Pickling: the 2 MB input costs more to copy than the 40 ms of scoring if you ship the whole payload per call on a hot path. Pass a reference or a compact encoding.
  • Start method: on Linux, 3.12 still defaults to fork. Forking a process that already has threads running can copy locks in the held state. CPython 3.12 warns about this with a DeprecationWarning. Use multiprocessing.get_context('forkserver') and create the pool before the app starts threads.
  • Memory: each worker loads its own model. Two workers with 1.5 GB each is 3 GB inside a container whose memory limit might be 2 GB, which gets the process OOM-killed rather than slowed down.

What I would ship

Read the quota from /sys/fs/cgroup/cpu.max at startup, and size the pool from that. On 3.13 or later, os.process_cpu_count() respects affinity, but it still ignores the CFS quota, so the cgroup read is still needed. Alert on cpu.stat nr_throttled and throttled_usec; a rising count means the pool is too large.

How you would detect it

Record executor queue wait and compute time as separate histograms. Queue wait rising while compute stays flat means too few workers. Compute time rising with throttling counters climbing means too many.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-56Your service runs async handlers on one event loop, and a handler calls a synchronous library that takes about 300 ms per call. Walk me through what that does to the other requests in flight, and how you would find and fix it without rewriting the whole service.

The 90-second answer

An async runtime multiplexes many requests onto one thread. Each handler runs until it awaits, then yields so the loop can run something else. A synchronous call that takes 300 ms never yields. For those 300 ms the loop thread does nothing else: no other handler progresses, no timers fire, no socket is read or written. Requests that arrive in that window queue behind it, so their latency includes the blocked time whether or not they touch the slow path.

The fix I would ship is to move the blocking call off the loop: run it in a thread pool executor (loop.run_in_executor in Python, spawn_blocking in Rust, Task.Run on a bounded pool in .NET) and await the result. The loop stays free while a worker thread waits. The pool must be sized from the arrival rate, not guessed, because an undersized pool just moves the queue from the loop into the executor.

Mechanism, with numbers (hypothetical figures)

Assume 200 requests per second, 1 ms of real async work each, and one 300 ms synchronous call per request, all on a single loop.

  • Blocked on the loop: each request occupies the loop for 1 ms of async work plus 300 ms of blocking, so the loop needs 200 × 301 ms = 60.2 s of wall time per second. That is impossible, so the queue grows without bound and latency climbs until requests time out.
  • Smaller case: at 1 blocking call per second the loop is blocked 300 ms in every second, a 30% stall. Each request arriving during a call waits on average about 150 ms extra.

Now offload the call. The loop does 200 × 1 ms = 0.2 s of work per second, about 20% utilised. The executor's demand is 200 calls/s × 0.3 s = 60 thread-seconds per second, which is 60 threads busy on average just to keep pace. Any pool smaller than 60 falls behind: with 16 threads, the backlog grows by 44 thread-seconds every second, and latency degrades again, just inside the pool's queue instead of the loop. Size for at least 60, and add headroom (around 80) for variance. Sixty-plus blocked threads per instance is a warning sign in itself: it means the library call is the bottleneck, and the sizing is telling you to replace it.

Detection

  • Event loop lag: measure the gap between a scheduled timer and when it actually fires. Python's asyncio debug mode logs callbacks running longer than loop.slow_callback_duration (100 ms by default). Node's perf_hooks.monitorEventLoopDelay gives a histogram.
  • Profile with a sampling tool (py-spy, 0x, async-profiler) and look for the blocking frame sitting directly under the loop, not under an awaited coroutine.
  • Alert on p99 latency rising while CPU stays low. A blocked loop uses little CPU, and that combination is the signature.
  • For the executor, watch queue depth and the time a task waits before a thread picks it up. Rising wait time with a full pool means the sizing arithmetic above no longer holds.

Trade-offs and when not to use this

A thread pool only helps when the call is I/O-bound or the library releases the GIL or the equivalent. If it is CPU-bound pure Python, threads do not parallelise it and you need a process pool or a separate service. Sharing one pool across unrelated call sites lets a slow dependency starve the others, so give each dependency its own bounded pool with a timeout. Replacing the library with a native async client is better when one exists, because it removes the thread hop and the 60-thread sizing problem together.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-57A metrics counter is incremented from 64 goroutines and read by a reporter once a second. Compare an atomic increment with a mutex-guarded int, and say when a lock is still the right tool.

The 90-second answer

For one integer that only gets incremented and read, use an atomic. In Go 1.22, atomic.Int64.Add compiles to a single locked read-modify-write (LOCK XADD on x86), so no goroutine parks and the scheduler stays out of it. A mutex gives the same result but adds a lock and unlock to every call, and under contention it parks waiters and wakes them later. I reach for a lock only when the counter has to change together with something else.

Assumptions: Go 1.22, one process, 64 writers, one reader per second, no requirement that the count match another field at the same instant.

Go
type Counter struct{ n atomic.Int64 }

func (c *Counter) Inc()        { c.n.Add(1) }
func (c *Counter) Load() int64 { return c.n.Load() }

type LockedCounter struct {
	mu sync.Mutex
	n  int64
}

func (c *LockedCounter) Inc() { c.mu.Lock(); c.n++; c.mu.Unlock() }
func (c *LockedCounter) Load() int64 {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.n
}

Why the plain int breaks: two goroutines both load 5, both store 6, and one increment vanishes. Add makes the read, add and write one indivisible step, so the same two increments take the value 5 to 6 to 7.

Aspectatomic.Int64sync.Mutex + int64
Per-call work when uncontendedone locked instructionlock, increment, unlock
Under heavy contentioncache line ping-pongs between coreswaiters park, convoys form, wakeups add latency
Consistent read with writesLoadmust lock in Load too
Two fields updated as onenoyes

The timing gap is real but depends on the machine. Measure with go test -bench on your hardware before quoting numbers.

When a lock is still right

  • The counter and another value must agree. A count and a running sum that feed an average need a snapshot of both, and two atomics cannot give you that.
  • The update is check then act across more than one word: increment only while under quota and append to a log in the same step.
  • The state is a structure, such as a per-tenant map of counters, not one integer.
  • A max or min via compare-and-swap loops. It works, but under contention each failed CAS wastes a retry, and a mutex can be simpler to reason about.

Failure modes and how you catch them

  • Mixed access: a reporter reads the plain int without the lock. This is a data race, and go test -race reports it. Run the race detector in CI for any package that shares counters.
  • Hot cache line: all 64 writers hit one word. Shard into stripes, one per P or per goroutine group, each padded to 64 bytes so neighbours do not share a cache line, and sum the stripes on read. The reader now sees a slightly stale total, which is acceptable for a per-second report and wrong for a quota check.
  • Atomics are not a substitute for ordering: an atomic counter says nothing about the other memory a goroutine wrote before incrementing. Publish that data through a channel, mutex or atomic store with a release-acquire pairing, as the Go memory model requires.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-58In the Java Memory Model, what is the name of the ordering relation that guarantees one thread's write is visible to another thread's read, and what does a data race mean?

The relation is happens-before (JLS 17.4.5). If action A happens-before action B, then B sees A's effects and any write that A made before it. Two conflicting accesses to the same variable, at least one of them a write, that are not ordered by happens-before form a data race (JLS 17.4.1). A program with a data race has no guaranteed result, so a reader may see a stale value, or in a hot loop never see the update at all.

The answer is one step: happens-before orders the accesses, and a race is any conflicting pair of accesses it does not order.

Two things a candidate should say after the definition, because interviewers follow up on them:

  • The edges that create happens-before include a thread's program order, a monitor unlock followed by a lock on the same monitor, a volatile write followed by a volatile read of the same variable, and Thread.start() and join(). Happens-before is transitive, so a chain of these edges orders far-apart actions.
  • x86 does not change this. TSO limits how the CPU orders stores and loads, but the JIT compiler is free to hoist a plain read out of a loop. A missing edge in Java code is a bug on every architecture.

Fix: make the flag volatile, or guard both sides with the same monitor. Detect it with a jcstress test, because stress load often hides it.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-59Your HTTP service gets SIGTERM during a rolling deploy with 300 requests in flight, some of them long uploads. Walk me through the shutdown sequence: when you stop accepting connections, how you drain, and how you split a fixed timeout budget across the steps so the orchestrator's SIGKILL never lands mid-request.

The 60-second answer

I'd treat shutdown as three phases with a hard deadline that comes from the orchestrator, not from me. On SIGTERM the process first flips readiness to failing, so the load balancer stops sending new traffic. It keeps serving the requests it already has. After a short propagation window it calls Shutdown on the listener, which closes the listening socket and stops accepting. Then it waits for in-flight handlers to finish, and only after the drain deadline does it cancel their contexts and close connections.

The budget is the part that decides whether this works. Kubernetes sends SIGKILL after terminationGracePeriodSeconds, which defaults to 30 s and counts from SIGTERM. Everything I do has to finish inside that number with margin.

Budget (hypothetical figures, 30 s grace period)

StepDurationCumulativeWhy
SIGTERM, readiness goes false0 s0 sLB stops routing new requests
Propagation wait5 s5 sendpoint removal reaches LB and kube-proxy
Stop listener, drain in-flightup to 20 s25 sshort requests finish; long uploads get cancelled
Cancel contexts, force close2 s27 shandlers see ctx.Done(), sockets close
Flush logs, metrics, exit1 s28 s2 s spare before SIGKILL

The propagation wait is not optional. If I close the listener immediately, requests the LB still routes to me get connection refused, and those are retried or counted as errors.

What happens to the 300 requests

Most of them are short and finish in the drain window. Long uploads are the problem. A 40 s upload cannot finish in a 20 s drain, so I have two options. I can cancel it at the drain deadline and return 503 with Connection: close if the response has not started, or I can design uploads to be resumable so the client picks up at an offset. I would not extend the grace period to 120 s to accommodate one endpoint. That delays every rollout and hides a design problem.

Trace for one upload handler:

Go
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
go srv.ListenAndServe()
<-sigterm
ready.Store(false)
time.Sleep(5 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil { // waits for active conns to go idle
    srv.Close() // force-closes; handlers see request ctx cancelled
}

Shutdown closes listeners and waits for connections to become idle. It does not cancel request contexts. That's why the upload handler also needs to watch r.Context().Done(), or Close must be called after the drain deadline. Many services assume Shutdown cancels handlers. It doesn't.

Failure modes to check

  • Keep-alive connections that never go idle. A client holding a keep-alive socket can keep Shutdown waiting until the context expires. Setting IdleTimeout and sending Connection: close on responses during drain helps.
  • Background goroutines not tied to the server. A worker writing to a queue after Shutdown returns loses work. Those need their own drain step.
  • Timeouts that don't sum. If each hop has a 20 s write timeout and the budget is 20 s, the drain never gets to run its full length.
  • Detection: count shutdown_forced_closes_total and requests_cancelled_on_shutdown per deploy. A nonzero count on every rollout means the drain window is too short for real traffic.

Alternatives

A connection-draining feature in the LB (for example, deregistration delay on a target group) does part of this for you, but it does not cancel your handlers or tell you what was cut off. Use it, and still implement the in-process sequence.

If the service is a stateless short-request API, a 10 s grace period with a 3 s drain is often enough. Long-lived streams or uploads are where the budget arithmetic above matters.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-60Your readiness probe runs SELECT 1 against the primary database and the liveness probe runs the same check. During a failover every pod's probe starts failing together and Kubernetes keeps restarting them. Explain the restart loop, then say what each probe should check and which one you would change first.

The 90-second answer

The loop comes from the liveness probe. When liveness fails failureThreshold times in a row, kubelet kills the container and starts a new one. A database failover makes the check fail on every pod at once, so the whole fleet restarts together, and each fresh pod immediately fails again against a primary that is still electing. Liveness should be a local check that only restarts a process that is wedged. A database check belongs in readiness, which removes a pod from Service endpoints without killing it. I would move the SELECT 1 out of liveness first, because that change stops the restarts. Readiness can keep the check, as long as it runs against cached health state and not a fresh query on every probe.

The mechanism with real numbers

Defaults are periodSeconds 10 and failureThreshold 3. A failover that takes 45 s to elect a new primary produces about 4 to 5 consecutive failed liveness probes, so each pod is killed around 30 s into the outage. The replacement pod starts, opens its pool of 20 connections, and gets killed again on its next failed probe. With 200 pods, that is 200 restarts per cycle plus a burst of up to 4,000 new connections against the database during its worst moment.

Liveness versus readiness

ProbeChecksFailure actionMust not check
livenessevent loop responds, worker pool not deadlocked, heap under a hard ceilingrestart containerany downstream dependency
readinessdependencies needed for this pod to serve any requestremove from endpoints, no restartanything a restart would fix

A restart cannot repair a database failover, so the database check must not control restarts. Readiness failures only remove the pod from endpoints, so a readiness check that depends on the database is safe to keep, provided that it does not empty the whole Service when the database is briefly unavailable.

The change I would ship

  1. Remove the database check from liveness. Serve liveness from a separate port and return 200 if the main loop ticked in the last few seconds.
  2. Keep the database check in readiness, but read a health state that a background goroutine refreshes every 5 s. Use hysteresis: mark not-ready after 3 consecutive failures and ready again after 2 successes, so a brief blip does not flap every pod.
  3. For read endpoints, consider serving from a replica or cache while the primary is down, and return 503 with Retry-After only for writes.

Failure modes to watch

  • Synchronized restarts: a rise in kube_pod_container_status_restarts_total across the whole deployment at once points at a probe, not the application.
  • Zero ready endpoints: kube_endpoint_address_available drops to 0 while pod CPU stays idle.
  • Probe load: if readiness opens a new connection on every probe, 200 pods at a 10 s period add 20 connections per second before any user traffic.

A probe should fail only for a condition its action can fix. Restarting a pod cannot fix a database failover.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-61Your orders table has 400 million rows. Why does adding a NOT NULL column with a constant default no longer rewrite the table on PostgreSQL 16, and what would still force a full rewrite?

The 90-second answer

Since PostgreSQL 11, ALTER TABLE ... ADD COLUMN c type NOT NULL DEFAULT <expr> does not rewrite the table when <expr> is non-volatile. PostgreSQL evaluates the default once, at ADD COLUMN time, and stores it in pg_attribute.attmissingval. Existing rows have no physical value for the column, so reads fill in attmissingval. Only the catalog changes, and the statement takes ACCESS EXCLUSIVE briefly. Its run time does not depend on the 400M row count, but the lock is still the risk, so set lock_timeout before running it.

The rule that matters is volatility. A constant or a stable function such as now() is evaluated once, so the stored value is correct for every existing row. A volatile function such as clock_timestamp(), random() or nextval() must produce a different value per row. That cannot be expressed as one stored value, so PostgreSQL rewrites the table and computes the default for each row. Column defaults cannot reference other columns in PostgreSQL, so a per-row value that depends on other columns is not something you add as a default. You add the column, backfill with an UPDATE, and then tighten the constraint.

Other changes that rewrite the table include ALTER COLUMN ... TYPE to a type that is not binary-compatible, such as int to bigint. Increasing a varchar length, or dropping the length limit, is binary-compatible and does not rewrite. Going from text to varchar(200) also does not rewrite, but PostgreSQL scans the whole table under ACCESS EXCLUSIVE to verify the length, so the lock lasts as long as that scan.

Check it on a copy

The relfilenode changes only when the table is rewritten:

SQL
SELECT relfilenode FROM pg_class WHERE oid = 'orders'::regclass;
ALTER TABLE orders ADD COLUMN settlement_currency text NOT NULL DEFAULT 'USD';
SELECT relfilenode FROM pg_class WHERE oid = 'orders'::regclass;

For the constant default, the two values match. Swap in DEFAULT clock_timestamp() and they differ. Hypothetical figure: on a 400M-row table, a rewrite that takes 40 minutes under ACCESS EXCLUSIVE will block every query on orders for that time unless lock_timeout aborts it first.

Comparison on PG 16

ChangeRewrite?Lock and cost
ADD COLUMN c int NOT NULL DEFAULT 0noACCESS EXCLUSIVE, brief
ADD COLUMN c timestamptz DEFAULT now()noACCESS EXCLUSIVE, brief
ADD COLUMN c timestamptz DEFAULT clock_timestamp()yesACCESS EXCLUSIVE for the full rewrite
ALTER COLUMN c TYPE bigintyesACCESS EXCLUSIVE for the full rewrite
ALTER COLUMN c TYPE varchar(200) from textnoACCESS EXCLUSIVE for a full validation scan

Failure modes

  • The queue stalls writes, not the rewrite. An ACCESS EXCLUSIVE request waits behind a long-running reader, and every new query on orders then waits behind it. Look for it in pg_stat_activity and set lock_timeout.
  • Assuming a per-row value is cheap. A volatile default or a value derived from other columns needs a backfill, not a default.
  • Assuming the default covers application inserts. An insert that omits the column gets the default. An insert that sends an explicit NULL fails the NOT NULL constraint. Test that path.

For a value derived from each row, add the column nullable, backfill in batches, then add the constraint as NOT VALID and validate it separately.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-62In an expand and contract migration, what is the first step: adding the new column, or dropping the old one?

Add the new column first. Dropping the old one is last, after every running version has stopped using it.

That order assumes a rolling deploy with zero downtime, which is the case expand and contract is designed for. During the rollout, old pods and new pods serve traffic against the same database at the same time. Every intermediate schema has to satisfy both binaries. If you drop cust_ref while an old pod is still in rotation, that pod fails on every query that names the column, with SQL state 42703 and a spike in 500s. Adding customer_id first breaks nothing, because old code simply ignores a column it does not know about.

For renaming orders.cust_ref to orders.customer_id, the sequence is:

StepActionWhy it is safe
1. ExpandAdd customer_id as nullableOld pods insert rows without setting it
2. Dual writeNew code writes both columnsEither column can be read during the transition
3. BackfillFill customer_id from cust_ref in batchesExisting rows catch up without a long lock
4. Switch readsNew code reads customer_idReads move only after the backfill is verified
5. Stop old writesNew code stops writing cust_refThe old column stops changing
6. ContractDrop cust_refNo deployed binary references it any more

Nullable matters in step 1. A NOT NULL column with no default would reject inserts from old pods that do not set the column. You can add a default or a NOT NULL constraint later, once old code is gone, if you want the constraint enforced.

Dual writing is the part interviewers usually probe, because it introduces its own failure mode. If the two writes are not in the same transaction, a crash between them leaves the columns disagreeing. Write both in one transaction in the new code:

SQL
BEGIN;
UPDATE orders SET cust_ref = $1, customer_id = $1 WHERE id = $2;
COMMIT;

Make the backfill idempotent and run it in batches keyed by primary key, for example 1,000 rows at a time, until it updates zero rows. As a hypothetical sizing example, 10 million rows at 1,000 per batch is 10,000 batches, which is why you run it as a background job with a pause between batches rather than as one giant update. Batching keeps each statement short, so it does not hold locks long enough to block checkout traffic.

Verify the backfill before switching reads. The count of rows where customer_id IS DISTINCT FROM cust_ref has to reach zero and stay there while dual writes are running. If it does not, you have a bug in the dual write path, a trigger or job still writing only the old column, or a batch that failed halfway. Switching reads before that count is zero just moves the inconsistency to the read path.

Before step 6, check that nothing still references the old column. Application code is the obvious place, but scheduled jobs, loaders, and reporting queries count too. Check pg_stat_statements for cust_ref, group by application_name, and search the codebase and job definitions. If a nightly job still reads cust_ref, dropping it breaks that job even though the web tier is clean.

The judgement call is timing, not order. Expand is cheap and reversible. Contract is the step you delay until you have evidence, from logs and query stats, that the old column is dead. That evidence is what makes the migration safe, and it is the part worth saying out loud in an interview.

Self-assessment

Key points to hit: add before drop, both binaries share one schema during a rolling deploy, dual write in one transaction, batched idempotent backfill, verify zero mismatches before switching reads, and prove the old column is unused before contracting.

Weak answer pattern: "add the new column, migrate the data, drop the old one" with no mention of old pods still running, dual writes, or evidence before the drop. That describes a stop-the-world migration, not expand and contract.

Likely follow-ups: How do you handle a column type change rather than a rename? What if the backfill cannot finish before the deploy window closes? How do you roll back after reads have switched?

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-63A field quantity = 4 was deleted from your order-line message last year, and a teammate now wants number 4 for a new delta field. Walk me through what a mixed-version fleet actually does with the bytes, and what you would enforce so this cannot happen.

The 60-second answer

A protobuf field number is the field's identity on the wire. Names are not transmitted, so renaming a field is free and renumbering one is a break. A decoder only sees a tag, which is (field_number << 3) | wire_type, plus the payload. It has no way to know that number 4 used to mean something else, so the old bytes get interpreted under the new meaning with no error.

Trace of the silent case. Assume the old writer had int32 quantity = 4; and the new reader has sint32 delta = 4;. The old writer encodes quantity = 3 as tag (4 << 3) | 0 = 0x20 followed by varint 0x03, so the bytes are 20 03. The new reader uses the same wire type, varint, so it accepts the value and applies zigzag decoding: (3 >> 1) ^ -(3 & 1) = 1 ^ -1 = -2. The service now believes the delta is -2. Nothing fails validation, nothing logs, and the bad value is stored.

The loud case is the less dangerous one. If the old field was string sku = 4; (wire type 2, length-delimited) and the new one is int32 qty = 4; (wire type 0), mainstream generated parsers usually treat the mismatched field as unknown rather than decoding it. The value silently disappears into unknown-field storage. Both outcomes are bad, and neither is caught by a unit test that only round-trips new messages.

Why old writers still matter. Deleted fields keep arriving from clients, batch jobs and replayed queues for as long as those producers exist. A reader that reuses the number is reading live data written under the old contract. Proto3 keeps unknown fields on re-serialization in current libraries, which means a service that re-emits a message can also re-emit the stale field under its new meaning.

What to enforce. Delete the field and reserve both its number and its name:

reserved 4; reserved "quantity";

A reserved number cannot be reused by protoc, which is the only check that runs on every build. Run buf breaking against the last released schema in CI, so that deletions without reservations and type changes such as int32 to sint32 fail the pull request. If you run a schema registry, use a compatibility mode that checks the full history (BACKWARD_TRANSITIVE is the usual choice), so an old schema version cannot be re-registered with a reused number.

What reservations do not cover. A reserved number stops new code from reusing it. It does not stop an old service that still ships an old .proto from writing it, so detection still matters. Canary the new reader against production traffic and compare decoded value distributions for the field before and after rollout. A sudden shift in the sign or magnitude of a field is the signature of a reused number.

Trade-off. Permanent numbers mean the schema accumulates dead slots. That costs nothing on the wire, so keep the reservations and accept the clutter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-64Your endpoint returns 200 before and after a deploy, but a client that worked yesterday now fails. Name the kind of change that most likely did it, and explain why the status code gave no signal.

The 90-second answer

The likely cause is a change to the body that the client reads, not to the status. A 200 means the server finished the request. It says nothing about whether the client could parse the body and pick the right branch, so a breaking change can ship behind a green status.

The usual culprits are a removed or renamed field, a type or unit change, or a new enum value that reaches an exhaustive switch in a generated SDK. Adding an optional field is safe for tolerant readers but breaks clients that deserialize into a closed schema.

Trace

Before: GET /tracks/t_91 returns 200 {"id":"t_91","duration":212}

After the team renames duration to duration_ms and stores milliseconds: 200 {"id":"t_91","duration_ms":212000}

The client reads duration, gets nothing, treats it as 0 and skips the track. Both responses were 200, so no status-based alert fires.

ChangeBreaks existing clients?Why
Add optional fieldUsually notTolerant readers ignore unknown keys
Remove or rename fieldYesRead path gets null or fails
Change type or unitYesParsing or arithmetic goes wrong, often silently
Add enum valueYes, for exhaustive matchesNew value reaches an unhandled branch

How to catch it before shipping

An OpenAPI diff in CI (oasdiff classifies changes as breaking or not) catches removals and type changes. It cannot see a unit change or a new enum value a client does not handle, so replay recorded responses from top callers against consumer-driven contract tests as well.

If the change is breaking, ship it beside the old field, mark the old one with a Deprecation header (RFC 9745) and a Sunset date (RFC 8594), and remove it only after logs show zero reads from active callers.

Trade-off

For third-party clients you cannot reach, running both representations is the only safe option. The cost is carrying two shapes for the deprecation window, and that cost should be tracked rather than hidden behind a version bump.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-65Your consumer must not apply the same message twice. Explain how a processed-messages table with a unique key prevents a duplicate write, and where its transaction boundary must sit.

The 90-second answer

Keep a processed_messages table with a primary key on (consumer, message_id). In one database transaction, insert the row and apply the business change. If the insert hits a conflict, the message was already applied: commit nothing new and acknowledge. The transaction boundary has to enclose both writes, because the dedupe row is only a truthful record if it commits atomically with the change it guards. Acknowledge the message after commit, not before.

SQL
BEGIN;
INSERT INTO processed_messages (consumer, message_id, processed_at)
VALUES ('fulfilment', $1, now())
ON CONFLICT DO NOTHING;
-- application reads rowcount; 0 means duplicate, so COMMIT and ack
UPDATE orders SET status = 'fulfilled'
WHERE id = $2 AND status = 'paid';
COMMIT;

Trace for one order when the first ack is lost:

StepEventprocessed_messagesorders.status
1deliver m-981insert, rowcount 1paid to fulfilled, commit, ack
2ack lost, redeliver m-981insert conflicts, rowcount 0untouched, ack

Why the unique key and not a SELECT then INSERT: two deliveries can run at once. Under READ COMMITTED, the second insert blocks on the first's uncommitted index entry and fails once the first commits. A check-then-insert lets both through.

Why ack after commit: if you ack first and the process dies before commit, the message is gone and the change is lost. If you commit first and die before ack, the message redelivers and the table skips it.

Alternatives. Making the business update itself idempotent (for example WHERE status = 'paid') needs no extra table, but it only works when the change is a state transition. A dedupe table covers arbitrary handlers at the cost of a write per message and a purge policy.

What it does not cover: side effects outside the database, such as a payment call made before commit, repeat on redelivery. Pass the message id as the provider's idempotency key, or move the call behind an outbox. Also, purged ids can no longer be recognised, so purge only beyond the longest redelivery horizon. SQS retention defaults to 4 days and can be set to 14.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-66In a saga, what is a compensating transaction?

The 90-second answer

A compensating transaction is a forward local transaction that semantically undoes the business effect of an earlier saga step that has already committed. Each forward step Ti has a compensation Ci. When step k fails, the orchestrator runs Ck-1 down to C1, in reverse order.

It is a new write, not an undo. The earlier step's commit is already durable and may already be visible to other readers, so the database cannot erase it. The compensation appends a reversing record instead. Because it is a forward action, it can itself fail, so it must be retried and must be idempotent.

RollbackCompensation
When it appliesbefore commitafter commit
Effect on historyerased, never visiblestays, plus a reversing record
Can it failengine guarantees atomicityyes, must be retried until it succeeds
Examplediscard an uncommitted debitinsert a refund row for a committed charge

Trace (hypothetical figures)

Checkout for a 4,500-cent order runs three steps:

  1. T1 reserves inventory. Commits.
  2. T2 charges the card 4,500 cents. Commits.
  3. T3 creates the shipment. Fails after the carrier rejects the label.

The orchestrator runs C2 with refund(payment_id, idempotency_key='saga-7f3c-C2'), which writes a refund row for 4,500 cents. Then it runs C1, which releases the reservation. The statement shows the charge and the refund. Nothing was deleted.

Failure modes and how you detect them

  • The compensation fails. Retry it with backoff and a stable idempotency key, and persist saga state so a restarted orchestrator resumes. Alert on any saga stuck in COMPENSATING for more than 15 minutes.
  • A step has no safe inverse, such as an email already sent. Place such steps after the pivot transaction, so nothing irreversible runs before the last likely failure.
  • Intermediate state is visible between T2 and C2. Use a semantic status such as PENDING_PAYMENT that readers respect.

An interviewer may ask what the saga guarantees: eventual consistency of the business outcome, with visible intermediate states. It does not give isolation.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-67Your coordinator logged COMMIT for transaction 9001 and sent it to shard A, then its local disk failed before shard B heard anything. Shard B's prepare record survived. Walk me through what each shard and the restarted coordinator do, and where atomicity breaks.

The decision log protects atomicity only if it is durable before any participant hears the decision, and only if it survives the failure you are designing for. A log on one local disk does not survive a disk failure. Once the coordinator has announced commit to one shard and then loses the record of that decision, the restarted coordinator has no record of transaction 9001 to act on. Shard B stays in-doubt, prepared and holding its locks, until an operator resolves it manually. Shard A is already committed. Atomicity is preserved only if that manual resolution commits B as well. Rolling B back would leave the transfer half applied.

Assumptions: two PostgreSQL shards, one coordinator with a local write-ahead log, presumed-abort 2PC using PREPARE TRANSACTION and COMMIT PREPARED. The coordinator writes its decision with fsync before sending COMMIT, which is the usual rule.

Trace, transaction 9001:

StepCoordinatorShard AShard B
1PREPARE sentprepare record fsynced, votes yesprepare record fsynced, votes yes
2fsync DECISION=commit 9001
3sends COMMIT to ACOMMIT PREPARED, A is committedstill prepared, rows locked
4disk fails before sending to Bstill prepared
5restarts with empty log, no record of 9001
6sends nothing for 9001still prepared, in-doubt

Presumed abort does not rescue this case. Presumed abort means a recovering coordinator treats a transaction with no decision record as aborted, and participants can be told to roll back. That works when the coordinator still knows the transaction existed and can issue the rollback. Here the disk failure took the decision record and the coordinator's knowledge of 9001 with it. An empty log is indistinguishable from "9001 never existed." The coordinator therefore sends no ROLLBACK to B, and B has no instruction to act on.

Shard B cannot decide alone at step 4, because it voted yes and must keep its locks until told. It was right to wait. The fault is the coordinator's. The restart at step 5 leaves B in-doubt indefinitely. Its prepared rows stay locked, its xmin stays pinned so VACUUM cannot clean past it, and the ledger shows a debit on A with no matching credit on B.

Recovery is manual. An operator checks both shards for the global transaction id:

SQL
-- On each shard, checked against PostgreSQL 16
SELECT gid, prepared, owner, database
FROM pg_prepared_xacts
WHERE gid = '9001';

A returns no row because it already committed. B returns one row. The only resolution consistent with A's outcome is to commit B:

SQL
COMMIT PREPARED '9001';

If the operator instead runs ROLLBACK PREPARED '9001' on B, atomicity breaks at that moment. A keeps the debit, B discards the credit, and the transfer is half applied with no automatic way to detect the mismatch except reconciling ledger rows by global transaction id.

The fix is a decision log that survives the coordinator's own failure. Options, with costs:

  1. Replicate the decision log to a quorum of coordinator replicas before sending COMMIT. This costs one extra network round trip on the commit path, usually a few milliseconds inside one region. Raft or Paxos groups do this in Spanner and CockroachDB.
  2. Write the decision to a shared durable store, such as a replicated database, before any COMMIT leaves the coordinator. This is simpler to operate, but the store becomes a dependency of every commit.
  3. Keep the local log and accept a window in which a coordinator disk loss needs manual repair. This is acceptable only if you can detect it. Alert when a prepared transaction is older than your threshold, for example 60 s, in pg_prepared_xacts, and reconcile both shards' ledger rows by global transaction id.

Operational checks. max_prepared_transactions defaults to 0, so PREPARE TRANSACTION fails until you raise it. A prepared transaction holds its xmin, so VACUUM cannot clean past it, and stale ones cause bloat.

When not to use 2PC here. If the coordinator's log cannot be made durable across machines, or the participants sit behind unreliable links, use a saga with an outbox instead. Compensation avoids holding locks across the network, at the price of a window where the transfer is visibly half done.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-68Your invoice workers take a Redis lock with a 30 s lease so that only one worker processes a given invoice. A worker can pause for longer than its lease. Why is a fencing token required, and how does the storage layer use it?

Short answer

A lease tells the holder it has a time window. It does not stop anyone else from acting. A client can pause (GC, VM stall, page fault, long partition) for longer than the lease, wake up still believing it holds the lock, and write. The lock service has already granted the lock to someone else. A fencing token fixes this: the lock service issues a number that strictly increases on every grant, and the protected resource rejects any write carrying a token lower than one it has already accepted.

Trace, lease TTL 30 s

t (s)Worker AWorker BLock serviceStorage max token
0acquiresgrants token 33, expires at 300
1writes with token 3333
2GC pause starts (40 s)33
30lease expires33
31acquiresgrants token 3433
33writes with token 3434
42wakes, still thinks it holds the lock, writes with 33rejects 33, since 34 was seen

Without the check at t=42, A overwrites B's work. No lock protocol prevents this, because A never learns it was paused. The lock service cannot see the pause, so the only place the stale write can be caught is the resource itself.

Where the check lives

Storage must make the check and the write one atomic step. For SQL: UPDATE invoices SET state = $2, fence = $1 WHERE id = $3 AND fence < $1. Zero rows affected means the writer is stale, so abort and drop the work. A check in the worker before the write does not help, because the pause can land between the check and the write.

Where it gets harder

  • Redis SET key val NX PX 30000 gives expiry but no token. A counter via INCR can supply one, but only if the resource compares it. Kleppmann's 2016 critique of Redlock makes the same point about timing assumptions. Antirez disagreed on the clock model. Tokens remove safety from timing; leases still matter for liveness.
  • Token source must be monotonic across failover of the lock service. A replica-local counter can roll back. Use a consensus-backed sequence such as an etcd revision or a ZooKeeper zxid.
  • If the protected action is an external API that ignores tokens, fencing is impossible. Use that system's idempotency key or conditional write. The lock then only reduces contention.

Trade-offs

Lease length sets how long a crashed holder blocks others against how often a healthy but slow holder loses its lease. A short lease causes churn under GC pauses; a long one stalls the pipeline after a crash. Heartbeat renewal helps, but a paused process cannot renew, so renewal does not replace fencing.

What to monitor

Count fence rejections at the storage layer; a rising count means leases are shorter than real pauses. Track lock hold time p99 against the TTL. Alert on any token decrease observed by storage.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-69Your order service runs on several replicas and resolves conflicting edits to a customer's shipping address with last-write-wins, using timestamps stamped by the client devices. Explain how clock skew makes this lose a write that happened later, and when you would replace it with a version vector instead.

The 60-second answer

Last-write-wins (LWW) picks the update with the larger timestamp. It needs no coordination, so it is cheap and always converges. The problem is the timestamp. A client clock can run fast or slow relative to another device, so the "latest" edit by real time may carry a smaller number. Then the winner is the earlier edit, and the later one is silently discarded. Nothing errors, so nothing alerts.

I would not use client wall clocks for conflict resolution at all. I would stamp writes server-side, or use a logical counter, and I would only switch to version vectors when the business needs to detect concurrency, not just pick a winner.

Trace with real figures (hypothetical skew)

Phone A's clock is 3 s ahead of the server. Phone B is accurate.

Real timeDeviceEditClient timestampServer stores
10:00:00.000Astreet = "12 Elm"10:00:03.000ts 10:00:03.000
10:00:01.000Bstreet = "98 Oak"10:00:01.000discarded, 10:00:01 < 10:00:03

B's edit happened a second after A's, and it is lost. The skew is 3 s, so any two edits closer than 3 s can invert. NTP typically keeps well-run servers within a few milliseconds, but phones and laptops are not NTP-disciplined to that level, and users can set their clock wrong entirely.

Failure modes to name

  • Silent lost update: the later write loses because the earlier writer's clock was ahead. Detected only by comparing against an audit trail.
  • Clock rollback: a device clock jumps backward after a timezone or NTP correction, so its new edits always lose to its old ones.
  • Ties: equal millisecond timestamps need a deterministic tiebreak (replica id), or replicas can disagree forever.

Alternatives

  • Server-stamped LWW: the coordinator assigns the timestamp on arrival. Fixes device skew, but the order now reflects network arrival, which is still not causal order across regions.
  • Version vectors: each replica keeps a counter per writer. Two versions are causally ordered if one vector dominates the other; otherwise they are concurrent. For example, {A:2,B:1} vs {A:1,B:2} are concurrent, so you keep both as siblings and let the application or user merge. You pay with metadata that grows with the number of writers and with sibling handling in every read path.
  • Hybrid logical clocks: a timestamp that stays close to wall time but respects causality (a receiver advances its clock past any timestamp it sees). Cheaper than vectors, but it still picks a winner for concurrent writes, so it does not detect conflicts.

When a version vector is needed

Use vectors when silently discarding a concurrent edit is unacceptable and a human or merge function must see both values: shared documents, multi-device settings edited offline, or carts that must not lose items. Keep LWW when the field is a single value where the most recent intent should win and a lost intermediate edit is harmless, and when you can stamp on a server you control.

Verify the detail that matters before the interview: a version vector entry per replica only proves concurrency between the two specific histories; it does not tell you which edit a user meant. That is why the merge policy has to be designed alongside it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-70Under vector clocks, when are two writes concurrent rather than causally ordered, and what does the server keep when neither write dominates the other?

The 90-second answer

Two writes are causally ordered when one clock dominates the other: every component of V is less than or equal to the matching component of W, and at least one is strictly less. V happened before W. If neither clock dominates, the writes are concurrent: neither writer had seen the other's write when it wrote. The server cannot pick a winner from the clocks alone, so it keeps both values as siblings and lets the client resolve them on its next write.

Three replicas, A, B and C, handling a playlist title:

WriteClockRelation to previous
w1, A sets "Road Trip"{A:1, B:0, C:0}none
w2, A renames it after reading w1{A:2, B:0, C:0}w1 < w2
w3, B renames it from a copy that predates w2{A:1, B:1, C:0}concurrent with w2

When w2 and w3 are compared, A is 2 vs 1 (favouring w2) and B is 0 vs 1 (favouring w3). Neither dominates, so both survive as siblings. Comparing w1 with w2 is different: every component of w1 is at most the matching component of w2 and A is strictly less, so w1 is an ancestor and can be discarded.

What the server stores per key is a set of (value, clock) pairs that are pairwise concurrent. A read returns every sibling plus a merged context clock. The client writes its resolution back with that context. The context dominates every sibling it saw, so the server deletes those siblings. A write that arrives with no context is treated as concurrent with everything, so it becomes a sibling instead of silently overwriting.

Storage cost scales with the number of replicas that have written the key, since each clock holds one (replica, counter) entry per replica. Clients must never be given clock entries keyed by session, or the clock grows with every session.

Failure modes to name in review:

  • Clock pruning. Dropping the oldest entries to cap size can make an old write look newer, so a client that was offline for weeks overwrites a live value without a conflict. Detect it by counting pruning events and by sibling counts that fall suddenly.
  • Sibling explosion. Many clients editing one hot key produce long sibling lists on every read. Alert on siblings per key and on read payload size.

When not to use this: a single-leader Postgres row with a version column already gives a total order and a compare-and-set, which is simpler to operate. Vector clocks earn their cost in multi-leader or leaderless stores. Last-writer-wins on wall-clock time always returns one value, so concurrent edits are lost without any signal. Only choose it when losing one of the two edits is acceptable and you can say so.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-71Your feed service serves home timelines for 300 million users, and a few accounts have 50 million followers. Should fan-out on write or fan-out on read apply to those accounts, and what threshold rule would you ship for a hybrid?

The 90-second answer

Assumptions first: a post write is rare compared with timeline reads, reads are roughly 100x writes, and a timeline is served from a per-user cache (Redis sorted set or similar) of post ids. I would not fan out every account the same way, because the cost of one write depends almost entirely on follower count.

Fan-out on write pushes each new post id into every follower's timeline cache at post time. Reads are one range query. Cost per post is followers cache writes. A 50 million follower account produces 50 million writes for one tweet, which takes minutes to drain and blocks the pipeline for everyone else.

Fan-out on read stores each author's posts once. Assembling a timeline means reading the last N posts from each followed account and merging. Cost per read is followees lookups plus a k-way merge. A user who follows 500 accounts pays for 500 reads on every refresh.

The hybrid rule: push for accounts below a follower threshold T, pull for accounts above it. At read time, merge the precomputed push list with a live pull from the followed celebrity accounts.

Worked numbers (hypothetical)

Account typeFollowersWrite fan-out per postRead cost per timeline
normal800800 cache writes1 range read
high-follower50,000,00050,000,000 cache writes1 range read + pull

With T = 100,000, a celebrity post costs 0 writes at post time. Each reader who follows at least one celebrity adds a pull of that account's last ~50 posts, which is one indexed read per celebrity followed. If a typical reader follows 3 celebrities, the read path adds 3 small reads, which is cheap compared with 50 million writes.

Failure modes to watch

  • Threshold set too high: a 4 million follower account gets pushed, and the queue behind it backs up. Detect it as consumer lag on the fan-out topic, p99 of time-to-visible per post.
  • Threshold set too low: many mid-size accounts are pulled, and timeline p99 climbs as followee count grows. Detect it as p99 read latency correlated with follow count.
  • Account crosses T mid-life: posts pushed before the switch stay in followers' caches. The read path must not double-count them, so merge by post id and dedupe.
  • Unfollow or private accounts: a pulled celebrity post must still respect visibility at read time, not only at push time.

Alternatives and when not to use hybrid

Pure fan-out on read is fine when the follow graph is small and reads are cheap, which is why many systems start there. Pure push is fine for a few hundred million cheap writes per day and no celebrity skew. Hybrid is worth its complexity only when the follower distribution is heavy-tailed, as it is here.

I would ship the hybrid with T set from measured fan-out lag, reviewed quarterly, and the threshold stored as config so it can move without a deploy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-72Your URL shortener issues codes from base62 characters. How many characters do you need to hold a billion URLs, what does the arithmetic look like, and what do you give up by choosing a longer code?

The 90-second answer

Five base62 characters give 62^5 = 916,132,832 codes, which is short of a billion. Six give 62^6 = 56,800,235,584, about 57 times the target. I would ship six, generated from a counter through a bijection so the write path never depends on a random draw succeeding. The longer code I would reserve for links that must resist guessing.

Arithmetic:

  • One base62 character carries log2(62) ≈ 5.954 bits.
  • 5 characters: 916M codes, below 1B. Fails.
  • 6 characters: 56.8B codes. At 1B issued, 1B / 56.8B ≈ 1.76% of the space is in use.
  • 7 characters: 3.52 × 10^12 codes. At 1B issued, about 0.028% is in use.

Encoding a counter is repeated division. Trace for id 1,000,000,000 (a hypothetical example):

StepDivideRemainder (digit)Symbol
11e9 by 62^511
2by 62^455
3by 62^341F
4by 62^255T
5by 6242G
6by 116g

Code 15FTGg. Digits 0–9 map to 0–9, 10–35 to a–z, 36–61 to A–Z. Decoding reverses the loop with multiply-add.

Python
ALPHABET = string.digits + string.ascii_lowercase + string.ascii_uppercase
def encode(n: int, width: int = 6) -> str:
    out = []
    for _ in range(width):
        n, r = divmod(n, 62)
        out.append(ALPHABET[r])
    return ''.join(reversed(out))

This fixed-width version only works while n < 62^width. Above that, the output silently truncates, so the service must reject or widen the code.

Counter versus random

A sequential counter has no collisions but leaks volume and makes codes enumerable: anyone can walk 1, 2, 3. A random generator with a unique constraint avoids enumeration but collides. The birthday estimate for n = 1e9 random draws over N = 5.68e10 is n²/(2N) ≈ 8.8 million colliding pairs, so inserts will hit unique-constraint retries throughout the fill. Running a Feistel network over the counter (with cycle-walking, since 62^6 is not a power of two) gives you a permutation: no collisions, no retry loop, and codes that look random.

Failure modes

  • Guessable links: at 1.76% fill, a random guess resolves to a live link about one time in 57. For unlisted or private links, use 7+ characters or a separate unguessable token.
  • Retry storms: if you choose random codes near a high fill, unique-violation rate climbs. Track it as a metric, and alert when retries per insert exceed a small threshold.
  • Silent truncation: a fixed width is only correct below 62^width. Assert it at write time.

The longer code's cost

Seven characters add one byte per link and one byte per index entry. Storage is not the real cost. Each extra character makes printed, spoken and QR-coded links harder to transcribe and lengthens every shared URL. I would not pay that everywhere to fix a problem that a permutation solves at six.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-73We generate random 64-bit order IDs on the client-facing API. Explain roughly how many orders it takes before two IDs collide, and how a unique-key insert should handle a collision when it happens.

The 90-second answer

Assume IDs are drawn uniformly and independently from N = 2^64 values. For n IDs, the probability of at least one collision is approximately p ≈ 1 − e^(−n(n−1)/(2N)). When n is much smaller than √N, this reduces to p ≈ n²/(2N).

√N = 2^32 ≈ 4.3 × 10⁹. That is the scale where collisions start to matter, not a cliff. At n = √N, the exponent is about 0.5, so p ≈ 39%. The 50% point is higher: n ≈ √(2N ln 2) ≈ 5.1 × 10⁹.

Worked check at n = 1 × 10⁹: n²/(2N) = 10¹⁸ / (2 × 1.845 × 10¹⁹) ≈ 0.027, so p ≈ 2.7%. At n = 5 × 10⁹: n²/(2N) ≈ 0.677, so p ≈ 1 − e^(−0.677) ≈ 49%. At n = 2.7 × 10⁹, p is only about 18%. So a billion orders carries a small but real chance over the table's life, and five billion is roughly a coin flip.

For the insert, do not check for the ID first and then insert. Two writers can both see it free. Let the primary key decide:

SQL
-- PostgreSQL 16
INSERT INTO orders (id, tenant_id, idempotency_key, customer_id, total_cents)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (id) DO NOTHING
RETURNING id;

No row returned means the insert hit a conflict. Before generating a new ID, look up (tenant_id, idempotency_key). If a row exists there, a client retry replayed the same request, so return the stored order. If no row exists, the conflict was on id, so generate a fresh ID and retry, capped at three attempts, then fail with 500 and alert. Three collisions in a row point to a broken generator, not bad luck.

The idempotency key needs its own unique constraint on (tenant_id, idempotency_key). A bare ON CONFLICT DO NOTHING without a target would swallow both kinds of conflict and hide which one fired. Targeting (id) in the insert and checking the idempotency key on the empty result keeps the two cases separate.

Trade-offs

A 128-bit ID pushes the bound out of reach at the cost of 16 bytes per key and less index locality for random values. A time-ordered ID keeps inserts append-friendly, but its random tail has its own birthday bound within each millisecond. A database sequence avoids collisions entirely but exposes order counts and needs a central allocator. For public order IDs I would use 128 bits and keep the retry loop as a backstop.

Failure mode to watch

A low-entropy or seeded PRNG repeats IDs far earlier than the bound predicts. Log the retry count per request: if it rises from near zero to around one percent, the generator has changed, not the arithmetic.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-74A marketing link you own has moved, so you can answer it with either a 301 or a 302. Which status makes browsers skip your server on later clicks, and what does that do to your click counts?

The 90-second answer

Use a 302 if you want every click to reach your server and be counted. A 301 is permanent, and browsers cache it. On a repeat visit a browser can follow the stored Location without sending a request to you, so those clicks never reach your analytics.

RFC 9110 defines 301 as a permanent move, and 9111 makes it heuristically cacheable, so a browser may remember the mapping for a long time with no Cache-Control header at all. 302 is a temporary move and is not heuristically cacheable, so without explicit freshness headers it is fetched again each time.

Trace with hypothetical figures, labelled as such: 100,000 clicks a day from 40,000 browsers, where 60% of browsers click again on later days. With a 301, your redirect endpoint logs roughly 40,000 first-visit hits on day one and then only new browsers after that, so the count drops by most of the repeat traffic. With a 302, it logs all 100,000 clicks. The destination pages still see the traffic in both cases, so the gap shows up only in the redirect layer.

The 301 also carries a cost you cannot undo from the server. If you later point the link at a new target, browsers that cached the old 301 keep going to the old target until their cache entry expires, and you cannot purge it from your side. A 302 lets you change the target instantly.

Trade-offs:

  • 301: one fewer server hit per repeat click, lower load and latency, search engines treat it as the canonical address, but analytics undercount and retargeting is sticky.
  • 302: every click is counted and retargeting is instant, but each click costs a server round trip and you own the uptime of the redirect path.
  • Cache-Control: no-cache on a 301 forces revalidation on every click, so you keep the permanent semantics for search engines and still see each click. You pay the same request cost as a 302.
  • 307 and 308 behave like 302 and 301 but keep the HTTP method on the redirected request, which matters for POST endpoints and not for plain link clicks.

When I'd not use 301 at all: any link that is a campaign, a short link with a target that changes, or anything where the count feeds billing. Use 301 for a genuinely permanent move of a page where search ranking matters more than the count.

Failure mode to check: a 301 shipped by mistake from a template or CDN rule can be cached by browsers for months. Detect it by looking at the Cache-Control and status on the live response before you ship, and by watching redirect-endpoint hit counts fall sharply after a change.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-75Your ingest dedup filter covers 400 million live fingerprints with a 30-day TTL, about 13 million expiring and arriving daily. Sized for 1% at 400 million, it measures 9% in production. Why, and what would you ship within 512 MiB per process?

The 90-second answer

Assumptions: standard (non-counting) Bloom filter, a steady live set of 400M fingerprints, 13M inserts and 13M expiries per day, and a hard budget of 512 MiB (4.295e9 bits) per process. The 1% sizing was correct for a set that never changes. The fault is that the formula's n is the number of keys ever inserted since the last build, not the live set.

Why the rate drifted. A Bloom filter cannot clear bits. Expiring a fingerprint does nothing to the filter, so every bit set since the last rebuild stays set. The effective n is cumulative inserts. Work it backwards from the measurement. With m = 3.834e9 bits and k = 7, fp = (1 - e^(-kn/m))^k. For fp = 0.09, 0.09^(1/7) = 0.709, so e^(-7n/m) = 0.291, which gives 7n/m = 1.234 and n = 676M. That is 276M cumulative inserts beyond the live set, about 21 days of churn. The filter was built about three weeks ago and nobody rebuilt it.

Python
import math
def fp(m, n, k): return (1 - math.exp(-k * n / m)) ** k
print(round(fp(3.834e9, 676e6, 7), 3))  # 0.09

A rebuild every 21 days would hold the rate near 1%, but that is a timer and not a design. Over a year the same filter saturates to near 100%, because cumulative inserts pass 4.7B.

Why one filter cannot fit the budget. Bits for a 1% filter at 400M cost 9.585 bits per key, about 457 MiB, so a single generation covering the live set plus one rotation of slack already crowds the budget. Counting filters would support deletes but use four bits per counter, roughly four times the memory, so they are out.

What to ship: rotating generations. Split the 30-day window into three 10-day generations. Each generation takes about 130M inserts over its life, and at rotation you drop the oldest generation whole, which is how expiry happens without any bit clearing. A lookup ORs across the three generations, so the false positive rate is roughly the sum of the three per-generation rates.

Budget: 4.295e9 bits split three ways gives 1.43e9 bits each. Divided by 130M inserts, that is m/n = 11.0 bits per key, so k = round(11.0 x 0.693) = 8. Per-generation rate p = e^(-11.0 x 0.4805) = 0.0051, and the lookup rate is about 3 x 0.0051 = 1.5%. That is slightly above the 1% target, so either accept 1.5% or trim the window to 9 days.

DesignMemorySteady fpExpiry
one filter, sized 400M457 MiB1% then drifts to 9%+none, needs rebuild
three 10-day generations512 MiBabout 1.5%drop oldest generation
counting filterabout 1.8 GiB1%per-key delete

Subtle points a reviewer will check.

  • The generation boundary must be on the TTL clock, not the wall clock of each process. Replicas that rotate at different times see different negatives for the same fingerprint for a few minutes. Rotate from a shared epoch number.
  • A new generation starts empty, so a fingerprint inserted just before rotation must still be written into the new generation. Write to the current generation only, and check all three on reads.
  • Gating only skips the database on a negative. Under a 1.5% false positive rate on a workload that is 95% new fingerprints, roughly 1.4% of new ingests still hit Postgres, so the saving is about 98.5% of the lookups it was built to avoid.
  • Ship the generations as a versioned snapshot so replicas load rather than rebuild 512 MiB at boot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-76You need the 10 largest order totals out of 500 million rows that arrive as a stream and never fit in memory. Explain how a min-heap of size k gets you there, what the cost is compared with sorting everything, and when that choice stops being worth it.

The 90-second answer

Keep a min-heap of size k = 10. For each incoming total, if the heap holds fewer than k items, push it. Otherwise compare it to the heap root, which is the smallest of the current top k. If the new value is larger, pop the root and push the new value. Otherwise discard it. When the stream ends, the heap holds the k largest values.

The cost is O(n log k). Each element does at most one push or pop, and each heap operation is O(log k). Memory is O(k), which is what matters here: 500 million totals never sit in memory at once.

Full sort is O(n log n) time and, for an in-memory array, O(n) memory. With n = 500,000,000 and k = 10, log₂ n ≈ 28.9 and log₂ k ≈ 3.3, so the heap does roughly 3.3 / 28.9 ≈ 11% of the comparison work of a sort, and it never needs the whole dataset in RAM.

Trace (hypothetical totals, k = 3)

InputHeap beforeActionHeap after
40[]push[40]
90[40]push[40, 90]
70[40, 90]push[40, 70, 90]
15[40, 70, 90]15 < root 40, discard[40, 70, 90]
120[40, 70, 90]120 > root 40, pop 40, push 120[70, 90, 120]

The root is always the threshold a new value must beat. That is the invariant to state out loud.

Where streaming matters

If the data is already in a database or an array you can index, sorting or ORDER BY total DESC LIMIT 10 is simpler and the planner may use a top-N heapsort itself. The heap earns its place when input is one-pass: a Kafka consumer, a log file read line by line, a shuffled export you cannot re-read. It also wins when you need top-k over many shards: each shard keeps its own size-k heap and you merge k-sized candidate lists, so network traffic is O(k) per shard instead of O(n).

Failure modes and details

  • Using a max-heap instead of a min-heap. You then need the global maximum at the root, which is the wrong element to evict. The min-heap works because the root is the weakest survivor.
  • Ties. Decide whether equal values displace existing entries, and make the comparison deterministic if the output must be stable across replays.
  • k close to n. When k approaches n the log k factor stops helping and a full sort or quickselect is competitive. Quickselect finds the k-th value in expected O(n) but needs the data in memory.
  • Heap of tuples. Store (total, order_id) if you need the ids back; comparing on total alone loses the identity of the winners.

When I'd pick each: a size-k heap for a single pass over a stream larger than memory, sorting or a database LIMIT for data already indexed and read repeatedly.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-77Your analytics job needs the p99 latency from 50 million samples in one batch, and the samples fit in memory. Would you sort them, or use quickselect, or median-of-medians? Walk me through the average and worst case and how you choose the pivot.

The 90-second answer

For one order statistic I would use quickselect with a random pivot. Expected work is linear, and on random data it beats a full sort by a wide margin. Its worst case is O(n²), so I would only pay for median-of-medians when the input can be chosen by an adversary or the latency bound has to hold with no probabilistic argument.

Quickselect partitions the array around a pivot, then recurses into only the side that contains rank k. Unlike quicksort it discards one side entirely each round, so the work is a geometric-style sum rather than n log n.

Python
import random

def select(a, k):  # k is zero-based, a is mutated
    lo, hi = 0, len(a) - 1
    while lo < hi:
        p = random.randint(lo, hi)
        a[p], a[hi] = a[hi], a[p]
        pivot, i = a[hi], lo
        for j in range(lo, hi):
            if a[j] < pivot:
                a[i], a[j] = a[j], a[i]
                i += 1
        a[i], a[hi] = a[hi], a[i]
        if k == i:
            return a[i]
        elif k < i:
            hi = i - 1
        else:
            lo = i + 1
    return a[lo]

Numbers for 50 million samples (estimates, n = 5 × 10⁷):

StrategyComparisonsNotes
Full sortn log₂ n ≈ 1.28 × 10⁹simple, predictable
Random-pivot quickselect≈ 3.4n ≈ 1.7 × 10⁸ expectedpractical default
First-element pivotn²/2 ≈ 1.25 × 10¹⁵ on sorted inputdo not use
Median-of-mediansO(n) worst case, larger constantseveral times slower on random data

The 3.4n figure is the expected-comparison bound for the median, 2n + 2n·ln 2, and it is the largest over k, so it is an upper bound for any percentile.

Why random beats a fixed pivot. A fixed rule such as first element, last element or median-of-three has an input that defeats it. Sorted or reverse-sorted data is enough for the first two. Median-of-three has published killer sequences. A random pivot makes the expected cost independent of input order, because no fixed input is bad for most random choices. Worst case still exists, but its probability is negligible at this size.

Why median-of-medians exists. Split into groups of five, take each group's median, then recursively select the median of those medians as the pivot. That pivot is guaranteed to sit between roughly 30% and 70% of the elements, so each round discards at least about 30%. The recurrence T(n) ≤ T(n/5) + T(7n/10) + O(n) solves to O(n). The price is the group medians and the recursion on every round, which is why it loses on random data.

Failure modes to name in the interview:

  • Duplicates. Lomuto partitioning with strict less-than degrades to O(n²) when most values are equal, because every element lands on one side. Use three-way partitioning for keys with heavy repetition.
  • Mutation. The routine reorders the input. If the caller still needs the original order, copy first: 50 million 8-byte values is 400 MB of extra memory.
  • Adversarial order. If clients can influence the ordering of the batch, a seeded or predictable RNG can be attacked. Use the OS-seeded generator.
  • Detection. Track recursion depth. C++ std::nth_element and libstdc++ use introselect: quickselect with a depth limit that falls back to heap-based selection, which bounds the worst case at O(n log n).

What I would ship. For a batch p99, call the standard library selection routine, or use random-pivot quickselect with three-way partitioning if the language lacks one. I would add median-of-medians only where the input is hostile and the bound has to be deterministic.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-78In sliding window maximum with a monotonic deque, what is the time complexity per element, and why is it not O(k)?

The 90-second answer

Amortized O(1) per element, so O(n) for the whole array regardless of window size k. The cost is not O(k) because the deque never rescans the window. Each index is pushed once when the scan reaches it and popped at most once, either from the back when a newer value is greater than or equal to it, or from the front when it leaves the window. The total number of pops across the whole run is bounded by the number of pushes, which is n. Work per element is therefore constant on average, even though a single step can pop several entries.

The invariant that makes this hold: the stored indices have strictly decreasing values from front to back, and the front is the current window maximum. Popping from the back while nums[dq[-1]] <= x is what keeps that order, and it is why a discarded index can never be needed again.

Python
from collections import deque

def max_sliding_window(nums, k):
    dq = deque()
    out = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

Counting check on n = 8, k = 3 (hypothetical input, worked by hand): there are 8 pushes and at most 8 pops in total, so about 16 deque operations for 8 elements, which is 2 per element. A naive scan that recomputes each window's maximum does 3 comparisons per window across 6 windows, which grows to n·k as k grows.

Failure modes and choices

Storing values instead of indices breaks the expiry test, because you cannot tell how old a value is. Using < instead of <= in the back pop is also correct, but it keeps equal values and can grow the deque on inputs such as all-equal arrays. For k greater than n, decide and state whether the function returns an empty list.

Alternatives: a max-heap with lazy deletion costs O(n log n). A sparse table answers arbitrary range maxima in O(1) after O(n log n) preprocessing, which is worth it only when you query many ranges rather than one fixed-size sweep. Brute force is O(n·k) and is fine only for small k.

The deque does not apply if windows vary in size or if you need maxima over arbitrary past ranges.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-79Merchandisers type discount formulas into your pricing evaluator, which must match Python's precedence for unary minus and `**`. Walk me through how the two-stack evaluator handles `2 ^ -3 ^ 2` and `-a ^ 2 - -b` in one pass with no lookahead, and what goes wrong if a prefix operator pops on arrival.

The 90-second answer

The evaluator has to decide unary versus binary from the previous token alone, because it cannot look ahead. A - is unary when no operand precedes it. That is (, an operator, or the start of input. Give unary minus its own token, u-, with precedence 3: above * and /, below ^ (precedence 4, right-associative). Python's rule is that -x ** 2 is -(x ** 2), so u- must be pushed on arrival and never pop anything. Only binary operators pop.

If a prefix operator pops on arrival, the stack is consumed too early. For -a ^ 2 the u- would negate a before the ^ sees it, giving (-a)^2 = 9 where Python gives -9. That is the failure mode to test for.

Pop rule for binary operators. Pop the top t when prec(t) > prec(o), or when they are equal and o is left-associative. ^ is right-associative, so 2 ^ 3 ^ 2 = 2 ^ (3 ^ 2) = 512.

Trace of 2 ^ -3 ^ 2 (a=3, b=4 in the second expression, but this one has none):

tokenprev operand?token classops (top right)outaction
2nooperand2push
^yesbinary, prec 4^2stack empty, push
-nounary u-^ u-2prefix, push without popping
3yesoperand^ u-2 3push
^yesbinary, prec 4^ u-2 3top u- is 3 < 4, no pop; push
2yesoperand^ u- ^2 3 2push
endpop ^: 3^2=9, then pop u-: -9, then pop ^: 2^-9

Result: 2^-9 = 0.001953125, matching Python's 2 ** -3 ** 2.

Trace of -a ^ 2 - -b with a=3, b=4:

The first - is unary (start of input), so it is pushed. a and 2 go to the output. ^ arrives and does not pop u- (3 < 4), so ^ sits on top. The binary - arrives: it pops ^ (4 > 1), giving 3^2 = 9, then pops u- (3 > 1), giving -9. The second - follows a binary operator, so it is unary and pushed. b goes to the output. At the end, u- gives -4 and the binary - gives -9 - (-4) = -5. Python gives -3**2 - -4 = -5.

Constraints that interact. The unary decision depends on prev_operand, which must be reset to false after ( and after every operator, and set true after ). Setting it true after u- would make - - x binary and fail. A right-associative ^ combined with a prefix operator is the only case where pop-on-arrival is observable, so test -x ^ y, 2 ^ -x, and 2 ^ -x ^ y directly. Random fuzzing rarely generates a prefix minus directly after ^, so these must be explicit cases.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-80Your service stores a binary tree of integer keys as one string using preorder traversal. Explain why the encoding needs null markers, give two different trees that collide without them, and state the cost of rebuilding the tree from the string.

The 90-second answer

Preorder visits the node, then the left subtree, then the right subtree. The string only records the order of keys, and that order does not determine the shape. Write a # for every missing child and the sequence becomes unambiguous: each node's two children are exactly the next two subtrees in the stream. Rebuilding is one pass over the tokens, O(n) time, with recursion depth equal to the tree height.

The collision. Take two trees with the same preorder key sequence 1 2 3:

  • Tree A: root 1, left child 2, right child 3. Preorder without markers: 1 2 3.
  • Tree B: root 1, left child 2, and 2's left child is 3. Preorder without markers: 1 2 3.

Both produce 1,2,3, so a reader cannot tell whether 3 is a right sibling or a grandchild. With markers they separate:

TreePreorder with # markers
A1,2,#,#,3,#,#
B1,2,3,#,#,#,#

The count gives a check for free. A tree with n nodes always has n+1 nulls, so 2n+1 tokens in total. A string that does not parse to exactly that many tokens is corrupt, and the decoder should reject it rather than return a partial tree.

Serialize and deserialize.

Python
# Python 3.12
def serialize(node, out):
    if node is None:
        out.append('#')
        return
    out.append(str(node.val))
    serialize(node.left, out)
    serialize(node.right, out)

def deserialize(tokens):
    it = iter(tokens)
    def build():
        tok = next(it)
        if tok == '#':
            return None
        node = Node(int(tok))
        node.left = build()
        node.right = build()
        return node
    root = build()
    if next(it, None) is not None:
        raise ValueError('trailing tokens')
    return root

Each token is consumed exactly once, so time is O(n) and the iterator is O(1) extra state beyond the token list. The cost that matters is the recursion. Recursion depth equals tree height h. For a balanced tree of 1,000,000 nodes, h is about 20. For a skewed tree of the same size, h is 1,000,000, and Python's default recursion limit of 1000 stops it on the first call. The fix is an explicit stack holding pending right children, which keeps the same O(n) time but moves memory from the call stack to the heap.

Alternatives. Level-order (BFS) with markers also round-trips, and it is easier to read in a log, but it needs a queue and produces the same 2n+1 tokens. Inorder alone never works, since 1 2 3 could be several shapes. An inorder plus preorder pair rebuilds without markers in O(n log n) with a lookup map, or O(n) when inorder positions are precomputed, but it requires unique keys and two traversals. Pick markers when keys can repeat or when you want a single self-delimiting stream.

Failure modes to name. A delimiter that can appear inside a key (a comma in a string key) silently shifts every token after it. Use an escape or a length-prefixed encoding for non-integer keys. A decoder with no end check accepts truncated input and returns a subtree, which looks like valid data downstream. Recursive decoders on untrusted input can be driven into stack overflow by a 1,000,000-node chain, so bound the depth or go iterative before the input reaches production.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-81Your room-booking service receives meeting requests as (start, end) pairs and must place each one in a room, reusing rooms whenever it can. Walk me through how the heap top decides reuse, and why the whole pass is O(n log n).

The 90-second answer

Sort meetings by start time. Keep a min-heap of end times, one entry per room in use. For each meeting with start s, look at the heap top. If the top end is <= s, that room is free: pop it and reuse it. Otherwise open a new room. Either way, push the meeting's end. The number of rooms needed is the heap size at the end of the pass, because reuse never shrinks the heap.

The top decides reuse because it is the room that frees up soonest. If the earliest-finishing room is still busy at s, every other room is busy too, so no reuse is possible. If it is free, taking it is never worse than opening a new room.

Use half-open intervals [start, end). A meeting ending at 10:00 frees its room for one starting at 10:00, so the comparison is <=, not <.

Trace. Minutes from midnight, meetings (0,30), (5,10), (15,20):

meetingheap beforetop vs startactionheap afterrooms
(0,30)[]noneopen room[30]1
(5,10)[30]30 > 5open room[10,30]2
(15,20)[10,30]10 <= 15pop 10, reuse[20,30]2

Code (Python 3.12)

Python
import heapq

def rooms_needed(meetings):
    meetings = sorted(meetings)              # by start
    busy_until = []                          # min-heap of end times, one per room
    for start, end in meetings:
        if busy_until and busy_until[0] <= start:
            heapq.heapreplace(busy_until, end)   # reuse the earliest-free room
        else:
            heapq.heappush(busy_until, end)      # open a new room
    return len(busy_until)

Why O(n log n). The sort costs O(n log n) and dominates. Each meeting then does one heapreplace or one heappush, each O(log k), where k is the current room count and k <= n. The loop is O(n log k), which sits inside the same bound. heapreplace pops and pushes in one sift, so a reuse costs one operation, not two.

For a booking service handling a day of 200,000 requests (a hypothetical figure), the sort takes milliseconds. The heap is not the bottleneck; the input validation and the database write are.

Failure modes.

  • Unsorted input: the heap top is then compared with a meeting that does not come next in time, and reuse decisions are wrong with no error raised.
  • Using < instead of <=: back-to-back meetings each need their own room, so the count is inflated for every booking that ends exactly when the next starts.
  • An end before start: reject at ingestion. Otherwise the meeting pushes a smaller end than its start and quietly steals a room.
  • Mixed time zones or DST gaps: normalise to UTC epoch seconds before sorting.

Alternative. Sort the starts and the ends separately and sweep with two pointers, counting concurrent meetings. That is also O(n log n), uses O(n) extra memory, and needs no heap. It gives the maximum room count but not which room each meeting gets. Use the heap when you must assign rooms. Use the sweep when you only need capacity, such as sizing rooms for a planning dashboard.

If you need the assignment, store a room id with each end time in the heap tuple (end, room_id). Ties on end then break on the id, which keeps the output deterministic for tests.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-82On an unweighted graph, why does BFS find shortest paths, and what breaks once edges have weights?

Short answer

BFS visits nodes in order of edge count from the source: all nodes one hop away, then all two hops away, and so on. The first time it reaches a node, it has used the fewest edges possible. On an unweighted graph every edge costs the same, so fewest edges means least cost.

With weights, BFS still counts hops. It never compares a longer path with cheaper edges against a shorter one with expensive edges. Dijkstra fixes this by settling nodes in order of total weight from the source, not hop count, using a priority queue.

Trace

Unit-weight graph, start A with edges A-B and B-D and A-C and C-D. Queue: [A]. Pop A, enqueue B and C at distance 1. Pop B, enqueue D at distance 2. D is then settled at 2, and no path with fewer edges exists.

Weighted version: A-B = 1, B-C = 1, A-C = 4. BFS treats A-C as one hop and reports cost 4 for C. The real shortest cost is A-B-C = 2. BFS returns a wrong answer without raising any error.

Code (Python 3.12)

Python
from collections import deque

def bfs_dist(adj, src):
    dist = {src: 0}
    q = deque([src])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in dist:      # mark on enqueue: each node enters once
                dist[v] = dist[u] + 1
                q.append(v)
    return dist

The queue holds at most two distinct distance levels, which is why the first visit is the minimum. Marking on enqueue keeps each node in the queue once.

Costs

BFS with adjacency lists is O(V + E) time and O(V) space. Dijkstra with a binary heap and lazy deletion is O(E log V).

Alternatives

  • Weights are only 0 or 1: 0-1 BFS, O(V + E), with a deque.
  • Weights are small bounded integers: Dial's algorithm.
  • Weights can be negative: Dijkstra is wrong. Use Bellman-Ford, O(VE).

When to pick what

If every edge costs the same, use BFS. If the graph has weights, use Dijkstra and check at ingest that no weight is negative, because one bad edge gives wrong output silently.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-83Your batch pricing job walks 200,000 line items in order. No two adjacent items may both get a discount, each item has a non-negative discount value, and finance caps discounted items per 1,000-item shard at 50 and needs the chosen set for audit. Define the DP state, say why the best total alone no longer suffices, and show what the state must carry for the cap and the audit trail.

The 90-second answer

The adjacency rule alone needed only the best total up to i and whether item i-1 was taken. The shard cap changes that. Within a shard, the number of discounted items so far is a second dimension, and two prefixes with equal totals but different counts no longer have the same future: one may still afford a discount the other cannot. So the state becomes (i, taken_prev, count) with value = maximum total. The count is bounded by 50, so the table is 1,000 × 2 × 51 per shard, about 102,000 cells, small enough to keep.

The audit requirement is a separate concern and should not be folded into the state. Store a back-pointer per cell (the predecessor's taken_prev and count) and reconstruct the set once, walking backwards from the best final cell. Carrying sets inside states brings back the exponential blow-up you were trying to avoid.

Recurrence. Let f[i][t][c] be the maximum total over items 0..i with c discounts used, where t says whether item i was taken.

Skip: f[i][0][c] = max(f[i-1][0][c], f[i-1][1][c]). Take (needs c ≥ 1, previous skipped): f[i][1][c] = f[i-1][0][c-1] + v[i].

Base: f[-1][0][0] = 0, everything else -∞. Read the answer as the max over t and c ≤ 50 at the last index.

Trace with cap 1 (toy values, labelled hypothetical). Values [4, 6, 5], cap 1. Starting cells after item 0: skip (0,0,0)=0, take (0,1,1)=4. Item 1: skip keeps max of the item-0 cells, giving 4 with count 0 and 4 with count 1; take needs count 0 from skip, giving 6 with count 1. Item 2: take requires previous count 0 and previous skip, but the only count-0 skip cell is 0, so take gives 5 with count 1. The best is 6, from item 1 alone. Had the cap been missing, the greedy answer 4+5=9 would look right, but adjacency forbids it anyway. The cap only binds when it is tighter than the adjacency optimum, which is why both constraints must be in the state together.

Failure modes. Forgetting the c ≥ 1 guard lets the take branch read a negative index and silently produce garbage, so test with cap 0. Sharding by reusing one table across shards without resetting leaks counts between shards and undercounts discounts; the failure is a plausible-looking total. Storing -∞ as 0 instead of a sentinel makes unreachable states look reachable and inflates totals when all values are small.

Cost and when to stop. Time is O(n × cap) per shard, here about 50,000 steps for each shard of 1,000 items, and memory is O(cap) if you roll the index and keep back-pointers only for the audit. If the cap became per-category rather than global, the state would need one count per category, and the table would stop being small. At that point, say so and reach for integer programming with the adjacency constraint as a linear inequality, rather than stretching the DP.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-84Your pricing service scans a sequence of strictly increasing candidate prices while keeping a tails array. Why does that array stay sorted after every element, and which slot does each new value overwrite?

The 90-second answer

Assume the question means the strictly increasing longest subsequence. tails[k] holds the smallest possible last value of any increasing subsequence of length k+1 seen so far. Each new value x finds the first slot i with tails[i] >= x and overwrites it. If no such slot exists, x is appended. The array stays strictly increasing because the overwrite preserves order, and the length of tails is the LIS length.

Why the array is sorted. Take any k >= 1. tails[k] is the end of some subsequence of length k+1. Drop its last element and you get a subsequence of length k ending at some value v, with v < tails[k]. Since tails[k-1] is the minimum possible end for length k, tails[k-1] <= v < tails[k]. So the invariant holds by construction, not by accident.

Why the overwrite keeps it sorted. Let i be the first index with tails[i] >= x. Then tails[i-1] < x because i was the first such index. That means x can end a subsequence of length i+1, and it is at least as small as the old tails[i], so replacing it is never worse. Order is kept: tails[i-1] < x <= old tails[i] < tails[i+1].

Why binary search. Because the array is sorted, the first index with tails[i] >= x is a lower-bound search. That is O(log n) per element, so the whole pass is O(n log n).

Python
from bisect import bisect_left

def lis_len(a):
    tails = []
    for x in a:
        i = bisect_left(tails, x)   # first index with tails[i] >= x
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)

Trace on 3 1 4 1 5 9 2 6:

xlower bound indextails after
30 (append)[3]
10[1]
41 (append)[1, 4]
10[1, 4]
52 (append)[1, 4, 5]
93 (append)[1, 4, 5, 9]
21[1, 2, 5, 9]
63[1, 2, 5, 6]

Final length 4, matching 1, 2, 5, 6. Note the array is not itself a subsequence of the input. Values like 2 and 6 were never adjacent in the source.

The strictness detail. Equal values must replace, not extend, which is why the search is bisect_left (first >= x). With bisect_right (first > x), the input 2 2 gives tails = [2, 2] and a length of 2, which is wrong for strict increase. For non-decreasing sequences, switch to bisect_right, and the answer changes accordingly.

Failure modes to name. Off-by-one in the search is the common bug: returning i when i == len without appending, or using hi = len - 1 and missing the append case. Test with [2, 2], [], and a strictly decreasing input, which should give length 1.

When not to use it. If you need the subsequence itself, you must store predecessor indices alongside tails, which is extra state and the part a candidate should mention before being asked. If the sequence is short, the O(n^2) DP is simpler and fast enough.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-85Your importer writes 10,000 event rows over a link with 1 ms round-trip latency. Compare one INSERT per row with multi-row batches. Walk me through the round-trip arithmetic and what the transaction boundary costs in each case.

The 60-second answer

At 1 ms round trip the network dominates, so count round trips first, then commits. Assumptions: PostgreSQL 16, one connection, client and server in the same region, and about 2 ms per commit for the WAL flush (hypothetical, so measure your own fsync cost before quoting it).

Per-row, autocommit: 10,000 statements × 1 ms = 10 s of waiting, plus 10,000 commits × 2 ms = 20 s. Total ≈ 30 s.

Per-row inside one transaction: 10,000 × 1 ms = 10 s, plus one commit of 2 ms. Total ≈ 10 s. The waste in the first case was the commits, not the rows.

Multi-row batches of 500 in one transaction: 10,000 / 500 = 20 statements × 1 ms = 20 ms. Server work at a hypothetical 10 µs per row adds 100 ms. One commit adds 2 ms. Total ≈ 122 ms.

ApproachRound tripsCommitsEstimated time
Per row, autocommit10,00010,000~30 s
Per row, one transaction10,0001~10 s
500-row INSERT, one transaction201~0.12 s
COPY, one transaction1 streamed1server-bound
SQL
BEGIN;
INSERT INTO plays (user_id, track_id, played_at)
VALUES (1, 17, now()), (2, 17, now()) /* ...498 more tuples... */;
COMMIT;

Trade-offs. A bigger transaction holds row locks longer, grows the WAL, and one failure rolls back all 500 rows. Chunking into 500-row transactions gives 20 commits, roughly 40 ms more at the figures above, and a bounded retry unit. PostgreSQL caps bind parameters at 65,535 per statement, so 500 rows × 8 columns fits but 10,000 × 8 does not. That cap is the second reason to chunk.

Failure modes. A unique violation aborts the whole statement. If duplicates are expected, use ON CONFLICT DO NOTHING and compare the affected row count with the batch length, because a silent shortfall is the failure you will otherwise miss. Set a statement timeout so one stuck batch cannot hold a connection indefinitely.

When not to batch. When each row must be acknowledged on its own, or when a user is waiting on a single write, per-row latency is the metric and batching does not help. For bulk loads with no per-row acknowledgement, COPY removes most of the statement overhead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-86On PostgreSQL, what does the EXPLAIN row estimate tell you, and how does it differ from the actual rows?

The 90-second answer

Every plan node carries two row counts. The rows= in the cost section is the planner's estimate: how many rows it expects that node to output, derived from table statistics collected by ANALYZE. The rows= in the actual section is what the executor really produced, and it is reported per loop. Multiply the actual figure by loops to get the total.

The estimate drives the plan. The planner picks join order, join method and scan type from it, so a wrong estimate can produce a wrong plan even when the SQL is fine. The gap between the two numbers is the first thing to check when a query is slow.

Worked example (hypothetical figures).

Seq Scan on orders  (cost=0.00..21834.00 rows=398120 width=24)
                    (actual time=0.031..212.4 rows=401877 loops=1)
  Filter: (status = 'open'::text)
  Rows Removed by Filter: 598123

The estimate is 398,120 and the actual is 401,877, an error of about 1%. The plan choice is sound.

An error of a factor of 10 or more is the signal to investigate. The usual causes are stale statistics after a bulk load or delete (run ANALYZE orders and check last_autoanalyze), and correlated columns, because the planner multiplies selectivities as if they were independent. The fix for the second case is CREATE STATISTICS ... (dependencies) ON status, region FROM orders.

Failure mode to name. Assuming the estimate is exact. A plan that was right at small table size can go wrong after growth with no query change, so compare estimated and actual rows whenever a plan shifts between releases.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-87Your listening-history API lets a client page through 2 billion plays for one user, newest first. Why does a keyset cursor keep a page 40,000 deep as cheap as page one, which index makes that true, and what does the client give up?

Core answer

Keyset pagination remembers the last row the client saw and asks the index for rows strictly after it. Its cost depends on page size and B-tree depth, not on how far the client has paged. OFFSET works the other way: the database must produce and discard every row before the offset.

Assumptions: PostgreSQL 16, a plays table with 2 billion rows, sorted by (played_at, id) descending and filtered by user_id.

SQL
SELECT id, played_at, track_id
FROM plays
WHERE user_id = $1
  AND (played_at, id) < ($2, $3)
ORDER BY played_at DESC, id DESC
LIMIT 50;

Index: CREATE INDEX plays_user_feed ON plays (user_id, played_at DESC, id DESC);

Both sort columns are descending in the index, so the scan seeks to the cursor and reads 50 entries, then stops. The first page has no cursor, so it drops the row comparison.

Hypothetical arithmetic: page 40,000 with LIMIT 50 is OFFSET 2,000,000. At about 1 µs per index entry visited, that is roughly 2 s per request. The keyset query descends about 3 or 4 B-tree levels and reads 50 entries, which is a few milliseconds at most. The keyset cost is the same at page 1 and page 40,000.

Why the id tiebreaker exists

played_at is not unique. Trace with page size 2 over rows (100,7), (100,6), (100,5), (99,4). Page 1 returns (100,7) and (100,6), so the cursor is (100,6). With the pair, the next query returns (100,5) and then (99,4). If the cursor held only the timestamp, played_at < 100 would return (99,4) and silently drop (100,5).

What the client gives up

  • Jumping to page N. There is no page number, so reaching page 40,000 means walking the cursors. UIs offer next and previous only.
  • Total count. COUNT(*) over the filter is still a scan. Serve an estimate or drop the count.
  • Cheap backward paging. Previous means running the reversed ordering from the cursor and reversing results in the app. The client must keep the first cursor of each page it has shown.
  • Stable positions. Nothing can refer to 'row 1,000,000' across sessions.

What the server must still get right

  • The sort key must not change. If played_at is edited after the client passed the row, the row is skipped (moved down) or shown twice (moved up).
  • Cursor precision. Encode the timestamp with its microseconds. A client that rounds to milliseconds moves the seek point and duplicates rows at the boundary.
  • NULLs. (played_at, id) < (NULL, ...) evaluates to NULL, so rows with a null sort key disappear. Make the column NOT NULL.
  • Index mismatch. An index on (played_at, user_id) forces a sort of all the user's rows on every page. EXPLAIN (ANALYZE, BUFFERS) shows a Sort node over millions of rows. That is the regression to catch in review.

New plays inserted at the head do not shift a forward cursor, which is the main reason keyset suits feeds. Encode the cursor as an opaque, signed value with a version byte, so the sort can change later without breaking clients mid-scroll.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-88Your accounts table soft-deletes rows by setting deleted_at, and a user who deleted 'acme' cannot register 'acme' again. Explain why a plain UNIQUE index on name causes this, and what index change lets a name be reused after deletion while live names stay unique.

The 90-second answer

A unique index does not know what deleted_at means. It holds an entry for every heap row, including the tombstone left by a soft delete, so the deleted row still owns the key and the insert fails with SQLSTATE 23505. The fix is a partial unique index that only indexes live rows.

SQL
CREATE UNIQUE INDEX accounts_name_live_uq
  ON accounts (name)
  WHERE deleted_at IS NULL;

The rule to state out loud: one live account per name, and any number of tombstones per name. Only the partial index expresses that. Tombstones keep their primary key, so foreign keys from orders and invoices still resolve.

Trace. Assume the old plain index accounts_name_key on name.

StepStatementResult
T1INSERT ... name='acme'id 1 created
T2UPDATE accounts SET deleted_at = now() WHERE id = 1id 1 is a tombstone, its index entry remains
T3INSERT ... name='acme'23505 on accounts_name_key

After the partial index replaces the plain one, T3 succeeds and gets id 2. The index has no entry for id 1, so it is also smaller.

Two details that break in practice

  • The planner only uses a partial index when the query's WHERE clause implies the index predicate. Write the predicate exactly as deleted_at IS NULL. A query filtered by deleted_at IS NULL AND NOT is_archived still implies it, but one that filters on deleted_at IS NOT DISTINCT FROM NULL written differently may not match in every version.
  • An upsert must name the same predicate in its conflict target: INSERT ... ON CONFLICT (name) WHERE deleted_at IS NULL DO NOTHING. Without the WHERE, PostgreSQL cannot infer the partial index and raises 42P10, so a deploy that changes only the ON CONFLICT clause fails at runtime.

Why not unique on (name, deleted_at)

This is the tempting alternative and it is wrong. Live rows have deleted_at NULL, and unique indexes treat NULLs as distinct by default, so two live 'acme' rows never collide. NULLS NOT DISTINCT (PostgreSQL 15 and later) closes that gap, but then only one tombstone per name can exist, so the second deletion of a reused name fails. The partial index avoids both problems because it is defined on exactly the rows the rule is about.

Other options

  • Renaming tombstones inside the delete transaction, for example name = name || '#' || id, works with the plain index. It leaves a convention every reader, export and audit query must know.
  • Moving deleted rows to an archive table removes the constraint problem. It costs restore logic, foreign keys that now point at a different table, and a second write on every delete.

I would ship the partial index. It keeps one table and stable ids, and failures show up as clear 23505 on live names or as 42P10 after a bad deploy.

What it does not fix. Tombstones still bloat the heap and any non-partial index. A large table still needs a retention-based purge of old tombstones, which is a separate decision with its own locking and foreign key cost.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-89Your ingest queue has capacity 1,000 and the writer drains 2,000 rows/s while producers push 6,000/s. Explain how backpressure reaches the producers, and whether a full queue should block the sender or drop the row.

The 60-second answer

A bounded queue turns a rate mismatch into a wait. When the writer drains slower than producers push, the queue fills, and the next send blocks. That block is the only signal that travels upstream. Blocking is right when losing a row is unacceptable, and dropping is right only when a lost row is cheap and counted.

The arithmetic. Arrival is 6,000/s and drain is 2,000/s, so the deficit is 4,000 rows/s. A queue of 1,000 fills in 1,000 / 4,000 = 0.25 s. After that, producers can only enter at the writer's rate, 2,000/s. Each producer's throughput equals its share of that rate, no matter how fast it could otherwise run.

TimeQueueProducer behaviour
0 s0full speed
0.25 s1,000 (full)blocked on send
after that1,000admitted at 2,000/s total

Blocking. The producer's goroutine or thread waits, its input buffer fills, and the slowdown reaches the client through TCP flow control or an edge timeout. Give the send a deadline and return 429 with Retry-After when it expires, so the client gets an explicit answer instead of a stalled connection.

Go
ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond)
defer cancel()
select {
case queue <- row:
case <-ctx.Done():
    http.Error(w, "busy", http.StatusTooManyRequests)
}

Dropping. A default branch in the select discards the row immediately. This keeps producers fast, but every dropped row is data the system never stored. Use it for sampled telemetry or metrics, and increment a counter so the loss is visible.

Which to pick. For orders, payments or anything a customer can later ask about, block with a deadline and reject. For metrics, drop and count. A bigger queue does not answer the question. It only postpones the wait and raises the memory held when the writer falls behind, since 1 KB per row at a 4,000 rows/s deficit adds about 14 GB per hour of backlog.

Detection. Watch queue depth as a fraction of capacity, the enqueue wait at p99, and the drop or 429 counter. A queue pinned at 100% for minutes means the writer is the bottleneck, and the fix belongs there.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-90During overload, which kind of request should a service shed first: a checkout payment or a background batch export?

The 90-second answer

Shed the batch export first. A checkout payment moves money and a user is waiting on it, so it belongs to the protected class. A background export has no user blocked on its result and can be retried later, so when capacity runs out it is the class whose loss the business can absorb.

The rule behind this is to order request classes by business criticality and shed from the lowest class upward, not in arrival order. Arrival order sheds whichever requests happen to arrive last, which may be checkouts.

Where the decision happens. Make it at admission, before the request holds a thread, connection or database slot. Rejecting early is cheap. A request that is accepted and then fails after it has taken a database connection wastes the capacity it was meant to protect.

Classify from the route, not the client. The gateway should set the class from the route table, for example an X-Request-Class header it writes itself. If clients can set their own class, every caller will mark its traffic critical.

Default unknown routes to the lowest class. A new endpoint with no entry in the route table should not flood the protected class by accident.

Detection. Watch the rejection rate per class. If checkout rejections rise while batch rejections stay flat, the classes or their budgets are wrong.

Shedding protects the critical path while you add capacity. It does not replace capacity.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-91Your customer export takes 20 to 40 minutes. Design the 202 contract: what the POST returns, the status resource, the polling interval, and what happens when a client resubmits after a timeout.

Core answer

Return 202 Accepted immediately, with a Location header pointing at a status resource, and run the export on a queue. RFC 9110 (section 15.3.3) defines 202 as accepted for processing with no guarantee the work will succeed, so the body describes the job, not the result.

HTTP
POST /exports HTTP/1.1
Idempotency-Key: 5b1e0c9a
Content-Type: application/json

{"tenant":"t_91","range":"2026-10"}

HTTP/1.1 202 Accepted
Location: /exports/ex_77a2
Retry-After: 30
Content-Type: application/json

{"id":"ex_77a2","status":"queued"}

Status resource. GET /exports/ex_77a2 returns 200 with status set to queued, running, succeeded or failed, plus progress while running. On success it carries a result URL. I would not answer with a 303 to the file, because a signed download URL is short-lived and a redirect hides its expiry from the client.

Polling interval. The server sends Retry-After on the 202 and on every GET while the job runs. The client waits at least that long, then backs off with full jitter, capped at 60 s. Hypothetical figures: a 30 s interval over a 40 minute job is 80 polls per export. At 2,000 concurrent exports that is about 67 requests per second on the status route, which a single read replica handles, so the interval is not the bottleneck. A client that ignores Retry-After gets 429 with its own Retry-After.

Idempotent resubmission. Store Idempotency-Key -> (job_id, sha256(body)) in the same transaction as the job row, then publish from an outbox. Three cases:

  • Same key, same body hash, first request still queued or running: 202 with the same Location. Not 409.
  • Same key, same body, job finished: 202 or 200 on the status resource, same job id. No second export.
  • Same key, different body: 422 with code: idempotency_key_reused.

Trace: request 1 commits the key row and job ex_77a2, then the response is lost to a 2 s client timeout. The retry arrives 2 s later, finds the key, and returns the same 202. The export runs once.

Failure modes.

  • Enqueue before commit: a crash leaves a job with no key row, and the retry creates a duplicate. The outbox removes this.
  • Key retention shorter than result retention: a retry after the key expires starts a second export. Keep keys at least as long as the status resource.
  • Expired status: return 410 Gone, not 404, so clients stop polling and resubmit on purpose.
  • Worker dies mid-export: hold a lease renewed by heartbeat. When it lapses, the job is requeued. Write to a temporary object and rename on success, so a rerun overwrites nothing visible.

The Idempotency-Key header is an IETF draft, not an RFC; check its current status before quoting it to a reviewer.

Detection: alert on p99 age of queued jobs, count of keys reused with a different body hash, and status GET rate per job.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-92A payment partner posts invoice events to your webhook endpoint with an HMAC signature header. Why must the HMAC be computed over the raw request body rather than the parsed JSON, and what would a timestamp in the signed string add?

The 90-second answer

Sign the exact bytes the sender transmitted. Parsing and re-serialising changes whitespace, key order, number formatting and unicode escapes, so an HMAC over json.dumps(json.loads(body)) fails on deliveries that are perfectly valid. The receiver must hash the body before any parser touches it. Teams that hit this failure often loosen the check to make it pass, which is worse than the original problem.

The timestamp goes inside the signed string as timestamp + '.' + raw_body. Without it, the signature proves only that someone with the secret produced those bytes at some point. A captured delivery can be replayed forever. With it, the receiver can reject anything outside a tolerance window, because an attacker cannot change the timestamp without invalidating the MAC.

Trace. The sender posts {"id":"evt_91","type":"invoice.paid"} at t=1718000000 with header t=1718000000,v1=3f9a…. The signed string is 1718000000. followed by those exact bytes. Suppose the receiver had hashed a re-serialised copy that dropped the space after the colon in the JSON. The MAC would not match and a valid delivery would be rejected. Hypothetical figures, but they show the failure mode.

Signed stringResult on receipt
raw body, timestamp includedverifies; age checked against tolerance
re-serialised JSONfails on valid deliveries after a library change
raw body, no timestampverifies forever; replay not bounded
timestamp in header but not signedattacker rewrites the header and the old MAC still checks only if it covers the body, so bind it

A timestamp tolerance bounds how long a captured request stays usable, but it does not stop a replay inside that window. That needs a seen-set keyed on the signature or event id, shared across instances, with a TTL longer than the tolerance. HMAC also needs a shared secret, so the verifier could forge deliveries. For third parties who must verify without holding a secret, asymmetric signatures such as Ed25519 are the alternative. For an internal partner, HMAC is the simpler choice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-93You shadow-write each order to a new store behind a flag, and the shadow write is fired after the primary commit. Compare a synchronous shadow write with an asynchronous one: what does each do to the caller's latency and outcome, and which one can leave the two stores diverged without anyone noticing?

The 90-second answer

The primary commit is the source of truth, so the caller's result must depend only on that commit. A synchronous shadow write puts the new store on the request path: the caller's p99 becomes the slower of the two writes, and a shadow timeout either fails a request that already committed or forces you to pretend it succeeded. An asynchronous shadow write keeps the caller fast and correct, but a failed or dropped shadow write leaves no trace in the caller's response. Divergence then goes unnoticed unless something counts it. Ship async with a bounded retry, a durable queue or outbox behind it, and a divergence metric.

Latency arithmetic

Assume the primary write takes 8 ms at p99 and the shadow write takes 6 ms at p99, independent of each other. A synchronous shadow write in sequence gives a caller p99 of about 14 ms, and it gets worse under load because the two tails add up. A shadow timeout of 50 ms adds up to 50 ms to every request that hits the timeout path. Async keeps the caller near 8 ms, and the shadow lag becomes a separate number you monitor.

Where divergence hides

Shadow modeCaller sees a shadow failure?Divergence visible?
Sync, error propagatedYes, the order fails after the primary committedCaller retries, so the primary gets a second row
Sync, error swallowedNoOnly if you compare the stores
Async, fire and forgetNoOnly if you compare the stores
Async via outboxNoYes, the outbox backlog and retry count show it

Sync with errors propagated is the worst choice. The primary has already committed, so the caller's failure invites a retry that writes a second order. Fire-and-forget async is the one that drifts silently: a process crash between the commit and the shadow send loses the row for good.

Why the outbox closes the gap

Write the shadow intent in the same transaction as the primary row. A relay then delivers it to the new store and marks it done only after the store acknowledges. The row survives a crash, and retries are safe if the new store applies writes keyed by the primary's order id and version. The cost is one extra row written per order, plus relay lag you must alert on.

What you ship: async shadow via an outbox, the new store applying writes idempotently by version, and a periodic count-and-hash comparison per tenant. Divergence then shows up as a metric with a known source, not as a surprise after the flag goes to 100%.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-94A GC pause adds 300 ms to every request it catches. Which should you look at first to see whether it is moving p99: the pause length, or the share of requests it touches?

The 90-second answer

The share of requests touched. A 300 ms pause only moves p99 when it catches more than 1% of the requests in the measurement window. Below that line the slow requests sit in the top 1% and p99 does not see them. Above it, p99 jumps to roughly the slowed latency, so the question is how much of the window the pause covers, not how long it lasts alone.

With 10,000 requests in a window, p99 reads the 9,900th fastest value, so only 100 requests can sit above it. A pause that catches 80 requests leaves p99 where it was. One that catches 150 pushes p99 up to about 340 ms, if healthy requests run near 40 ms.

Requests caught by pauses in windowReported p99 (healthy p99 120 ms, slowed 340 ms)
80 (0.8%)120 ms
150 (1.5%)340 ms

These figures are illustrative. Check p99.9 and the count of requests over 300 ms as well, because users caught in a pause can be hurt even while p99 looks calm.

Before tuning, confirm the pauses line up with the slow requests. Pair GC log timestamps with request spans. On the JVM, -Xlog:gc*:file=gc.log:time,uptime gives the timestamps. If the slow requests do not coincide with pauses, the tail has another cause.

When pauses are the cause, tune the allocation rate and live set first, then the collector's pause target. Full collections (Pause Full in the log) are the pauses that reach hundreds of milliseconds, so check for them first.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-95Your catalog service serves one hot key at 40,000 requests per second across 60 instances, and you want a per-instance in-process cache with a 2 s TTL. What does the database see, what is the worst staleness a reader can observe, and what breaks if writers only delete from Redis?

The 90-second answer

Assume 60 instances, a 50 ms database read, and a write path that updates Postgres then deletes the Redis key. Each instance gets about 667 requests per second for the key. Without coordination, every expiry sends a burst to the database, and the local cache does nothing to bound staleness beyond its TTL. With per-key single-flight on each instance, the database sees one read per instance per TTL window. The staleness bound is not the 2 s TTL. It is the sum of every layer's age: the local TTL, the Redis TTL behind it, and the replica lag on the refresh read.

Load arithmetic

Without single-flight: during one 50 ms miss, an instance receives 667 × 0.05 ≈ 33 requests, and each of them misses. That is 60 × 33 ≈ 2,000 database reads per expiry. With a 2 s TTL that is about 1,000 reads per second, all for one row.

With single-flight: one read per instance per window, 60 / 2 = 30 reads per second.

CaseReads/s to DBWorst staleness
No cache40,0000
Local TTL 2 s, no coalescing~1,0002 s + refresh lag
Local TTL 2 s, single-flight302 s + refresh lag
Above, Redis TTL 30 s behind it30 (Redis absorbs most)2 s + 30 s + lag

Staleness is additive

A write lands at t0 just after an instance refreshed. That instance serves the old value until its TTL expires, up to 2 s. If its refresh reads a replica 300 ms behind the primary, the next window also starts from old data, so the bound becomes 2.3 s. If the refresh goes through Redis and Redis holds the key for 30 s, a delete that never reaches Redis first leaves the old value for 30 s more. The budget you publish must be the sum, and that sum is the number to defend.

Deleting from Redis does not reach local caches

A delete in Redis clears shared state only. Every instance keeps its own copy until its local TTL runs out, so the write is invisible for up to 2 s on the fast path. If the product needs read-your-write on the same instance, the write path has to invalidate local entries too, which needs a pub/sub channel or a versioned key, and that channel must be treated as best effort.

Mitigations I would ship

  • Single-flight per key per instance, so one refresh serves every waiter.
  • TTL jitter of about ±10%, so instances started together do not expire together.
  • A hard bound on entries (for example 10,000 × 2 KB ≈ 20 MB per instance) with LRU eviction.
  • A stale-while-revalidate window only for keys where the budget allows it, and a metric for served-stale age.
  • Per-key-class budgets written down, not one global TTL.

Failure to watch: if the refresh call blocks while holding the single-flight slot, every request on that instance waits for the database timeout. Put a deadline on the refresh and serve the last value past it, with the stale age exposed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-96Your batch job must sort 400 GiB of order lines on a host with 1 GiB of RAM. Explain how the number of passes over the data depends on memory and fan-in, and which of two merge buffer sizes you would pick: 8 MiB or 64 MiB per run.

The 60-second answer

External merge sort works in two phases. Run formation fills the 1 GiB of memory, sorts it and writes one run to disk, so 400 GiB produces about 400 runs and reads and writes the whole file once. The merge phase then combines k runs per pass, and each pass also reads and writes the whole file once. Fan-in k is set by memory: each input run needs a read buffer of size B, and the output needs one more buffer, so k = floor(M/B) − 1.

Bigger buffers mean fewer runs can be merged at once, which can add a merge pass. I would pick 8 MiB.

Trace with both choices

  • 8 MiB buffers: k = 128 − 1 = 127. Merge pass 1 turns 400 runs into ceil(400/127) = 4. Merge pass 2 turns 4 into 1. Total: run formation plus 2 merge passes, so 3 full sweeps, about 2,400 GiB of reads and writes combined (3 × 800 GiB).
  • 64 MiB buffers: k = 16 − 1 = 15. Merge pass 1: ceil(400/15) = 27 runs. Merge pass 2: ceil(27/15) = 2. Merge pass 3: 2 becomes 1. Total: 4 sweeps, about 3,200 GiB.
Buffer BFan-in kMerge passesFull sweeps incl. run formation
8 MiB12723
64 MiB1534

The larger buffers save some seeks, but usually not enough to pay for an extra 800 GiB of I/O.

Replacement selection changes the count

On random input, replacement selection with a heap of size M averages runs of about 2M, giving about 200 runs here. With k = 15 that still needs 2 merge passes, not 3, since 15² = 225 ≥ 200. Sorted input can yield a single run, and adversarial input gives runs of exactly M.

Failure modes

  • Output buffer forgotten. If k is computed as M/B without subtracting the output buffer, the final merge exceeds memory. Detect it with the process's peak RSS during the last pass.
  • Fan-in pushed too high. If each read buffer shrinks below a few tens of KiB, the disk spends its time seeking. Detect it from the device's average request size and queue depth, not from MB/s alone.
  • Temporary space. Each merge pass writes a full copy of the data, so the scratch volume needs about 400 GiB free while a pass runs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-97Your API allows 100 requests per second per API key across a fleet of 20 instances. Compare checking a shared Redis counter on every request with each instance keeping a local counter that syncs to Redis every second. What does each cost in latency, and how much can a key overshoot its limit under the periodic sync?

Core answer

I'd first confirm the limit is fleet-wide per key. I'll assume 100 requests/s per key, 20 instances, and that a few extra admitted requests are cheaper than a wrongly rejected customer.

Shared counter: each request runs an atomic INCR on a window key in Redis, then compares the result to the limit. Accuracy is exact within the window. The cost is one network round trip on the hot path. At about 0.5 ms round trip inside a zone, every request gains roughly 0.5 ms, and a Redis stall stalls every API call that touches the limiter.

Local counter with periodic sync: each instance counts its own requests and adds its count to the shared total every second. Added latency per request is zero, but each admission decision uses a total that is up to one second old.

Overshoot under the sync. Suppose every instance starts a window seeing only its own count, with each able to admit up to the full 100 before the next sync. Worst case is 20 × 100 = 2,000 admitted in a single second, twenty times the limit. Shrinking the sync interval shrinks that bound, but it multiplies the write load: at 1 s the cost is 20 writes/s per key, which grows with every key you track.

A cheaper fix is to split the budget: each instance gets 100 / 20 = 5 requests per second locally. Overshoot is then zero by construction. The cost is under-use. A key whose traffic lands on one instance is capped at 5 per second even though the fleet has room for 100, so skewed keys get rejected early.

ApproachAdded p50 per requestWorst overshootMain failure
Shared INCR per requestabout +0.5 msnone within windowRedis latency becomes API latency
Local counter, sync every 1 s0up to 20 × 100 = 2,000 in one secondOver-admission on hot keys
Static split, 5/s per instance0noneUnder-admission when traffic is skewed

I'd pick the shared counter for paid tiers with strict contracts and modest request volume, where one round trip is cheap. I'd pick local counting with a periodic sync for high-volume keys, accepting the overshoot bound and sizing it to what the contract tolerates.

Failure behaviour matters too. If Redis is down, failing closed rejects every request for the key, and failing open lets a hot key reach the database unthrottled. I'd drop to the static split during an outage, so both directions stay bounded. To detect problems I'd watch the 429 rate per key against expected traffic, Redis p99 on the limiter path, and the fraction of keys whose instances hit their local cap while the fleet total stays low. That last signal means the split is starving skewed keys.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-98How many seconds are in a day, and what does that number let you do when converting a daily request count into average QPS?

The 30-second answer

A day has 86,400 seconds (24 x 60 x 60). To get average QPS, divide the daily request count by 86,400. That is the only conversion you need for the average; everything else is a planning multiple applied afterwards.

Worked example (hypothetical figures)

Assume 200,000,000 requests in a day.

QuantityArithmeticResult
Average QPS200,000,000 / 86,400about 2,315

The average is the fleet's bill, not its capacity. Size the fleet for peak, which for a consumer API is usually a few times the average, and confirm that multiple against your own traffic graph.

Why the average alone is not enough

At 2,315 QPS and 200 ms mean latency, Little's law gives about 463 requests in flight (QPS x mean latency). A fleet sized only to that number saturates during busy hours, and p99 climbs before CPU looks high.

Failure modes to name

  • Daily averages hide the busy hour. Traffic is rarely flat across a day.
  • Fan-out multiplies QPS. One user action that triggers five backend calls is five times the load on each backend, so count per backend.

If an interviewer asks for more, ask for the busiest minute from last month and divide it by the average to get the real peak factor.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-99Your checkout path has three layers that each retry on 503: an edge gateway, the checkout API, and a payment client. During a payment partner brownout, how many calls can reach the partner per user request, and where would you cap retries so the partner stops getting multiplied load?

The 90-second answer

Retries multiply across hops. If each layer makes 3 attempts (one try plus 2 retries) and every layer retries the same failure, one user request becomes 3 × 3 × 3 = 27 calls to the partner. The fix is to give each dependency exactly one layer that owns retries, and to put a budget at the edge so the total extra load is bounded no matter how many layers exist.

Assumptions: a 100% failure rate at the partner during the brownout, retries only on 503 and connection reset, and no retries on 4xx.

LayerAttempts per callCalls into next layer during outage
Edge gateway33
Checkout API39
Payment client327

Hypothetical figures: at 2,000 user requests/s, the partner sees 54,000 requests/s instead of 2,000. That is the outage getting worse because of your retries.

What I would ship

  1. Retries live at one layer only. The payment client is the layer that knows the error and the idempotency key, so it owns the retries. The gateway and checkout API pass the request through with retries disabled for that route.

  2. A retry budget at the edge. Envoy's retry_budget with budget_percent 20 and min_retry_concurrency 3 caps retries at 20% of active requests, above a floor of 3 concurrent retries. Under the same full outage, extra load is roughly 1.2×, not 27×. Check the field names and defaults against the Envoy version you run.

  3. Propagate the attempt number. Envoy sets x-envoy-attempt-count on retried requests. Downstream services can refuse further retries when the count is high or when the remaining deadline is shorter than one attempt. gRPC's retry throttling does a similar job with a token bucket per channel: each failure removes a token, each success adds tokenRatio, and retries stop when tokens fall to half of maxTokens.

Non-idempotent POST

A retried POST without an idempotency key can charge the customer twice. Keys make retries safe, but they do nothing about load. The budget and single-owner rule do the capping.

Failure modes and detection

  • Hidden retries: a mesh retry policy plus an application client retry policy on the same call. Detect it by comparing request counts at each ingress and egress. A ratio above your design number (here 1.0 per hop) means someone else is retrying.
  • Retrying errors that cannot succeed: a 503 after the deadline is spent. Check remaining budget before every attempt.
  • Retry storms that look like traffic growth: downstream RPS rising while upstream RPS is flat. Alert on that divergence.

When you cannot tell which layer retried, you have a multiplier you cannot cap. Fix that before tuning any backoff numbers.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-100Your config loader builds a singleton lazily with double-checked locking. Why must the instance field be volatile in Java, and what can another thread observe if it is not?

The 60-second answer

The unsynchronized first read is a data race unless the field is volatile. Without it, the Java Memory Model allows another thread to see a non-null instance before the constructor's writes to the object's fields are visible, so it can run against a half-built object. volatile makes the reference store a release and the reference load an acquire. Anything written before the assignment is then visible to any thread that reads the non-null reference.

Java
public final class Config {
    private static volatile Config instance;
    private final Map<String, String> values;

    private Config() { values = loadFromDisk(); }

    public static Config get() {
        Config local = instance;          // one volatile read on the fast path
        if (local == null) {
            synchronized (Config.class) {
                local = instance;
                if (local == null) {
                    local = new Config();
                    instance = local;     // volatile write publishes the constructed object
                }
            }
        }
        return local;
    }
}

The second check inside the lock is what makes this work. The first check avoids the lock once the instance exists, and the re-check stops two threads that both passed the first check from building two instances.

Trace without volatile

StepThread T1 (in the lock)Thread T2 (fast path)
1allocates Config, fields still zero
2stores values
3stores instance, which the JIT may move ahead of step 2
4reads instance, non-null, returns without locking
5reads values, sees null, throws NPE later

With volatile, the write in step 3 cannot move before step 2, and T2's volatile read in step 4 synchronises with it. Step 5 then sees the map.

Why final alone does not save you

JSR-133 gives final fields a freeze at the end of the constructor, so a reader sees their values even when the reference is published racily. That only holds if this does not escape the constructor, and it covers only final fields. A mutable non-final field still needs volatile, a lock, or a happens-before edge from somewhere else.

Alternatives and their costs

ApproachLazyFast-path costUse when
volatile DCLyesone volatile read per callconstruction needs runtime arguments or can fail and retry
holder class idiomyesnone after class initialisationno arguments needed
enum singletonnononethe singleton must be serialisation-safe
eager static finalnononeconstruction is cheap and always needed

I would reach for the holder idiom first, because the JVM's class initialisation lock already gives the happens-before edge. Volatile DCL earns its place only when the constructor needs arguments.

Failure modes

The dangerous part is that a missing volatile compiles, passes unit tests, and often passes on x86, where the hardware does not reorder stores with other stores. The JIT can still reorder them, and ARM hardware reorders them too. The symptom is an intermittent NPE or a field reading its default value, appearing under load on a specific architecture. Detect it with a jcstress test that publishes the object across threads, or by searching production logs for NPEs on fields that are assigned in the constructor.

The other cost is the lock. If the constructor does I/O, every first caller queues behind the same monitor for the full load time. Measure lock hold time on Config.class before choosing this pattern for anything with slow initialisation.

Curated: · Written: · Reviewed:

Difficulty: Medium