Skip to content
Tech Interview Prep

Real Interview Questions for the Backend Software Engineer at Stone

New

Interview Q&A

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

Q&A-1Design the backend architecture for a payment gateway, ensuring transaction consistency and handling network timeouts gracefully?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would split the gateway into an edge layer, a core ledger service, and adapters to payment service providers (PSPs) or acquirers. The edge layer authenticates merchants, validates requests, and enforces idempotency. The core owns a double-entry ledger and a payment state machine in one database. Adapters translate to each PSP and absorb its quirks, including webhooks and status queries.

The central rule: a network timeout never means the payment failed. It means the outcome is unknown. The gateway therefore never retries a charge with a new reference. It retries with the same idempotency key and PSP reference, then asks the PSP for the status before deciding.

Merchant API Edge: auth, validation, idempotency Core: ledger + state machine Outbox publisher PSP adapter PSP or acquirer Webhook handler

Consistency inside the gateway

Money movement is recorded as balanced entries. A capture of R$100.00 debits the merchant settlement account and credits the PSP clearing account, or the reverse depending on your chart of accounts. The sum of entries per transaction must be zero, enforced by a database check and a unique constraint on (payment_id, entry_type).

State transitions and ledger entries commit in one local transaction. An outbox row commits in that same transaction, so a crash after commit cannot lose the event that tells the adapter to call the PSP. A separate publisher drains the outbox and marks rows sent only after the PSP call is accepted.

Python
# Python 3.12, psycopg 3. One transaction: state, ledger, outbox.
def capture(conn, payment_id, idem_key):
    with conn.transaction():
        cur = conn.execute(
            "SELECT status FROM payments WHERE id = %s FOR UPDATE", (payment_id,))
        status = cur.fetchone()[0]
        if status != "AUTHORIZED":
            return status  # already captured or failed; replay, do not re-post
        conn.execute(
            "UPDATE payments SET status='CAPTURED', version=version+1 WHERE id=%s", (payment_id,))
        conn.execute(
            "INSERT INTO ledger_entries(payment_id, account, amount_cents) VALUES "
            "(%s,'psp_clearing',-10000), (%s,'merchant_settlement',10000)",
            (payment_id, payment_id))
        conn.execute(
            "INSERT INTO outbox(payment_id, event, idem_key) VALUES (%s,'capture',%s)",
            (payment_id, idem_key))

I would not use two-phase commit across the PSP. The PSP is outside my transaction boundary and cannot roll back on my command. The pattern is a saga with compensation: authorize, capture, settle, and if a later step fails, post a reversing entry and move the payment to a terminal failed state. Each step is idempotent, so replaying it is safe.

Timeouts: the unknown-outcome problem

Set explicit budgets. Suppose the merchant-facing deadline is 5 seconds. The gateway reserves 500 ms for edge processing and gives the PSP adapter a 3 second read timeout, with 1 second connect timeout. If the PSP does not answer in 3 seconds, the payment moves to UNKNOWN, not FAILED. The API returns 202 with status: unknown and a payment_id the merchant can poll.

A reconciliation worker then queries the PSP by its reference, for example psp_ref = gw_9f31..., with exponential backoff: 5 seconds, 30 seconds, 2 minutes, 10 minutes. Webhooks can resolve the payment sooner, but they are treated as hints until the status query or a signed webhook confirms the final state. Webhook handlers verify the PSP signature, store the raw payload, and apply the transition through the same state machine, so a replayed webhook is a no-op.

TimeEventGateway stateAction
0.0 sMerchant sends POST /payments with Idempotency-Key: k1CREATEDInsert payment and ledger hold in one transaction
0.4 sAdapter calls PSP with reference gw_9f31AUTHORIZED pendingWait for PSP response
3.4 sPSP read timeoutUNKNOWNReturn 202, start reconciliation
4.1 sSigned webhook arrives: authorizedAUTHORIZEDApply transition, publish event
4.2 sMerchant retries with same k1AUTHORIZEDReplay stored response, no second PSP call

Retries and failure modes

Retries use the same idempotency key, capped backoff with jitter, and a circuit breaker per PSP. If a PSP times out on 20% of calls over a 1 minute window, the breaker opens for 30 seconds and new captures queue or fail fast with 503 and Retry-After, rather than piling up threads. A concrete load figure helps size this: at 1,000 requests per second with a 5% timeout rate, blind retries would add 50 extra PSP calls per second and could double that during a PSP slowdown. Status queries are cheaper and safer than new charges, so the retry budget goes there first.

Three failure modes I would name in the loop. First, the database commits but the response is lost, so the merchant retries. The idempotency store, kept for at least 24 hours and ideally 7 days for payments, returns the original payment_id and response. Second, the PSP captures but its webhook is delayed by hours. Reconciliation by reference catches it, and a daily settlement report comparison catches anything reconciliation missed. Third, two gateway instances race to capture the same payment. The SELECT ... FOR UPDATE on the payment row plus the unique ledger constraint serializes them, and the loser replays the winner's state.

What I would not do

I would not mark a timed-out payment as failed and let the merchant create a new one, because that is how duplicate debits happen. I would not hold a database transaction open while calling the PSP, because a slow PSP would exhaust the connection pool. And I would not treat a webhook as the only source of truth, because webhooks are delayed, duplicated, and occasionally forged if signature checks are skipped.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2Given an array of integers, find the contiguous subarray which has the largest sum and return its sum?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

Assuming a non-empty array and that the subarray must contain at least one element, Kadane's algorithm solves this in one pass. Keep the best sum ending at the current position and the best sum seen anywhere so far. At each element, either extend the previous run or restart at that element, whichever is larger.

Python
def max_subarray_sum(nums):
    if not nums:
        raise ValueError("array must be non-empty")
    best = current = nums[0]
    for x in nums[1:]:
        current = max(x, current + x)
        best = max(best, current)
    return best

Initialising both values to nums[0], rather than to 0, is what makes the all-negative case work. For [-3, -1, -2] the answer is -1, the least negative single element. Initialising to 0 would incorrectly return 0 by implicitly allowing an empty subarray.

Worked trace

For [-2, 1, -3, 4, -1, 2, 1, -5, 4]:

ixcurrentbest
0-2-2-2
1111
2-3-21
3444
4-134
5255
6166
7-516
8456

The answer is 6, from [4, -1, 2, 1]. At index 2 the running sum drops to -2, so restarting at 4 beats extending it. That local decision is safe because any subarray ending at index 3 that started earlier would include that negative prefix and sum to less than starting fresh.

Why this over the alternatives

ApproachTimeExtra spaceWhen it is the right choice
Brute force, check every start and endO(n^2)O(1)Only for tiny inputs or as a test oracle
Divide and conquer on the midpointO(n log n)O(log n) stackWhen you need a parallel or external-memory variant
KadaneO(n)O(1)Default for a single in-memory array

For n = 1,000,000, brute force examines roughly 5 x 10^11 pairs. Kadane touches each element once. Divide and conquer is correct but does more work and is harder to get right at the crossing subarray, which is the part interviewers probe.

Failure modes to name before they ask

Empty input: the problem as stated has no valid subarray, so raising or returning a sentinel is a contract decision. I would raise in a library function and document it, rather than silently returning 0, which collides with a legitimate answer.

Overflow: in Java or C++ with 32-bit int, an array of values near 2 x 10^9 overflows before the comparison happens. Use long or long long for the accumulators. Python integers do not overflow, which is worth stating if the interview is in Python.

If they follow up and ask for the subarray itself, track the start index alongside current. When current restarts at x, record the current index as the start. When current exceeds best, record the pair (start, i). That adds O(1) state and does not change the complexity.

If they ask about a stream that never ends, Kadane still applies element by element, but best becomes a running maximum that can only grow. That is usually a sign the real question is about a sliding window with a length constraint, which needs a deque over prefix sums instead.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-3Write a function to determine if a string has all unique characters, optimizing for both time and space complexity?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

Clarify the alphabet and the definition of a character first, because that decides the space bound. For a Python str (Unicode code points) or a Java String (UTF-16 code units, so a surrogate pair is two units), the straightforward answer is a single pass with a set: O(n) time, O(k) extra space where k is the number of distinct characters seen, and early exit on the first repeat. If the input is known to be ASCII, a 128-bit mask gives O(n) time and O(1) extra space.

Python
# Python 3.12
def has_unique(s: str) -> bool:
    seen: set[str] = set()
    for ch in s:
        if ch in seen:
            return False
        seen.add(ch)
    return True

def has_unique_ascii(s: str) -> bool:
    # Caller guarantees all ord(ch) < 128. Two 64-bit words cover 128 bits.
    lo = hi = 0
    for ch in s:
        o = ord(ch)
        if o < 64:
            bit = 1 << o
            if lo & bit:
                return False
            lo |= bit
        else:
            bit = 1 << (o - 64)
            if hi & bit:
                return False
            hi |= bit
    return True

Worked trace for has_unique("abca")

Stepchseen beforeActionResult
1a{}add acontinue
2b{a}add bcontinue
3c{a, b}add ccontinue
4a{a, b, c}a already presentreturn False

The early exit matters in practice. A string that repeats at position 4 costs four steps, not n. On a long log line or a payload field, that is the difference between scanning the whole input and stopping at the first duplicate.

Alternatives and when to pick them

ApproachTimeExtra spaceTrade-off
Set / hash setO(n) averageO(k)Simple, handles full Unicode, worst case O(n^2) under hash collisions
Bitmask (ASCII)O(n)O(1), 16 bytesFastest and smallest, only valid for a bounded alphabet
Sort a copy, then scan neighboursO(n log n)O(n) for the copyNo hash table, but slower and copies the input
Brute force, compare every pairO(n^2)O(1)Only defensible for tiny fixed inputs

Sorting in place would give O(n log n) time and O(1) extra space, but it mutates the caller's data. For a backend service that receives a string from a request body, mutating it is a side effect the caller did not ask for, so I would not offer that as the default.

Failure modes to name in the interview

Case and normalisation change the answer. "Aa" has unique characters under a case-sensitive check and a duplicate under a case-insensitive one. "é" written as a single code point (U+00E9) and as e plus a combining accent (U+0065 U+0301) look identical on screen but are different code points, so the set version reports them as distinct. If the business rule is about user-visible characters, normalise with NFC (unicodedata.normalize("NFC", s)) before checking, and say so.

Empty string returns True (vacuously unique). That is the mathematically consistent choice, but some specifications expect False for empty input, so state the assumption rather than letting the interviewer guess.

For very large inputs, the set grows to O(k) entries. If the alphabet is bounded, the bitmask version caps memory at 16 bytes regardless of input length, which is why I would reach for it for ASCII identifiers, tokens, or codes in a payment service where the format is already constrained. For arbitrary Unicode text, the set is the honest answer and O(k) is the price of correctness.

If asked to optimise further, the next step is not a cleverer algorithm. It is to ask whether the check runs on a hot path, how large n realistically gets, and whether a Bloom filter or a precomputed constraint at write time would remove the need to check at read time at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4Implement a basic rate limiter for an API endpoint using an algorithm of your choice?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would use a token bucket per API key. It allows short bursts, which real clients need, and it refills at a steady rate, which protects the endpoint over time. For a single instance I keep buckets in memory. For multiple instances I move the same logic into Redis with a Lua script so the check and the decrement happen atomically.

Assumptions I would state first: limit is 100 requests per minute per API key, burst is 20, and excess requests get 429 with Retry-After. If the interviewer wants a global limit instead of per key, the key changes and the algorithm does not.

Single instance implementation

Python
import time
import threading

class TokenBucket:
    def __init__(self, capacity: int, refill_per_second: float):
        self.capacity = capacity
        self.refill_per_second = refill_per_second
        self.tokens = float(capacity)
        self.updated_at = time.monotonic()
        self.lock = threading.Lock()

    def allow(self) -> tuple[bool, float]:
        with self.lock:
            now = time.monotonic()
            elapsed = now - self.updated_at
            self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_second)
            self.updated_at = now
            if self.tokens >= 1.0:
                self.tokens -= 1.0
                return True, 0.0
            wait = (1.0 - self.tokens) / self.refill_per_second
            return False, wait

buckets: dict[str, TokenBucket] = {}
buckets_lock = threading.Lock()

def get_bucket(api_key: str) -> TokenBucket:
    with buckets_lock:
        if api_key not in buckets:
            buckets[api_key] = TokenBucket(capacity=20, refill_per_second=100 / 60)
        return buckets[api_key]

def handle_request(api_key: str):
    allowed, wait = get_bucket(api_key).allow()
    if allowed:
        return 200, {}
    return 429, {"Retry-After": str(max(1, round(wait)))}

Refill is lazy. No background thread wakes up to add tokens. Each call computes elapsed time since the last call for that key, so idle keys cost nothing until they return.

Worked trace

Capacity 20, refill 100 per minute, so 1.67 tokens per second. One key sends 25 requests in the same second.

RequestTokens beforeDecisionTokens after
120.0allow19.0
192.0allow1.0
201.0allow0.0
210.0reject, wait about 0.6 s0.0
250.0reject0.0
after 6 s idle10.0allow9.0

That burst behaviour is the main reason to pick token bucket over a fixed window. A fixed window resets all 100 at the minute boundary, so a client can send 100 at 12:00:59 and another 100 at 12:01:00. Token bucket smooths that edge.

Comparison with alternatives

AlgorithmBurstMemory per keyMain weakness
Token bucketYes, up to capacityTwo numbersNeeds atomic update when distributed
Fixed window counterNo, resets at boundaryOne counter plus window startDouble burst at window edge
Sliding window logNoOne timestamp per requestMemory grows with limit, 100 timestamps per key here

Sliding window log is the most accurate and the easiest to explain, but at 10,000 active keys and 100 requests each it stores a million timestamps. Token bucket stores two floats per key.

Distributed version

With three app instances behind a load balancer, in-memory buckets diverge. One client can get 20 tokens from each instance. The fix is a Redis hash per key holding tokens and updated_at, updated by a Lua script. The script refills, checks, decrements and sets a TTL of 120 seconds in one atomic step, so two concurrent requests cannot both spend the last token. The TTL also solves the memory leak in the in-memory version, where buckets grows forever if keys are never deleted. In production I would add periodic cleanup or rely on that TTL.

LUA
-- KEYS[1] = rate:key:<api_key>, ARGV = capacity, refill_per_second, now_ms
local data = redis.call('HMGET', KEYS[1], 'tokens', 'updated_at')
local tokens = tonumber(data[1]) or tonumber(ARGV[1])
local updated = tonumber(data[2]) or tonumber(ARGV[3])
local elapsed = math.max(0, (tonumber(ARGV[3]) - updated) / 1000)
tokens = math.min(tonumber(ARGV[1]), tokens + elapsed * tonumber(ARGV[2]))
local allowed = 0
if tokens >= 1 then tokens = tokens - 1 allowed = 1 end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'updated_at', ARGV[3])
redis.call('EXPIRE', KEYS[1], 120)
return {allowed, tokens}

Failure modes I would name

Redis down: fail open or fail closed is a product decision. Fail open keeps the API up and risks overload. Fail closed protects the backend and returns 503 for everyone. I would fail open for read endpoints and fail closed for expensive writes, and I would alert on Redis errors rather than silently degrading.

Clock skew: time.monotonic() avoids wall clock jumps on a single host. In Redis I pass the app server time in milliseconds, so skew between app servers can grant or deny a few extra requests. Using Redis TIME inside the script removes that, at the cost of a slightly more complex script.

Response contract: every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset. Rejected requests add Retry-After. Clients that ignore Retry-After and retry immediately will keep hitting 429, so the header matters as much as the status code.

I would test with a script that fires 200 concurrent requests at one key and asserts exactly 20 succeed, then waits 12 seconds and asserts about 20 more succeed. That test catches race conditions in the lock and in the Lua script before load does.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5Reverse a linked list iteratively and recursively, explaining the trade-offs of each approach?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

Assume a singly linked, acyclic list and reverse it in place, returning the new head. Iterative version keeps three pointers and rewires each next once: O(n) time, O(1) extra space. Recursive version reverses the tail first, then fixes the link back to the current node: O(n) time, O(n) stack space. For a backend interview I would write the iterative version by default, because recursion depth is the failure mode that matters at scale.

Python
# Python 3.12, singly linked list
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_iterative(head):
    prev, curr = None, head
    while curr is not None:
        nxt = curr.next      # save before rewiring
        curr.next = prev
        prev, curr = curr, nxt
    return prev

def reverse_recursive(head):
    if head is None or head.next is None:
        return head
    new_head = reverse_recursive(head.next)
    head.next.next = head    # tail now points back
    head.next = None
    return new_head

Worked trace, iterative, on 1 -> 2 -> 3 -> 4

StepprevcurrnxtAfter curr.next = prev
1None121 -> None
21232 -> 1 -> None
32343 -> 2 -> 1 -> None
434None4 -> 3 -> 2 -> 1 -> None
54None-return prev = 4

The invariant is that everything at or before prev is already reversed and terminated by None, and curr is the first node not yet processed. Saving nxt before the assignment is the only line that can be dropped by accident, and dropping it loses the rest of the list.

Trade-offs

IterativeRecursive
TimeO(n), one passO(n), one pass
Extra spaceO(1), three pointersO(n) call stack
Depth limitBounded by heapPython default recursion limit is 1000, so a list of a few thousand nodes raises RecursionError. JVM stacks overflow similarly, well before the heap is exhausted.
Tail calln/aNeither CPython nor the JVM optimises this tail shape, so depth grows linearly regardless.
ReadabilitySlightly more bookkeepingCloser to the definition: reverse the rest, then attach the head

That depth limit is the practical difference. A linked structure parsed from a long chain, a tree flattened into a list, or a log stream can easily reach 100,000 nodes. The iterative loop handles that with the same three pointers. The recursive version fails deterministically at a depth set by the runtime, not by available memory, which makes it a poor default in production code.

Failure modes to name if asked

A cycle breaks both versions. Iterative loops forever, recursive overflows the stack. If the input comes from untrusted data, detect a cycle first with Floyd's tortoise and hare, O(n) time and O(1) space, or bound the traversal. A second trap is forgetting to update the caller's head reference: reversing in place changes the first node, so the function must return the new head and the caller must assign it. Returning the old head gives a list whose first node points to None and whose remaining nodes are detached.

In real backend work you would rarely reverse a linked list at all, since arrays and database cursors cover most cases. The interview point is pointer discipline, the space cost of recursion, and knowing which version survives a long input.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6Explain how you would implement a queue using two stacks?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

Use two stacks, inbox and outbox. enqueue always pushes onto inbox. dequeue pops from outbox, and only refills outbox when it is empty, by popping everything from inbox and pushing it onto outbox. That reversal is the whole trick. The first element pushed onto inbox ends up on top of outbox after the transfer, so it leaves first. FIFO from two LIFO structures.

Python
# Python 3.12, single-threaded version
class QueueUsingStacks:
    def __init__(self):
        self.inbox = []
        self.outbox = []

    def enqueue(self, item):
        self.inbox.append(item)

    def dequeue(self):
        if not self.outbox:
            if not self.inbox:
                raise IndexError("dequeue from empty queue")
            while self.inbox:
                self.outbox.append(self.inbox.pop())
        return self.outbox.pop()

    def peek(self):
        if not self.outbox:
            if not self.inbox:
                raise IndexError("peek at empty queue")
            while self.inbox:
                self.outbox.append(self.inbox.pop())
        return self.outbox[-1]

    def __len__(self):
        return len(self.inbox) + len(self.outbox)

Worked trace

Callinbox (top at right)outbox (top at right)Returns
enqueue(1)[1][]
enqueue(2)[1, 2][]
enqueue(3)[1, 2, 3][]
dequeue()[][3, 2]1
enqueue(4)[4][3, 2]
dequeue()[4][3]2
dequeue()[4][]3
dequeue()[][]4

The last dequeue triggers a second transfer of a single element. That is expected. Transfers happen only on an empty outbox, never on every call.

Why it is O(1) amortized

Each element is pushed onto inbox once, popped from inbox once, pushed onto outbox once, and popped from outbox once. Four stack operations per element over its lifetime, so n enqueues and n dequeues cost at most 4n operations. Amortized cost per operation is O(1). A single dequeue that triggers a transfer of k elements costs O(k), so worst case latency is not bounded. For k = 1,000,000 buffered payment jobs, one call does a million pops and pushes while the request thread waits.

OperationAmortizedWorst case for one call
enqueueO(1)O(1)
dequeue / peekO(1)O(n), when outbox is empty
SpaceO(n)O(n), two stacks hold every queued item

Where this breaks in a backend service

This structure is an interview answer, not a production queue. Three concrete problems show up first.

  1. Thread safety. The code above is not safe under concurrent producers and consumers. Two threads can both see an empty outbox and both transfer, corrupting order. Guard both stacks with one lock and the transfer becomes a long critical section. In Java I would reach for ConcurrentLinkedQueue, in Python for queue.Queue, and for anything crossing a process boundary, a broker such as RabbitMQ or SQS, where durability and redelivery matter more than in-memory ordering.
  2. Unbounded growth. Nothing here applies backpressure. A fast producer and a slow consumer grow both lists until the heap is exhausted. A real design caps the buffer and blocks or rejects the producer at the cap.
  3. No random access or cheap iteration. You cannot index the middle element or scan the queue without draining it. If a worker pool needs to inspect pending jobs by priority, this representation fights you.

If an interviewer pushes on alternatives, the honest comparison is a circular buffer or a linked list with head and tail pointers, both giving true O(1) worst case dequeue, at the cost of more code and, for the linked list, pointer chasing. Two stacks win only on simplicity and on reusing a stack you already have.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7Design a URL shortener service like Bitly, focusing on high-read throughput and database selection?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

A shortener is a write-light, read-heavy key-value store. Writes are POST /shorten with a long URL, reads are GET /{code} returning 301 or 302 to the long URL. That asymmetry drives everything: optimise the read path for cache hits and low tail latency, keep the write path simple and strongly consistent on code uniqueness.

I would start with PostgreSQL as the system of record and Redis in front of it, plus a CDN or edge cache for hot codes. PostgreSQL gives us a unique constraint on code, transactions for expiry and ownership, and SQL for analytics without running a second database on day one. If read volume outgrows what Postgres read replicas plus Redis can serve, the lookup table (code -> long_url, expires_at) ports cleanly to DynamoDB or Cassandra because access is a single-partition-key get. I would not start there. The operational cost and weaker ad hoc query story are hard to justify until scale forces it.

miss miss create Client CDN / edge cache API tier, stateless Redis cache-aside PostgreSQL primary + replicas

Code generation

Use a database sequence or a preallocated counter block, encoded in base62, rather than hashing the URL. Hashing collides and needs a collision table. A counter is unique by construction and short. At 62^7 codes you get about 3.5 trillion codes, so 7 characters is plenty. Preallocate blocks of, say, 10,000 IDs per API instance to avoid a database round trip per create, and persist the block range so a crash does not reuse IDs.

Python
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

def encode(n: int) -> str:
    if n == 0:
        return ALPHABET[0]
    out = ''
    while n:
        n, r = divmod(n, 62)
        out = ALPHABET[r] + out
    return out.rjust(7, ALPHABET[0])

# encode(62**7 - 1) == 'zzzzzzz', encode(1) == '0000001'

Schema is deliberately boring:

SQL
CREATE TABLE urls (
  code       TEXT PRIMARY KEY,
  long_url   TEXT NOT NULL,
  owner_id   TEXT,
  expires_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

The primary key is the lookup. No joins on the read path.

Read path and the numbers

Assume 100 million URLs and 10,000 redirects per second at peak, a 1000:1 read to write ratio. That is 10 writes per second, trivial for Postgres. Reads are the problem. With Redis cache-aside and a 95% hit rate on hot codes, which Zipfian traffic usually gives you, the database sees about 500 reads per second. Two read replicas handle that comfortably. Cache entries carry the same TTL as expires_at so an expired link stops redirecting without a database check on every hit. Negative caching matters too: cache 404s for a short period, or a scanner hitting random codes becomes a database denial of service.

Redirect choice: 301 lets browsers and CDNs cache aggressively, which is great for read throughput and bad if you need accurate click counts or the ability to change the target. 302 keeps control server side and costs you cacheability. I would default to 302 for a general service and offer 301 as an explicit opt-in per link, and say that trade-off out loud in the interview.

OptionFit for this workloadWhen I would pick it
PostgreSQL + RedisSingle-key lookup, unique constraint, analytics, expiry jobsDefault start, up to roughly low tens of thousands of reads per second per region
DynamoDB on-demandSingle-digit ms p99, no replica management, global tablesMulti-region active-active reads are a hard requirement
CassandraLinear write scale across regionsSustained write volume far beyond this workload, team already runs it

Failure modes I would name

Cache stampede when a viral code expires: use request coalescing or a short lock so one request rebuilds the entry while others wait briefly. Hot partition if you move to a hash-partitioned store: codes are random from the counter, so distribution is even, unlike user IDs. Clock skew on expiry: store expires_at in UTC and compare server side, never trust the client. Abuse: rate limit POST /shorten, validate and length-cap URLs, block known phishing domains, because a shortener is an open redirect factory otherwise. Analytics writes must not block redirects: emit click events to a queue and write them asynchronously, or your p99 redirect latency inherits your analytics pipeline.

Follow-up I expect: how do you scale past one region. Answer is read replicas and edge caching first, then a globally replicated key-value store for the code -> long_url table only, keeping Postgres for ownership and billing data that does not need global reads.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8How would you architect a real-time notification system that handles millions of push notifications and SMS messages daily?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would split this into ingest, routing, and delivery, with a durable log between each stage so a crash never loses a notification. Producers publish an event to an ingest API, the API writes it to Kafka and returns 202, and workers consume it, resolve the user's channel preferences and device tokens, then call a push provider (FCM or APNs) or an SMS aggregator (Twilio, Infobip, or a local carrier gateway). Delivery receipts come back on a separate topic and update a status store the product can query.

Assumptions I would state up front: 5 million notifications a day, roughly 70% push and 30% SMS, peak traffic 8 times the daily average, and a target of p95 under 5 seconds for push and under 30 seconds for SMS submission. SMS is best effort because carrier queues sit outside our control.

The arithmetic sets the scale. 5,000,000 / 86,400 is about 58 messages per second on average, about 460 per second at peak, and I would design for 2,000 per second to absorb a burst after an outage or a marketing send. At 1.5 million SMS a day and, say, $0.04 per message in Brazil, that is about $60,000 a day, which is why routing matters: never send SMS when push will reach the user.

Producer: order, payment, fraud events Ingest API Kafka: notifications.raw Router: preferences, tokens, quiet hours Push workers: FCM / APNs SMS workers: aggregator Receipts topic Status store: Postgres

Routing and storage

Partition Kafka by user_id so messages for one user stay ordered, which matters for a sequence like "payment approved" followed by "payment settled". Global ordering is unnecessary and expensive. The router reads two stores: a token registry (user_id, platform, token, last_seen) in Postgres with Redis as a cache, and a preference table holding push enabled, SMS enabled, locale, and quiet hours. If the token is older than 90 days or FCM returns NotRegistered, mark it dead and fall back to SMS only if the user opted in.

DecisionPushSMS
Typical latency1 to 5 s5 to 30 s submission, carrier dependent
Cost per messageNear zero at volume$0.02 to $0.08 depending on carrier and country
Throughput limitProvider quota, usually highAggregator throughput tier, often 100 to 1,000 msg/s per sender ID
Failure signalInvalid token, throttling 429Carrier DLR codes, handset unreachable
ReachOnly app installed and notifications allowedAny mobile number, subject to opt-out

Idempotency and dedup

Retries are guaranteed at every hop, so every send needs a stable key. The producer supplies event_id, and the worker checks a dedup table before calling the provider.

Python
# Python 3.12, worker side. dedup table has a unique index on event_id.
import psycopg

def send_push(conn, event):
    with conn.transaction():
        cur = conn.execute(
            "INSERT INTO notification_sends (event_id, user_id, channel) "
            "VALUES (%s, %s, 'push') ON CONFLICT (event_id) DO NOTHING "
            "RETURNING id",
            (event["event_id"], event["user_id"]),
        )
        row = cur.fetchone()
        if row is None:
            return "duplicate"  # already sent or in flight, ack the Kafka record
        provider.send(event["token"], event["title"], event["body"],
                      idempotency_key=event["event_id"])
        return "sent"

If the worker crashes after the provider call but before the commit, the retry hits the unique index and skips. If the provider supports an idempotency key, as Twilio and FCM do in different forms, pass it so a retry on their side also collapses.

Failure modes I would name in the loop

SMS aggregator throttling: watch for 429 and carrier DLR backlog, shed load by deferring low priority templates (marketing) and keeping transactional ones (fraud alert, payment confirmation) in a priority queue. A dead letter queue with the raw payload, error code, and retry count, plus an alert when DLQ depth passes 1,000, catches poison messages.

Opt-out race: a user sends STOP while a message is queued. Check preferences at send time, not at ingest time, and re-check on retry. For SMS in Brazil and the US, STOP handling and template registration are compliance requirements, not nice to have, and LGPD consent records should be stored with the preference row.

Backlog after an outage: consumer lag per partition is the signal. Autoscale workers on lag, and cap retries with exponential backoff plus jitter, for example 30 s, 2 min, 10 min, then DLQ. Unbounded retries turn a provider outage into a self-inflicted flood when it recovers.

Duplicate delivery from receipt loss: receipts arrive late or not at all, so the status store should treat "submitted" and "delivered" as separate states and never resend just because a receipt is missing after 24 hours. Reconcile daily against the provider's delivery report instead.

That gives a system that scales horizontally on Kafka partitions, keeps SMS spend down by preferring push, and degrades by priority instead of dropping fraud alerts first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9How would you structure a chat application's backend to support offline messaging and synchronization?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would treat the server as the single ordering authority and the client as an outbox. Every message gets a client-generated client_msg_id (a UUID) before it is sent. The server appends it to a per-conversation log, assigns a monotonically increasing seq inside that conversation, and only then acknowledges it. Offline clients keep sending into a local outbox, and on reconnect they push pending messages and pull everything after the last seq they have seen. That gives at-least-once delivery with exactly-once effect, because the server deduplicates on client_msg_id.

Client outbox API: POST /messages Postgres: messages table Assign per-conversation seq Commit, then publish WebSocket fan-out Online recipients Offline client reconnect GET /sync?since_seq=N

Data model and write path

One append-only table, partitioned by month, with a unique constraint that does the deduplication work:

SQL
CREATE TABLE messages (
  conversation_id BIGINT NOT NULL,
  seq             BIGINT NOT NULL,
  client_msg_id   UUID NOT NULL,
  sender_id       BIGINT NOT NULL,
  body            TEXT NOT NULL,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  edited_at       TIMESTAMPTZ,
  deleted_at      TIMESTAMPTZ,
  PRIMARY KEY (conversation_id, seq),
  UNIQUE (conversation_id, client_msg_id)
);

The write handler runs in one transaction: insert with the client-supplied ID, let the unique constraint reject a retry, and on conflict return the row that already exists. Sequence assignment needs care. MAX(seq)+1 races under concurrency, so I would use a per-conversation counter row updated with SELECT ... FOR UPDATE, or a Postgres advisory lock keyed by conversation_id. At Stone scale for a chat feature, that lock is held for milliseconds and keeps seq gapless enough for sync. Gaps are tolerable if the client treats seq as a high-water mark only after a contiguous pull, but a counter row makes the trace below clean.

Publish after commit, never before. If I published first and the transaction rolled back, recipients would see a message that sync would never return. After commit, push the row to a Redis pub/sub channel per conversation, and have WebSocket gateway instances fan out to connected sockets. Redis is a transport here, not storage. If a gateway dies, the message is still in Postgres and the client will pull it.

Sync protocol

Two endpoints, deliberately boring:

EndpointPurposeKey detail
POST /conversations/{id}/messagesSendBody carries client_msg_id; response returns the assigned seq
GET /conversations/{id}/sync?since_seq=41&limit=100Catch upReturns rows with seq > 41 in order, plus next_seq
POST /conversations/{id}/readRead receiptStores last_read_seq per user, not a timestamp

Worked trace. Alice is offline and sends two messages, then reconnects:

StepEventServer state
1Alice queues client_msg_id=a1, a2 locallyNothing sent
2Alice reconnects, POST with a1Inserted as seq=42, returns 201 {seq: 42}
3Network drops, Alice retries a1Unique constraint hits, returns existing seq=42, no duplicate
4Alice POSTs a2Inserted as seq=43
5Alice GET /sync?since_seq=41Returns 42, 43, plus Bob's seq=44 sent while she was offline
6Alice stores last_seen_seq=44Next sync starts at 44, no re-download

Edits and deletes are new rows in effect, not rewrites: an edit sets edited_at and a new body on the same seq, a delete sets deleted_at as a tombstone. Sync returns tombstones too, so an offline client that missed a delete still converges. Client timestamps are display-only. Ordering by created_at breaks when a phone clock is wrong by minutes, which is common, so seq is the only ordering key.

Failure modes I would name in the loop

Duplicate on retry is handled by the unique constraint, as traced above. A client that never syncs grows the pull without bound, so limit=100 with next_seq pagination is mandatory, and I would cap how far back a sync can go before forcing a snapshot rebuild. WebSocket disconnects are expected, so the client treats the socket as a hint and always reconciles with a sync pull after reconnect. Presence (typing, online status) stays out of this log entirely. It is ephemeral, goes over the socket only, and is never persisted to messages, because persisting it would pollute the sync stream with events that have no ordering meaning.

For scale, the hot path is one indexed insert and one indexed range scan per conversation, both served by the primary key. If a single conversation becomes hot, the per-conversation lock is the first bottleneck I would measure, and the fix is sharding the counter, not changing the protocol.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10Explain how you would transition a monolithic application to a microservices architecture using message brokers like Kafka or SQS?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would not start by picking Kafka or SQS. I would start by picking one seam in the monolith where a team can own a bounded context end to end, then move traffic behind a strangler facade and let the old code die only after the new path has carried real traffic. The broker choice follows from the coupling I need to break.

Take a payments monolith at Stone as the concrete case. Suppose orders, payments, and ledger share one Postgres database and call each other in process. I would extract payments first because its boundary is already visible in the code: authorize, capture, refund, and webhook handling. orders keeps owning order state. ledger stays shared until payments stops writing to it directly.

The migration has five moves. First, put an anti-corruption layer in front of the monolith so new callers depend on a payments API, not on internal tables. Second, give the extracted service its own database and write events through a transactional outbox, so a database commit and an event publish cannot diverge. Third, run the new service in shadow mode, consuming copied events and comparing results without serving traffic. Fourth, cut over by percentage behind the facade, with instant rollback to the monolith path. Fifth, delete the old code path only after a full reconciliation period with zero divergence.

Why the outbox matters

The classic failure is dual write: update Postgres, then publish to Kafka, then crash before the publish. The payment exists but no event does. The reverse order loses the event on crash after publish. The outbox fixes the ordering by making the event a row in the same transaction as the business change.

Python
# Python 3.12, checked against Postgres 15 semantics
def capture_payment(conn, payment_id, amount_cents):
    with conn.transaction():
        conn.execute(
            "UPDATE payments SET status='captured', amount_cents=%s WHERE id=%s",
            (amount_cents, payment_id),
        )
        conn.execute(
            """INSERT INTO outbox (aggregate_id, event_type, payload)
               VALUES (%s, 'payment.captured', %s::jsonb)""",
            (payment_id, json.dumps({"amount_cents": amount_cents})),
        )
    # A separate relay reads outbox and publishes to Kafka or SQS.
    # It marks rows sent only after the broker acknowledges.

A relay polls or uses CDC, publishes, and marks the row sent. Delivery is at least once. Consumers must be idempotent, keyed on event_id or the aggregate version. Anyone promising exactly once end to end across Postgres and a broker is selling a demo, not a system.

old path new path Client Strangler facade Monolith Payments service Payments DB + outbox Outbox relay Kafka or SQS Ledger and notifications

Kafka or SQS: pick by the contract you need

DimensionKafkaSQS
---------
---------
---------
---------
Consumer modelLog consumers commit offsets, replay from any offsetQueue consumers delete after processing, visibility timeout governs redelivery
OrderingPer partition, keyed by aggregate idStandard: no order. FIFO: per message group, deduplication window 5 minutes
Replay and auditStrong. Retention commonly set to 7 days or longer, so a new consumer can rebuild stateWeak. Retention up to 14 days, no replay after delete
OperationsYou run brokers, partitions, rebalance, lag monitoringAWS runs the queue, you run DLQ redrive and visibility tuning
Best fit hereLedger rebuild, event history, multiple independent consumers of payment.capturedTask queues, webhooks, notifications where replay is not required

For payments events that ledger and notifications both consume, and that finance may need to replay after a bug, I would choose Kafka. For a single consumer that just needs reliable delivery, SQS Standard is cheaper to operate and simpler to reason about. Mixing both is fine: Kafka for domain events, SQS for asynchronous jobs.

Cutover trace and failure modes

Shadow mode first. Mirror production events into the new service for, say, 48 hours on a representative traffic slice. Compare captured totals per hour between monolith and new service. Hypothetical gate: divergence above 0.01% of events blocks cutover. Then shift 1%, 10%, 50%, 100% of traffic at the facade, watching p99 latency, error rate, and consumer lag. Rollback is a facade flag flip, not a redeploy.

Three failures I would name in the interview. Schema drift: a producer adds a field and an old consumer breaks. Mitigation is versioned schemas, additive changes only, and contract tests in CI. Poison messages: one malformed event loops forever and blocks its partition or message group. Mitigation is a dead letter queue after a bounded retry count, plus alerting on DLQ depth above zero for payments topics. Ordering violations: two events for the same payment arrive reversed and the consumer applies a stale state. Mitigation is keying by payment id so one partition or message group serializes them, and storing the aggregate version to reject older events.

The monolith does not get deleted at cutover. It stays as the rollback path until reconciliation is clean for a full business cycle, then the old tables are read only, then dropped. That sequence is what makes the migration reversible, which is the property that actually de-risks it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11What is the difference between SQL and NoSQL databases, and when would you choose one over the other for a financial ledger?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

For a financial ledger, I would put the system of record in a relational database, usually PostgreSQL, and use NoSQL only around the edges. A ledger is not a bag of documents. It is a set of accounts with invariants that must hold across rows at the same moment: every journal balances, a debit in one account has a matching credit in another, and a balance can be recomputed from posted lines. Relational tables, foreign keys, check constraints and multi-row transactions express those invariants directly. A document store can store the same rows, but it makes cross-account invariants your application code to maintain, and that is where money goes missing.

Assume the ledger is double-entry, append-only, and the source of truth for balances and audit. If the workload were only storing user preferences or session state, the answer would flip.

What the ledger needs

A posting is atomic. Either both lines land or neither does, and a retry after a network timeout must not post twice. In SQL that is a transaction plus a unique idempotency key. In a NoSQL store without multi-document transactions, the same posting becomes two writes that can be observed separately, or one write that succeeds and one that fails. You then need reconciliation jobs to find the gap, which is a failure mode you chose at design time.

Relational also gives you reporting without an export pipeline. Finance will ask for balances by account, by currency, by day, with joins to customers and products. SQL answers that in place. A document model answers it after you denormalise the same data into several shapes and keep those shapes in sync.

SQL
-- PostgreSQL, checked against PG 16
CREATE TABLE journal_entries (
  id            BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  idempotency_key TEXT NOT NULL UNIQUE,
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE journal_lines (
  entry_id   BIGINT NOT NULL REFERENCES journal_entries(id),
  account_id BIGINT NOT NULL REFERENCES accounts(id),
  amount_minor BIGINT NOT NULL,  -- signed, smallest currency unit
  PRIMARY KEY (entry_id, account_id)
);

-- Enforced in the posting transaction, not by a trigger alone:
-- SELECT COALESCE(SUM(amount_minor), 0) FROM journal_lines
-- WHERE entry_id = $1;  -- must equal 0 before COMMIT

Storing minor units as BIGINT avoids floating point drift. A transfer of 10,050 cents is exact in a way 100.50 in a float is not.

Worked trace: one posting

StepActionResult if it fails
1BEGIN; INSERT journal_entries (idempotency_key) VALUES ('pay_9f2')Duplicate key on retry, return the original entry id
2Insert line: operating account, -10050FK fails if account does not exist, transaction aborts
3Insert line: customer account, +10050Same as above
4Check SUM(amount_minor) = 0 for the entryUnbalanced entry never commits
5COMMITBoth lines visible together, or neither

Balances are then a derived view: SELECT account_id, SUM(amount_minor) FROM journal_lines GROUP BY account_id. You can rebuild them from the lines at any time, which is what an auditor wants.

Where NoSQL fits

ConcernRelational (PostgreSQL)Document / key-value (MongoDB, DynamoDB)
Cross-account invariantMulti-row transaction, constraints, SELECT ... FOR UPDATESingle-item or single-document transactions in most setups; multi-document support varies by product and version
Ad hoc finance queriesJoins and aggregation in placeNeeds pre-built projections or an export to a warehouse
Write scalingVertical plus read replicas; partitioning by month or account range helpsHorizontal by partition key, very high single-key write rates
Schema changeMigrations, explicit nullabilityFlexible per document, drift accumulates silently
Audit trailAppend-only tables, revoke UPDATE/DELETE from app roleAppend-only collections work, but no FK to enforce the trail points at real accounts

I would use NoSQL for the parts that do not carry the invariant: a read projection keyed by customer for the API, raw payment gateway payloads kept for dispute handling, KYC documents, and high-volume ingestion of bank statement lines before they are posted. Those stores tolerate eventual consistency and schema drift. The posting step still goes through the relational ledger.

Failure modes to name in the interview

Partial posting in NoSQL: one line written, process crashes, balance is wrong until a reconciler runs. Detection is a nightly job comparing SUM(lines) per entry against zero and per account against the cached balance. Prevention is the transaction above.

Duplicate posting on retry: client times out, retries with a new request, two entries appear. Prevention is the unique idempotency_key and returning the stored entry on conflict, not creating a second one.

Lost update on balance: two concurrent postings read the same cached balance and overwrite each other. Prevention is deriving balances from lines, or locking the account row with SELECT ... FOR UPDATE inside the transaction. A cached balance column is fine as a performance aid if it is updated in the same transaction and reconciled against the lines.

The short version I would give live: relational for the ledger itself because the invariants are relational, NoSQL for projections and payloads where flexibility and write throughput matter more than cross-row guarantees.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12Explain the concepts of database indexing and how an improper index can degrade write performance?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

An index is a separate sorted structure, usually a B-tree in Postgres and MySQL, that maps a column value to the physical location of matching rows. Without it, a lookup scans every row. With it, the engine walks a few levels of the tree and fetches only the matches. The trade is read speed for write cost, because every index has to be maintained on every insert, update and delete that touches its columns.

That maintenance is where an improper index hurts. A write does not just append to the heap. It also inserts a key into each index, writes WAL for that change, may split a leaf page, and evicts useful pages from the buffer pool. Add indexes that are redundant, low selectivity, or built on columns that change often, and write throughput falls while reads gain nothing.

INSERT or UPDATE arrives Write heap tuple For each index: insert key WAL + page split if leaf full Buffer pool churn Commit, then vacuum cleans dead tuples

What the index actually stores

A B-tree leaf holds the indexed key plus a pointer to the heap tuple, in Postgres a TID. Internal pages hold separator keys for routing. Depth grows slowly, so a 10 million row table with a fanout of roughly 200 needs about three levels. That is why a point lookup is three page reads instead of a full scan.

Selectivity decides whether those reads help. An index on orders(id) where id is unique returns one row. An index on orders(status) where 95% of rows are open returns almost the whole table. The planner will often ignore it and seq scan instead, but you still pay to maintain it on every write. A composite index only helps when the query constrains its leftmost columns in order, so (customer_id, created_at) serves WHERE customer_id = ? ORDER BY created_at, while (created_at, customer_id) does not serve that query well.

Worked trace: one insert, four indexes

Assume orders has 10 million rows, a 4 KB page size, and these indexes: primary key on id, unique on external_ref, (customer_id, created_at), and a low selectivity index on status. Hypothetical figures, labelled as such, from a typical Postgres setup:

StepNo extra indexWith low selectivity status index
Heap insert1 page write1 page write
Index inserts3 index page writes4 index page writes
WAL generated~1.2 KB~1.6 KB
Leaf split probabilitylow, pages ~70% fullhigher, extra tree to split
Read benefit for WHERE status='open'none, planner seq scansnone, planner still seq scans

One extra index looks small. At 5,000 inserts per second it is 5,000 extra index writes per second, plus WAL and replication traffic for each. At 20 indexes on a wide table, insert latency can move from single digit milliseconds to tens of milliseconds once the working set no longer fits in shared_buffers and every index insert risks a random disk read.

The failure modes I check first

  1. Redundant indexes. (customer_id) and (customer_id, created_at) both exist. The first adds write cost and the planner rarely needs it. Detection: pg_stat_user_indexes shows idx_scan = 0 for months while idx_tup_read stays low.

  2. Index on a frequently updated column. Updating orders.status in place would normally be a HOT update, which avoids new index entries. If status is indexed, Postgres cannot do a HOT update and must insert a new entry into every index. Detection: n_tup_hot_upd stays near zero while n_tup_upd climbs, and index bloat grows.

  3. Wide or oversized keys. Indexing a 500 character payload column bloats the tree, lowers fanout, and increases depth. Detection: pg_relation_size on the index is a large fraction of the table size.

  4. Too many indexes for the write mix. A read heavy reporting table tolerates 10 indexes. A table taking 10,000 writes per second usually does not. Detection: EXPLAIN (ANALYZE, BUFFERS) on the write shows most time in index inserts, and pg_stat_statements shows mean time rising as index count grows.

How I fix it in practice

SQL
-- Find unused indexes (Postgres)
SELECT indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;

-- Add a covering index without locking writes for long
CREATE INDEX CONCURRENTLY idx_orders_customer_created
    ON orders (customer_id, created_at DESC)
    INCLUDE (status, total_cents);

-- Verify the planner uses it
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, total_cents FROM orders
WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;

INCLUDE makes the index covering for that query, so the engine can answer from the index alone and skip heap fetches. The cost is a wider index, so I only add it when the query is hot and the extra columns are narrow.

Drop candidates get removed in a maintenance window after confirming no query plan references them, because dropping an index that a nightly job uses will move the cost to that job. For a new index on a large table, CONCURRENTLY avoids a long write lock, at the cost of a longer build and a second scan.

The rule I apply: every index needs a named query it serves, a selectivity estimate, and a write budget. If I cannot name the query, the index is a tax on every write with no reader to pay for it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13How do you implement observability and tracing in a microservices environment? What metrics are critical to monitor?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would instrument every service with OpenTelemetry, propagate one trace context end to end, and alert on the four golden signals per service and per dependency: latency, traffic, errors and saturation. Logs, metrics and traces share the same trace_id, service.name and version, so a p99 alert in the API can be traced to the exact downstream call that caused it.

The non-negotiables are propagation and sampling. Without propagation across HTTP, gRPC and Kafka, each hop starts a new trace and you cannot reconstruct a payment flow. Without deliberate sampling, tracing either costs too much at peak traffic or drops the rare errors you need most.

How I would implement it

Each service exports spans through the OpenTelemetry SDK to an OTel Collector sidecar or agent, which batches and forwards to the backend (for example Tempo or Jaeger for traces, Prometheus for metrics, Loki or Elasticsearch for logs). I would use the vendor SDKs rather than hand-rolled middleware, and add semantic attributes on every span: http.route, db.system, messaging.system, plus domain attributes such as order.id or payment.id where privacy rules allow them. Never put card numbers, tokens or full request bodies in attributes.

Propagation uses W3C traceparent for HTTP and gRPC. For Kafka, the producer injects the current context into message headers and the consumer extracts it before processing, so an asynchronous step stays in the same trace.

Go
// Go, service entry point: extract context, start span, inject downstream
func (h *Handler) CreateOrder(w http.ResponseWriter, r *http.Request) {
    ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
    ctx, span := h.tracer.Start(ctx, "POST /orders")
    defer span.End()
    span.SetAttributes(attribute.String("order.id", orderID))

    // Downstream HTTP call inherits ctx, so traceparent is sent automatically
    req, _ := http.NewRequestWithContext(ctx, http.MethodPost, paymentsURL, body)
    otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header))
    resp, err := h.httpClient.Do(req)
    if err != nil {
        span.RecordError(err)
        span.SetStatus(codes.Error, err.Error())
    }
    _ = resp
}

For Kafka the same pattern applies: inject into msg.Headers on publish, extract from headers in the consumer, and start the consumer span as a child of the producer span.

Sampling: I would use head sampling at a low base rate (for example 1% at 10,000 requests per second gives roughly 100 traces per second, which is manageable) plus tail sampling in the Collector. Tail sampling keeps 100% of traces with errors or p99 latency and drops most successful traces. That arithmetic matters: at 1% head sampling alone you would expect to lose 99% of the traces for a rare 0.1% failure mode, which is exactly the failure you are paged for.

Client API gateway Order service Payment service Kafka topic Fulfilment service Collector Trace backend Prometheus

Metrics I would monitor, and why

I would apply RED (rate, errors, duration) to every service endpoint and USE (utilisation, saturation, errors) to every resource it depends on. The critical set:

SignalMetricAlert threshold (example)What it catches
Latencyhttp_server_duration p50, p95, p99 by routep99 > 500 ms for 5 minSlow dependency or lock contention
Errorshttp_server_requests 5xx rate, downstream error rate5xx > 1% over 5 minFailed payment calls, bad deploys
TrafficRequest rate per route, Kafka produce/consume rateDrop > 30% vs 7-day baselineClient outage, broken producer
SaturationDB connection pool utilisation, Kafka consumer lag, queue depthPool > 80%, lag > 1,000 messagesPool exhaustion, stuck consumer
BusinessPayment success rate, order creation rate, refund rateSuccess rate drop > 0.5 ppSilent logic bug that returns 200

Business metrics deserve emphasis in a payments context. A deploy that returns 200 but declines valid payments will not trip a 5xx alert. Payment success rate and order-to-payment conversion catch that within minutes.

Failure modes I would name in the interview

Context lost at an async boundary: a Kafka consumer that does not extract headers creates orphan traces, and the fulfilment step looks disconnected from the order that triggered it. I would detect this by checking trace completeness in dashboards, for example the percentage of consumer spans with a parent.

Cardinality explosion: putting customer_id or order_id on a Prometheus metric creates one time series per customer and can take down ingestion. High-cardinality identifiers belong on traces and logs, not metrics. I would enforce this with a lint rule on metric labels.

Sampling that hides the incident: head sampling at 1% during a 0.1% error spike means most error traces are discarded before anyone knows there is a spike. Tail sampling on error status fixes this, at the cost of Collector memory, so I would size the Collector for the retained trace volume.

Clock skew and missing version labels: traces from two deploys interleaved without service.version make it hard to correlate a regression with a release. I would set service.name and service.version from the deployment manifest, not from code defaults.

Logs complete the picture: structured JSON with trace_id, span_id, level and a stable event name, shipped to the same backend. A log line without a trace ID is hard to place in a flow, so I would include the IDs in the logger context at the entry point and propagate them through every handler.

That combination gives one question a single answer: pick a trace ID from an alert, see every span and log line for that request, and know which service, version and dependency caused it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14Explain the difference between optimistic and pessimistic locking, and how they prevent race conditions?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

Pessimistic locking acquires a lock before the write, so a second transaction waits or fails instead of overwriting the first. Optimistic locking assumes conflicts are rare, reads without a lock, and checks at write time that the row has not changed since the read. If it has, the write fails and the caller retries or aborts.

Take a Stone account balance update. Two requests both read a balance of R$100 and try to debit R$80. Without protection both succeed and the balance ends at R$20 instead of going negative or being rejected. Pessimistic locking serialises them. Optimistic locking lets both read, lets one commit, and makes the second commit fail on a version check.

Pessimistic: lock first, then work

SQL
-- PostgreSQL, checked against 16
BEGIN;
SELECT balance_cents FROM accounts WHERE id = 42 FOR UPDATE;
-- second transaction now blocks on this row until COMMIT/ROLLBACK
UPDATE accounts SET balance_cents = balance_cents - 8000 WHERE id = 42;
COMMIT;

The lock is held for the whole transaction, including any external call made inside it. That is the main failure mode. Hold it across an HTTP call to a fraud service and a slow dependency holds the row lock for seconds, queues every other writer, and exhausts the connection pool. Set lock_timeout (for example 2 s) and statement_timeout so waiters fail fast instead of piling up. Two transactions locking rows in opposite order can also deadlock. PostgreSQL detects it, aborts one with 40P01, and the application must retry the aborted transaction. Lock rows in a consistent order, such as ascending id, to make that rare.

Optimistic: read freely, validate on write

SQL
-- version column incremented on every update
UPDATE accounts
SET balance_cents = balance_cents - 8000, version = version + 1
WHERE id = 42 AND version = 7;
-- 0 rows affected means someone else committed first: retry or return 409

No lock is held while reading or while doing other work. The cost moves to the write. Under high contention on a hot row, say 50 concurrent debits against one merchant account, most writers will fail the version check and retry. That retry storm can waste more work than blocking would have. Optimistic locking suits read-heavy, low-contention data such as a profile update or a catalogue price edit. It suits pessimistic locking when contention is expected and the critical section is short, such as balance, inventory, or seat allocation.

Worked trace: same race, both strategies

StepPessimistic (SELECT ... FOR UPDATE)Optimistic (version check)
1T1 locks row 42, reads 10000 centsT1 reads row 42, version 7, balance 10000
2T2 tries to lock row 42, blocksT2 reads row 42, version 7, balance 10000
3T1 debits 8000, commits, releases lockT1 updates with version = 7, commits, version becomes 8
4T2 acquires lock, reads 2000, sees insufficient funds, rolls backT2 updates with version = 7, affects 0 rows, retries or returns conflict
5Result: one debit, no lost updateResult: one debit, no lost update

The difference is when the conflict surfaces. Pessimistic surfaces it at lock acquisition, as waiting. Optimistic surfaces it at commit, as a failed update. Neither prevents the race by magic. Both make the second writer observe the first writer's result before its own write lands.

PessimisticOptimistic
Read pathBlocks other writersNever blocks
Conflict signalWait, then proceed, or lock timeout0 rows updated, caller retries
Cost under contentionQueueing, pool exhaustion, deadlock riskRepeated retries, wasted work
Best fitHot rows, short transactions, invariants that must holdLow contention, long read or external work before write
Typical API response on conflict503 or timeout if wait is too long409 Conflict with current version
Pessimistic Optimistic 1 0 Begin transaction Strategy SELECT ... FOR UPDATE Other writers wait Update and commit Read row and version Update WHERE version = read_version Rows affected? Retry or return 409

A practical rule I use: if the transaction touches a row many writers hit and the work inside is a few SQL statements, lock it pessimistically and keep the transaction short. If the work includes a network call or the row is rarely written, read optimistically and let the version check catch the rare conflict. Mixing both on the same row in different code paths defeats both, because the optimistic writer never waits for the pessimistic lock and the pessimistic writer never checks the version.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15How do you ensure secure communication between internal microservices?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I assume a Kubernetes or VM fleet running services that call each other over HTTP or gRPC, with a service mesh or a platform team that can issue identities. I would not rely on a VPC alone. Network reachability is not authentication.

The baseline is mutual TLS for every hop, with a workload identity per service, short-lived certificates, and authorisation checked on the receiving side. TLS gives confidentiality and integrity in transit. mTLS adds proof of who is calling. A separate authorisation layer decides what that caller may do, because a valid identity for payments should not automatically be allowed to call admin/users.

Caller workloadpayments-api mTLS handshakeX.509 SVID Mesh or sidecarvalidates cert chain Receiver serviceorders-api Authorisation checkidentity + scope + resource Handler or 403

Identity and transport

Each workload gets an X.509 SVID from SPIFFE/SPIRE, or the equivalent from the cloud provider, for example AWS IAM Roles for Service Accounts or GCP Workload Identity. The certificate is bound to a SPIFFE ID such as spiffe://prod/payments-api. Lifetime is short, typically 1 hour for the SVID with rotation starting at half-life, so a leaked key has a narrow window and there is no long-lived shared secret to rotate manually.

Enforce TLS 1.3 only where the fleet supports it, and TLS 1.2 as a floor elsewhere. Disable plaintext listeners entirely. In Istio terms that is a PeerAuthentication with mode: STRICT on every namespace, plus a DestinationRule requiring ISTIO_MUTUAL. In a non-mesh setup the same rule lives in the server config:

Go
// Go 1.22, server side. ClientCAs is the SPIFFE trust bundle,
// refreshed by the agent, never baked into the image.
cert, err := tls.LoadX509KeyPair(svidCertPath, svidKeyPath)
if err != nil { log.Fatal(err) }

cfg := &tls.Config{
    Certificates: []tls.Certificate{cert},
    ClientCAs:    trustBundle, // SPIFFE trust domain bundle
    ClientAuth:   tls.RequireAndVerifyClientCert,
    MinVersion:   tls.VersionTLS13,
}
ln, err := tls.Listen("tcp", ":8443", cfg)

The handshake cost is real but bounded. With session resumption a resumed TLS 1.3 handshake is roughly one round trip, and inside a data centre that is usually under 1 ms of added latency. The expensive case is a full handshake on every short-lived connection, which is why connection pooling and keep-alive matter more than the cipher choice.

Authorisation, not just authentication

mTLS answers "which workload is this?" It does not answer "may it read this order?" I add a second check at the receiver. Two common patterns:

PatternWhere the claim livesBest forWeakness
mTLS identity plus ACLMesh policy or service configService to service calls with fixed topologyPolicy drifts as services are added
OAuth 2.0 client credentials, JWT access tokenAuthorization: Bearer header, validated against issuer JWKSCalls that cross trust boundaries or need fine-grained scopesToken replay inside its lifetime, needs audience and expiry checks
Static API keyHeader or configLegacy partner APIsShared secret, no per-caller identity, rotation breaks callers

For internal calls I default to the first row and add JWTs only when a request carries a user context that must survive multiple hops. When I do use a token, I validate issuer, audience, expiry and scope on every request, keep lifetimes to 5 to 15 minutes, and never accept a token minted for a different audience. A token for payments presented to ledger must fail even if the signature is valid.

Failure modes I would test for

Expired or not-yet-valid certificates from clock skew between nodes. Detection is a spike in handshake failures with certificate_expired in the mesh telemetry. Fix is NTP discipline plus a small clock-skew allowance in validation, not longer certificate lifetimes.

Trust bundle rotation done wrong. If the new bundle replaces the old one before all workloads have the new intermediate, calls fail in waves. I roll the bundle with both old and new roots trusted during the overlap window, then remove the old root.

A compromised workload holding a valid SVID. Short lifetimes limit the window, and per-service authorisation limits the blast radius. I also log the SPIFFE ID on every request so an audit trail can attribute calls without parsing certificates later.

Plaintext fallback. A client that silently retries over HTTP when TLS fails defeats the whole design. I test this by scanning for open non-TLS ports in the cluster and by alerting on any plaintext traffic on service ports.

What I would not do

I would not put a shared internal API key in environment variables and call that secure communication. I would not terminate TLS only at an ingress and then pass traffic in plaintext inside the cluster. And I would not treat a service account token for the Kubernetes API as authorisation for application calls. Each layer has one job, and the application layer still checks permissions on the resource it is about to return.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16Describe a time when you made a technical decision that resulted in a failure. How did you handle it, and what did you learn?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

Two years ago I owned the pricing read path for an order service. Postgres was the source of truth and reads were fine at our volume, about 25,000 orders a day, but the catalogue lookup on every checkout added roughly 60 ms p99 and the team wanted it gone. I proposed cache-aside in Redis with a 5 minute TTL and no explicit invalidation. My reasoning was that prices change rarely, so a short TTL would bound staleness and keep the code simple. That decision was wrong in a way I should have caught in review.

Prices did change rarely, but when they did, every cached entry for that SKU stayed stale for up to 5 minutes. During a promotion change we charged the old price on 12 orders for that SKU in the 4 minutes before the entries expired. The average difference was $4.20, so about $50 in undercharges, plus a support queue because the invoice price did not match the price shown at checkout. The failure was not the cache. It was treating a correctness-sensitive field as if it were a display field.

What happened, hour by hour

TimeSignalWhat we did
09:12Promotion published in admin, cache keys untouchedNothing, TTL was the plan
09:16Last stale entry expired naturally, 5 minutes after it was cachedNo new stale reads after this point
09:31Reconciliation job flagged 12 orders where charged price differed from catalogue pricePaged the on-call, I joined
09:38Confirmed stale Redis entries had been the cause, Postgres had the new priceFlipped the cache feature flag off, reads fell back to Postgres
09:45Purged the affected price:* keys for the promoted SKUsNo stale entries remained to expire
10:05Finance exported the 12 affected ordersIssued refunds or rebills per policy, emailed affected customers
11:30Cache re-enabled behind explicit invalidationMonitored reconciliation for 24 hours, zero mismatches

Handling it mattered more than the fix. I owned the flag, so disabling the cache took one config change and p99 went back to 60 ms, which was acceptable for a day. I did not try to patch the cache in place while traffic was live. We purged only the promoted SKUs, rebuilt them from Postgres, and let the rest expire. Finance owned the customer remediation, I owned the data export and the reconciliation query, and we agreed the definition of affected orders before anyone contacted a customer. That avoided arguing about $50 while customers waited.

The fix I shipped

Cache-aside stayed, but the write path now updates the cache after the database commit, and a version check stops an older read from overwriting a newer price. The TTL is 60 seconds as a backstop, not as the correctness mechanism:

Python
# Python 3.12, Redis 7
import json

SET_IF_NEWER = """
local cur = redis.call('GET', KEYS[1])
if cur then
  local cur_v = cjson.decode(cur).version
  if tonumber(ARGV[2]) <= cur_v then return 0 end
end
redis.call('SET', KEYS[1], ARGV[1], 'EX', 60)
return 1
"""

def get_price(sku: str) -> Decimal:
    cached = redis.get(f"price:{sku}")
    if cached:
        return Decimal(json.loads(cached)["price"])
    price, version = db.get_price(sku)  # version increments on every update
    payload = json.dumps({"price": str(price), "version": version})
    redis.eval(SET_IF_NEWER, 1, f"price:{sku}", payload, str(version))
    return price

def update_price(sku: str, new_price: Decimal) -> None:
    version = db.update_price(sku, new_price)  # commit first
    payload = json.dumps({"price": str(new_price), "version": version})
    redis.eval(SET_IF_NEWER, 1, f"price:{sku}", payload, str(version))
    audit.log(sku, new_price, version)

The Lua script is the part that matters. A read that started before the update can finish after it, but its older version will not overwrite the newer cached price. The reconciliation job now runs every 15 minutes instead of hourly and alerts on any mismatch above zero. Zero tolerance sounds strict, but for money fields a single mismatch is a bug, not noise.

What I learned

I had optimised for the common case, rare price changes, and ignored the cost of the rare case. A 60 ms saving was not worth a correctness window on every price change. Now I ask, for any cache or replica, what is the worst stale read, how long can it live, and who detects it. If the answer is "the TTL" and the field affects money, inventory, or permissions, I want explicit invalidation or a version check before I ship it. I also learned to put a kill switch on the read path before launch. The flag cost an afternoon. On the day, it turned a potential outage into a 7 minute rollback.

If I were reviewing that design today, I would ask for the invalidation path in the first design doc, a reconciliation metric on the dashboard, and a load test that publishes a price change mid-traffic. Those three questions would have surfaced the flaw before customers did.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17How do you handle a situation where you disagree with a product manager or a tech lead on a technical approach?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I separate the decision from the person, put numbers on the table, and make the disagreement cheap to test. I do not start by arguing for my preferred stack. I ask what outcome we are optimising for, what constraint is fixed, and what evidence would change either of our minds.

A concrete case from a payments checkout. The product manager wanted a new fraud check called synchronously inside POST /payments, because she needed a hard decline before authorisation. The tech lead wanted it async via Kafka, because the vendor was slow. Both had a point. My job was to make the trade-off visible.

I pulled the current numbers first. Checkout p99 was 180 ms against a 250 ms budget. The vendor quoted p50 120 ms and p99 400 ms in their sandbox. A synchronous call would push p99 past 500 ms once retries were included, and at our volume that meant roughly 2 million extra seconds of latency per day across peak traffic. That is not a preference, it is a budget breach.

Then I proposed a two-day spike instead of a debate. Run the vendor in shadow mode behind a feature flag, log what it would have decided, and measure real latency and false positive rate on live traffic without affecting a single payment. If the data showed the vendor was fast enough, I would happily go synchronous. If not, we had evidence for the async design.

Yes No Disagreement stated Agree outcome and fixed constraint Collect current metrics Cheapest test that could settle it Test result clear? Decide and write ADR Escalate with options and costs Implement, measure, revisit date

What the spike showed, and how I closed it

Shadow mode ran for 48 hours on 5% of traffic. Real p99 was 620 ms, worse than the sandbox, and the vendor flagged 1.8% of transactions, of which our existing rules already caught most. The synchronous option would have added 620 ms to the tail and blocked checkout threads while waiting. The async option had a different cost: a fraud decision could arrive after authorisation, so we needed a compensating action, a hold and review queue, and clear customer messaging.

Optionp99 addedFailure modeCost to reverse
Sync vendor call in request path+620 ms, breaches 250 ms budgetVendor timeout blocks checkout, thread pool saturatesLow, remove call
Async via outbox and Kafka+8 ms to write eventDecision arrives late, needs hold and review flowMedium, consumer already built
Hybrid: sync for high value only+620 ms on 3% of trafficTwo code paths, inconsistent customer experienceMedium, flag per segment

We chose async for standard transactions and sync only above a high-value threshold where the latency hit affected few users and the fraud loss justified it. I wrote a short ADR recording the numbers, the rejected sync-everything option, and a revisit date in six weeks once we had review queue data. The product manager got the hard decline where it mattered most. The tech lead got a request path that stayed inside budget.

When the other person is a tech lead, and I lose

The same process applies, with one extra step. If the lead decides against my recommendation after seeing the data, I implement their version fully and record my dissent in the ADR, with the metric that would prove me right. I do not quietly build my version in parallel or relitigate it in every stand-up. If that metric moves the wrong way, I bring the ADR back with fresh numbers. That keeps disagreement professional and reversible.

What I avoid: escalating to a manager before I have data, which reads as politics; silent compliance when I think a design will fail in production, which creates a bigger problem later; and framing it as my stack versus theirs. The question I keep asking is what would we need to see in two days to know who is right, and then I go and get it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18Tell me about a complex project you owned from start to finish. How did you manage stakeholders and ensure delivery?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I owned a settlement rebuild end to end: replacing a nightly batch file that paid merchants with an event-driven pipeline that recalculated balances from the ledger and paid out intraday. Scope was 14 weeks, 2.1 million transactions a day, and four teams touching it. I was the single point of accountability for scope, the technical design, and the go-live date, and I ran delivery as a weekly demo plus a written decision log, not status meetings.

The first two weeks were discovery with finance operations and risk, because they owned the rules I could not invent. We traced 40 historical payout disputes back to three causes: duplicate webhook delivery, a timezone bug in the batch window, and manual adjustments with no audit trail. That gave me a testable definition of done: replay any day from the ledger, reproduce the payout to the cent, and show the adjustment history. Product owned prioritisation, finance owned the payout rules, risk owned the cut-off times, and I owned the architecture and the date. Writing that split down early stopped the usual drift where everyone assumes someone else decided.

Delivery ran on a fixed cadence. Monday: plan and risks. Wednesday: working software demo, even if it was only the replay tool. Friday: written update with what shipped, what slipped, and the next decision needed. Every stakeholder got the same one-page note, with a section tailored to them. That sounds bureaucratic, but it meant a finance lead could read the reconciliation numbers without wading through API details, and an engineer could see the contract changes without hunting in chat.

StakeholderWhat they neededHow I kept them alignedDecision they owned
ProductIntraday payouts without breaking merchant promisesWeekly demo against real replay dataFeature order and scope cuts
Finance operationsReconciliation to the cent, audit trail for adjustmentsDaily shadow-run report during the last 4 weeksPayout rules and manual adjustment policy
RiskCut-off times and fraud holds preservedJoint review of every rule change in the decision logHold and release criteria
Merchant supportA clear answer when a payout looked wrongShared lookup tool built in week 6Support scripts and comms timing
Platform teamNo new infra surprises at launchContract freeze 3 weeks before cutoverQueue and storage limits

Where delivery nearly failed

In week 9 the shadow run showed a 0.4% mismatch against the old batch. That is roughly 8,400 transactions a day, so it was not noise. The cause was my bug: I had bucketed transactions by UTC day, while finance defined the settlement day in America/Sao_Paulo time. The fix was small, but the detection mattered. Because we had run the new pipeline in parallel for three weeks and compared totals per merchant per day, we caught it before any money moved. A launch based on unit tests alone would have shipped it.

I also cut scope in week 10. The original plan included a self-serve merchant dashboard. It was the least critical piece and the one with the most open questions, so I moved it to a follow-up and kept the lookup tool for support. That bought back two weeks of buffer. The arithmetic was simple: 14 weeks planned, 2 weeks of buffer held for reconciliation fixes, and one feature removed rather than letting the buffer be consumed silently.

Yes No Weekly demo on replay data Stakeholder feedback Decision logged with owner Scope or design change Shadow run comparison Mismatch above 0.05%? Fix and re-run replay Proceed to next release

Rollout

We rolled out to 5% of merchants for 3 days, then 25%, then 100%, with a one-command rollback to the batch file for the first two weeks. The guardrail was reconciliation mismatch, not error rate. Error rate can look fine while money is wrong. We held the old path until mismatch stayed under 0.05% for five consecutive days, which it did on day 4. After cutover, payout disputes dropped from about 40 a week to 6, and the median time to answer a merchant query went from a day of spreadsheet work to under 10 minutes in the lookup tool.

If I ran it again I would freeze the settlement-day definition in week 1 as a signed test fixture, not a paragraph in a doc. Most of the stakeholder friction in this project came from rules that lived in people's heads. Turning each rule into a replayable test case was what let product, finance, and engineering argue about data instead of about memory.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19Give an example of how you mentored a junior engineer or helped improve your team's overall engineering practices?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I mentored a junior backend engineer through her first production ownership, and used what we learned to change how our team reviewed payment code. She had joined a team running a webhook handler for card payments. It processed about 40,000 events a day, and timeouts from the downstream ledger service were paging us roughly twice a week. Her first instinct, which is a normal instinct, was to raise the client timeout from 2 seconds to 10 seconds.

I did not correct that in a review comment. I asked her to walk me through what happened during the last page, with the trace open. We found the handler held a database connection while waiting on the ledger call, so a slow downstream call did not just delay one request. It consumed the pool. At 20 connections, p99 for unrelated endpoints went from about 40 ms to over 900 ms because new requests queued behind the pool. Raising the timeout would have made that worse.

Over the next six weeks we worked in a loop: she owned the fix, I reviewed the reasoning before the code, and we measured the result together. The fix moved the ledger call outside the transaction, added a 1.5 second deadline with a circuit breaker, and made the webhook handler return 202 and process asynchronously with an idempotency key on the ledger write. She wrote the runbook entry for the new failure mode, which was a retry storm when the breaker opened.

What the mentoring actually looked like

Week 1 and 2 were pairing on live incidents only. I narrated my debugging steps out loud and made her drive the keyboard for the second incident. By week 3 she was leading the incident call and I stayed silent unless she asked. That handover matters. If I keep driving, the junior learns my answers. If I step back too early, she learns to guess under pressure.

I also changed my review style for her. Instead of marking up every line, I left two kinds of comments: questions that pointed at a mechanism she had not considered, and direct fixes for things that were purely local style. She told me later that the questions were the part she kept. A direct fix ends a thread. A question about connection pool lifetime changed how she read the next service she touched.

Measure, 8 weeks before to 8 weeks afterBeforeAfter
Pages from webhook timeouts2 per week0 in the final 6 weeks
p99 latency on unrelated endpoints during a slow ledger call900 ms85 ms
Her PRs merged without a senior rework pass1 in 43 in 4
Mean time to first review on her PRs26 hours9 hours

Those figures are from our internal dashboards for that service, not a company-wide claim. The latency change came from releasing the connection before the network call, which we verified by loading the handler with a stubbed ledger service that slept 3 seconds.

The team practice that came out of it

The pattern we kept hitting was that reviewers checked logic but nobody checked resource lifetime or retry behaviour. So I proposed a short checklist in our PR template, and we trialled it on one service for a month before rolling it out. It added about five minutes to a review and caught two pool exhaustion issues in the first three weeks that would otherwise have shipped.

MARKDOWN
## Review checklist: backend change
- [ ] What resource is held across a network or disk call? (connection, lock, file handle)
- [ ] What happens on retry? Is the write idempotent, and what is the key?
- [ ] What is the deadline, and what does the caller see when it expires?
- [ ] Which metric or log line proves this worked in production?
Junior owns the change Author writes reasoning in PR Reviewer asks mechanism questions Ship behind flag or async path Review dashboard together Author writes runbook update

Failure modes I watch for in mentoring

The first is becoming a bottleneck. If every design decision routes through me, review latency goes up and the junior never builds judgement. I set a rule that she could merge after one other senior approved, and I was not required to be that senior. The second is feedback that is too vague to act on. "Make this cleaner" teaches nothing. I tried to name the concrete risk, such as "this lock is held across the HTTP call, so a slow downstream blocks the pool." The third is measuring only code output. Her runbook entry and her incident leadership were better evidence of growth than her commit count, and they are what I would cite in a promotion case.

If I were doing it again I would start the pairing in week 1 with a written plan for what ownership looks like by week 6, including which incidents she leads alone. We improvised that plan, and the improvisation cost us a week where I was still answering questions she was ready to answer herself.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20How do you prioritize technical debt versus delivering new features under tight deadlines?

Reported in Stone Software Engineer Interview Questions & Guide 2026

The 90-second answer

I do not treat debt and features as two queues competing for the same sprint. I price both in the same unit: cost of delay per week, plus the risk they carry if I wait. A feature has a cost of delay because revenue, a contractual date, or a customer commitment slips. Debt has a cost of delay because every week it stays, it taxes every change that touches that code and raises the chance of an incident on a live path.

Under a tight deadline I ask three questions in order. First, does the debt sit on the path the feature must ship through? If the new payment endpoint reuses a retry handler that times out silently, paying down that handler is part of the feature, not a separate item. Second, what breaks if I wait one release cycle? A missing index on a low traffic admin report can wait. A connection pool that saturates at 20 connections on the checkout path cannot. Third, can I ship the feature behind a flag with a rollback, and buy the debt down in the next cycle without blocking the release?

That gives me a rule I can defend to a product manager: pay debt first when it blocks correctness, safety, or the feature itself. Defer it when the interest is measurable but small, and write down the interest so the deferral is a decision, not an accident.

How I score it

I keep a short debt register next to the roadmap. Each item gets an owner, the code path it affects, and two numbers: the weekly cost of waiting, and the engineering days to remove it. I score it the same way I score a feature.

Python
# Python 3.12, illustrative scoring used in planning
def priority(cost_of_delay_per_week, risk_cost_per_week, effort_days):
    # risk_cost_per_week = probability of incident per week * cost of that incident
    return (cost_of_delay_per_week + risk_cost_per_week) / max(effort_days, 0.5)

A feature that unlocks a partner launch in two weeks has a high cost of delay per week. A flaky timeout handler on the payment gateway has a low direct cost of delay, but a high risk cost: if it misfires during the launch, it corrupts retries and support load spikes. The formula surfaces that trade-off instead of letting the loudest stakeholder win.

Worked example, figures are hypothetical and labelled as such for a planning discussion:

ItemEffortCost of delay / weekRisk cost / weekScore
New refund endpoint10 daysR$80k in delayed partner revenueR$5k8.5
Fix idempotency store TTL and replay logic3 daysR$0kR$45k (duplicate refunds)15.0
Add index to admin reporting query1 dayR$2k in analyst waiting timeR$1k3.0
Refactor ledger read model for elegance15 daysR$0kR$3k0.2

The idempotency fix outranks the feature even though it produces no demo. Shipping refunds on top of a replay bug would turn the launch into a reconciliation problem. The reporting index is cheap and I would just do it in a spare day. The read model refactor waits, because the current model is correct and only slower than I would like.

What I do in the room

I bring the register to planning with the feature list, not after it. I name the debt that the feature depends on and propose one of three options: bundle it into the feature estimate, ship the feature with a flag and a dated follow-up ticket, or defer the feature. I never accept a silent deferral. The ticket gets a week number, an owner, and the metric that will prove the interest is growing, such as p99 latency on the affected endpoint, retry rate, or incident count.

I also protect a fixed slice of capacity, typically 15 to 20 percent, for debt that scored high on risk. Without that slice, every cycle the feature wins the argument and the risk compounds until it becomes an outage that cancels two cycles of features. With the slice, the conversation stays about ordering, not about whether debt exists.

Failure modes I watch for

The common failure is paying debt that nobody can observe. A rewrite of a stable internal tool with no incident history and no feature blocked on it burns the deadline and buys nothing the business can feel. The opposite failure is shipping on a known broken path because the demo worked once. On a payment path, a timeout that is handled by blind retry without an idempotency key will pass a happy path test and fail in production at the first slow downstream, which is exactly when traffic peaks.

I detect the second failure before release by checking the trace for the feature end to end: does a retry after a 2 second timeout create one order or two, does the ledger balance after a partial failure, and can I roll back with the flag without a deploy. If any of those answers is unclear, the debt item moves into the feature scope.

When the deadline is real, my answer to the interviewer is this: I ship the feature, I pay the debt that sits under it, and I defer the rest in writing with a price tag and a date. That is how the team keeps both the launch date and the system that has to survive after it.

Curated: · Written: · Reviewed:

Difficulty: Hard

Curated: · Written: · Reviewed: