
Real Interview Questions for the Software Engineer at Shopify
NewInterview Q&A
Q&A-1Simulate a rover that turns and moves on a grid, then support several rovers, a 3D map and collision checks?
Reported in Shopify interview process 2026: rounds, questions and tips
The 90-second answer
I would model a rover as position plus heading, and keep movement as a pure state transition. Position is (x, y) on a bounded grid, heading is one of N, E, S, W. L and R rotate heading in place. M attempts to move one cell in the current heading. That separation matters because turning never collides, and moving is the only operation that needs a collision check.
For several rovers, I would execute commands sequentially in input order and maintain an occupancy map from cell to rover id. A rover that cannot move stays put and reports the blocked step, rather than moving partway. Sequential execution gives deterministic results and makes the trace auditable, which is what I would ship first. Simultaneous movement is a different contract and I would call that out explicitly.
For 3D, I would extend position to (x, y, z) and store obstacles as a set of occupied cells. Heading stays in the x/y plane unless the spec adds climb or descend commands. The collision check does not change in shape, it just checks a 3-tuple instead of a 2-tuple.
from dataclasses import dataclass
# Python 3.12
HEADINGS = ["N", "E", "S", "W"]
DELTAS = {"N": (0, 1), "E": (1, 0), "S": (0, -1), "W": (-1, 0)}
@dataclass
class Rover:
id: str
x: int
y: int
z: int
heading: str # N, E, S, W
def turn(self, direction: str) -> None:
i = HEADINGS.index(self.heading)
i = (i + (1 if direction == "R" else -1)) % 4
self.heading = HEADINGS[i]
def next_cell(self) -> tuple[int, int, int]:
dx, dy = DELTAS[self.heading]
return (self.x + dx, self.y + dy, self.z)
def try_move(rover: Rover, occupied: dict, obstacles: set, bounds: tuple) -> bool:
"""Move one step if the target cell is free. Returns False and stays put if blocked."""
max_x, max_y, max_z = bounds
nx, ny, nz = rover.next_cell()
if not (0 <= nx <= max_x and 0 <= ny <= max_y and 0 <= nz <= max_z):
return False
cell = (nx, ny, nz)
if cell in obstacles or cell in occupied:
return False
del occupied[(rover.x, rover.y, rover.z)]
rover.x, rover.y, rover.z = cell
occupied[cell] = rover.id
return TrueWorked trace on a 5 by 5 grid, z = 0, no obstacles. Rover A starts at (1, 1) facing N, Rover B at (3, 3) facing S.
| Step | Rover | Command | Result | Position after |
|---|---|---|---|---|
| 1 | A | M | free | (1, 2) facing N |
| 2 | A | R | turn in place | (1, 2) facing E |
| 3 | A | M | free | (2, 2) facing E |
| 4 | B | M | free | (3, 2) facing S |
| 5 | B | M | blocked, A occupies (2, 2) | (3, 2) facing S |
Step 5 is the case that decides the design. B does not slide, jump, or queue. It stays at (3, 2) and the blocked step is logged, so a caller can replay the run and see exactly where it stopped.
Where the simple version breaks
Order dependence is the first trap. If A and B both want (2, 2), whoever runs first gets it. That is acceptable for sequential execution, but I would state it in the API contract and return the winner in the response. If the interviewer wants simultaneous movement, the rule changes: compute all intended cells first, then reject any move where two rovers target the same cell, and also reject swaps where A moves into B's cell while B moves into A's. A swap passes a naive occupancy check if you update one rover at a time, so simultaneous mode needs a two-phase commit.
The second trap is partial movement. A command string like MMMRM should not leave the rover halfway through if step 3 is blocked, unless the spec says so. My default is atomic per step: each M either completes or does not, and execution continues with the next command from the unchanged position. If the spec wants all-or-nothing per rover, I would simulate on a copy and commit only if every step succeeds.
Cost is linear. Each step is an O(1) hash lookup in the occupancy map, so a run with S total steps across all rovers costs O(S) time and O(R + O) space for R rovers and O obstacle cells. That holds in 3D as well because the map key is just a longer tuple. If the grid were huge and sparse, I would keep the hash map and drop the dense array entirely.
I would close by asking which movement contract they want, sequential or simultaneous, because that single answer changes the collision code more than adding the third dimension does.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Implement an LRU cache with get and put operations?
Reported in Shopify Software Engineer Interview Guide
The 90-second answer
I would build it from a hash map plus a doubly linked list. The map gives O(1) lookup by key. The list keeps recency order, with the most recently used entry at the head and the least recently used at the tail. Every get and every put on an existing key moves that node to the head. When put adds a new key and the size exceeds capacity, I evict the tail node and delete its map entry. Both operations are O(1) time and O(capacity) space.
Assumptions I would state first: capacity is fixed and positive, keys are hashable, get on a miss returns -1, and this is a single process cache. That last point matters at Shopify scale. An in-process LRU is per pod, so it helps for hot local data and request-scoped reuse. It does not replace a shared cache such as Redis when you need consistency across hosts.
# Python 3.11
from typing import Hashable, Any
class _Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key: Hashable, value: Any):
self.key = key
self.value = value
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.map: dict[Hashable, _Node] = {}
# Sentinel head/tail remove empty-list checks.
self.head = _Node(None, None) # most recent side
self.tail = _Node(None, None) # least recent side
self.head.next = self.tail
self.tail.prev = self.head
def _unlink(self, node: _Node) -> None:
node.prev.next = node.next
node.next.prev = node.prev
def _push_front(self, node: _Node) -> None:
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node
def get(self, key: Hashable) -> Any:
node = self.map.get(key)
if node is None:
return -1
self._unlink(node)
self._push_front(node)
return node.value
def put(self, key: Hashable, value: Any) -> None:
node = self.map.get(key)
if node is not None:
node.value = value
self._unlink(node)
self._push_front(node)
return
node = _Node(key, value)
self.map[key] = node
self._push_front(node)
if len(self.map) > self.capacity:
victim = self.tail.prev
self._unlink(victim)
del self.map[victim.key]Worked trace with capacity 3, written as key=value from most to least recent:
| Step | Call | List after call | Result |
|---|---|---|---|
| 1 | put(a, 1) | a=1 | |
| 2 | put(b, 2) | b=2, a=1 | |
| 3 | put(c, 3) | c=3, b=2, a=1 | |
| 4 | get(a) | a=1, c=3, b=2 | 1 |
| 5 | put(d, 4) | d=4, a=1, c=3 | b evicted |
| 6 | get(b) | d=4, a=1, c=3 | -1 |
| 7 | put(c, 30) | c=30, d=4, a=1 | update, no eviction |
Step 7 is the case people miss. Updating an existing key refreshes recency and changes the value, but the size does not grow, so nothing is evicted.
| Operation | Time | Why |
|---|---|---|
get hit | O(1) | map lookup, then two pointer swaps |
get miss | O(1) | map lookup only, list untouched |
put existing key | O(1) | map lookup, unlink, push front |
put new key, under capacity | O(1) | insert into map and list |
put new key, at capacity | O(1) | insert plus one tail eviction |
Follow-ups I expect
Why not just use OrderedDict and call move_to_end? In Python that is a fair production shortcut, and I would say so. The manual list shows the mechanism an interviewer is probing, and it ports directly to languages without an ordered map. The trade-off is more code to get wrong, especially around sentinel nodes and unlinking.
What breaks in production? Two things. First, thread safety. The code above is not safe under concurrent get and put from multiple threads, because unlink and push front are not atomic. I would guard both methods with one lock, or use a striped lock if contention showed up in profiling. Second, unbounded value size. Capacity counts entries, not bytes. A cache holding 10,000 entries with 1 MB values will exhaust memory even though the count looks safe. In a real service I would cap by total bytes as well, or keep values small and push large payloads to a shared cache.
If the interviewer asks for TTL or frequency based eviction, I would add expiry timestamps checked on get, and note that LFU needs a second map from frequency to list, which adds memory and complexity for a workload that may not need it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Build a local URL shortener with validation, hash collision handling, file persistence and high test coverage?
Reported in Shopify interview process 2026: rounds, questions and tips
The 90-second answer
I would build a small Python service with three decisions made explicit: how the code is generated, how collisions are resolved, and how state survives a restart. I would use a counter-free hash with probing for codes, validate the URL before storing anything, and persist to a JSON file with an atomic rename. Tests would cover validation, collision, persistence, and the HTTP layer, because those are the places this exercise usually breaks.
Assumptions I would state up front: single process, single host, no database, and a file that can be read on startup. That rules out distributed locking and lets me focus on correctness of the local logic.
Validation
Accept only http and https, require a host, reject URLs over 2048 characters, and reject embedded credentials. urlparse alone accepts a lot, so I check the parsed parts explicitly.
# Python 3.12, standard library only
from urllib.parse import urlparse
MAX_URL_LEN = 2048
def validate_url(raw: str) -> str:
if not isinstance(raw, str) or not raw.strip():
raise ValueError("url_required")
url = raw.strip()
if len(url) > MAX_URL_LEN:
raise ValueError("url_too_long")
parts = urlparse(url)
if parts.scheme not in ("http", "https"):
raise ValueError("unsupported_scheme")
if not parts.hostname:
raise ValueError("missing_host")
if parts.username or parts.password:
raise ValueError("credentials_not_allowed")
return urlReturning a stable code string matters. The API can map unsupported_scheme to 422 and keep the message for humans separate from the branch clients use.
Code generation and collisions
I would hash the URL with SHA-256, encode the first bytes in base62, and take 6 characters. That gives 62^6 = 56,800,235,584 possible codes. At 10,000 stored URLs the birthday bound puts collision probability near 0.09%, low enough for a local tool and high enough that I still handle it. On collision I rehash with an incrementing salt and probe again. I would not truncate a UUID or use Python's built-in hash(), which is salted per process and changes between runs.
import hashlib
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
CODE_LEN = 6
def _code_for(url: str, salt: int) -> str:
digest = hashlib.sha256(f"{salt}:{url}".encode()).digest()
n = int.from_bytes(digest[:8], "big")
chars = []
for _ in range(CODE_LEN):
chars.append(ALPHABET[n % 62])
n //= 62
return "".join(chars)
def shorten(store: dict, url: str) -> str:
salt = 0
while True:
code = _code_for(url, salt)
existing = store.get(code)
if existing is None or existing == url:
store[code] = url
return code
salt += 1Worked trace when two different URLs land on the same first code:
| Step | Salt | Code | Store state | Result |
|---|---|---|---|---|
| 1 | 0 | aB3x9Q | empty | store aB3x9Q -> https://a.example |
| 2 | 0 | aB3x9Q | aB3x9Q taken by other URL | probe again |
| 3 | 1 | k7Lm2P | free | store k7Lm2P -> https://b.example |
| 4 | 0 | aB3x9Q | same URL as step 1 | return existing code, no duplicate |
Step 4 gives idempotency for free. Shortening the same URL twice returns the same code instead of creating a second entry.
File persistence
I would keep the mapping in memory and write the whole file on each mutation. For a local tool with thousands of entries that is fine, and it avoids a half-written JSON file corrupting the store. Write to a temp file in the same directory, flush, then os.replace it over the target. A crash before the rename leaves the old file intact.
import json, os, tempfile
def save_store(path: str, store: dict) -> None:
directory = os.path.dirname(path) or "."
fd, tmp = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(store, f, indent=2, sort_keys=True)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
except BaseException:
if os.path.exists(tmp):
os.unlink(tmp)
raise
def load_store(path: str) -> dict:
if not os.path.exists(path):
return {}
with open(path, encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, dict):
raise ValueError("corrupt_store")
return dataOn startup I load the file, and if parsing fails I fail fast with corrupt_store rather than starting empty and silently losing every mapping.
HTTP surface
POST /shorten with {"url": "https://shopify.com"} returns 201 and {"code": "aB3x9Q", "short_url": "http://localhost:8000/aB3x9Q"}. GET /aB3x9Q returns 302 with the original Location. I would use 302 here because the mapping is not permanent by contract, and I would document that choice.
Tests
I would aim for branch coverage above 90% on the shortener module, with parametrized cases for each validation rule, a forced collision by monkeypatching _code_for to return a constant on salt 0, a round-trip persistence test using tmp_path, and a corrupt-file test. The collision test is the one reviewers check, so I would make it deterministic instead of hoping two real URLs collide.
import pytest
@pytest.mark.parametrize("bad,code", [
("", "url_required"),
("ftp://example.com", "unsupported_scheme"),
("https://", "missing_host"),
("https://user:pw@example.com", "credentials_not_allowed"),
])
def test_validate_rejects(bad, code):
with pytest.raises(ValueError) as exc:
validate_url(bad)
assert str(exc.value) == code
def test_collision_probes_to_next_salt(monkeypatch):
store = {"AAAAAA": "https://taken.example"}
monkeypatch.setattr(
"shortener._code_for",
lambda url, salt: "AAAAAA" if salt == 0 else "BBBBBB",
)
assert shorten(store, "https://new.example") == "BBBBBB"
assert store["BBBBBB"] == "https://new.example"
def test_persistence_round_trip(tmp_path):
path = str(tmp_path / "urls.json")
save_store(path, {"aB3x9Q": "https://shopify.com"})
assert load_store(path) == {"aB3x9Q": "https://shopify.com"}If I had another hour I would add a DELETE /{code} endpoint, a size cap that returns 507 when the file passes a configured limit, and a concurrency note: this design assumes one writer, so running two processes against the same file would need a lock or a real store.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Assign each person in a CSV a gift recipient with no self-assignment, then add rules on who may give to whom?
Reported in Shopify interview process 2026: rounds, questions and tips
The 90-second answer
I would treat this as a perfect matching problem in a bipartite graph, not as shuffling. Put every person on the left as a giver and again on the right as a recipient. Draw an edge from giver u to recipient v when u may give to v. A valid assignment is a set of edges that covers every giver and every recipient exactly once. That is a perfect matching.
The no-self-assignment rule is just the absence of the edge u -> u. Every later rule, a blocklist, an allowlist, "not last year's recipient", "managers do not give to their reports", becomes deleting or keeping edges. The algorithm does not change when the rules change. That separation is the point.
A shuffled derangement works only for the first part. With constraints, random shuffling plus retry gets exponentially unlikely to hit a valid assignment and gives you no way to explain why it failed.
Parsing and validation first
Read the CSV with a real parser, not split(','), because names can be quoted and contain commas. Trim whitespace, reject empty rows, and reject duplicate names after normalisation. A duplicate silently merges two people and makes the matching meaningless. Keep the original display name for output and a normalised key for matching.
# Python 3.12, standard library only
import csv
from collections import deque
def load_people(path):
with open(path, newline='', encoding='utf-8') as f:
rows = [r['name'].strip() for r in csv.DictReader(f)]
names = [r for r in rows if r]
if len(names) != len({n.casefold() for n in names}):
raise ValueError('duplicate name in CSV')
return names
def hopcroft_karp(adj, n_right):
pair_u = [-1] * len(adj)
pair_v = [-1] * n_right
dist = [0] * len(adj)
def bfs():
q = deque()
for u in range(len(adj)):
if pair_u[u] == -1:
dist[u] = 0
q.append(u)
else:
dist[u] = -1
found = False
while q:
u = q.popleft()
for v in adj[u]:
pu = pair_v[v]
if pu != -1 and dist[pu] == -1:
dist[pu] = dist[u] + 1
q.append(pu)
if pu == -1:
found = True
return found
def dfs(u):
for v in adj[u]:
pu = pair_v[v]
if pu == -1 or (dist[pu] == dist[u] + 1 and dfs(pu)):
pair_u[u] = v
pair_v[v] = u
return True
dist[u] = -1
return False
matching = 0
while bfs():
for u in range(len(adj)):
if pair_u[u] == -1 and dfs(u):
matching += 1
return pair_u, matchingBuild adj[u] as every v where v != u and the rules allow it. Call the function. If matching == n, pair_u is the assignment. Complexity is O(E * sqrt(V)). For 10,000 employees with sparse rules, say an average of 20 allowed recipients each, that is about 200,000 edges and runs comfortably in well under a second in a compiled implementation. A simple augmenting-path search is O(V * E) and is fine for a few hundred people, which is why I would start there in an interview and name Hopcroft-Karp as the production choice.
Worked trace
Four people, with two extra rules: Ana may not give to Ben, and Chen may not give to Ana.
| Giver | Allowed recipients |
|---|---|
| Ana | Chen, Dee |
| Ben | Ana, Chen, Dee |
| Chen | Ben, Dee |
| Dee | Ana, Ben, Chen |
One perfect matching is Ana to Chen, Ben to Dee, Chen to Ben, Dee to Ana. Note that a greedy pass in CSV order can paint itself into a corner. If Ana takes Chen first, Chen takes Ben, Ben takes Dee, Dee takes Ana, that happens to work here, but change one rule and greedy fails while a matching still exists. Augmenting paths fix exactly that: when a giver finds all allowed recipients taken, the search reassigns an earlier giver to a different recipient instead of giving up.
When no assignment exists
This is the case interviewers probe. If the maximum matching covers 97 of 100 people, do not output a partial assignment and do not loop forever reshuffling. Report the unmatched givers and recipients. By Hall's theorem, some set of givers has fewer allowed recipients than givers, and the unmatched set points at it. In practice the cause is usually a rule that is too tight, for example "only give within your team" combined with a team of one, or two people who may only give to each other while also being barred from each other. The fix is a product decision: relax a rule, allow a cross-team edge for the blocked group, or allow a repeat from last year. The code should surface the blocked group so a human can make that call.
Failure modes I would name
Duplicate or whitespace-variant names in the CSV, which I reject at load time. Rules referencing a name that is not in the CSV, which I reject rather than ignore, because a typo in a blocklist silently permits a forbidden pairing. And non-determinism: if the business wants the same input to produce the same output for audit, sort names before building adjacency and use a fixed iteration order. If they want randomness across years, shuffle the adjacency order with a seeded RNG after the matching structure is fixed, or add a random tie-break weight. Randomness is a presentation choice on top of the matching, not a substitute for it.
At Shopify scale I would also keep this as a small batch job behind the internal tools surface rather than a request-path service. It runs once a year, it needs an audit log of who gave to whom, and a failed run should be rerunnable with the same input. The matching core stays the same either way.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Walk me through your life — schools, jobs, key decisions, what brought you here?
Reported in 10 Shopify Software Engineer (New Grad) Interview Questions (2026)
What I would say in the room
"I started at [university] in [year], studying [degree]. I got serious about programming there through [specific project], where I built [thing] and learned [skill] by shipping it to [real users]. After graduating I joined [first employer] as [role]. I worked on [system] for [period], mostly [concrete responsibility, for example checkout retries and webhook delivery]. The turning point was [decision]. I [chose A over B], which meant [cost, for example giving up a larger team and a clearer promotion path]. I stayed on the technical track because I wanted to own production systems. I applied to Shopify because [specific connection to prior work]. At my last job I spent months cutting duplicate order webhooks. I want to work on that problem where it is the core product."
That runs about 110 seconds. I budget it as 30 seconds for school, 40 for work, 20 for the decision, 20 for Shopify. If a chapter runs longer, the interviewer starts steering, and the story stops sounding like a choice and starts sounding like a CV.
Why the decision carries the answer
Schools and job titles are easy to verify on a resume. An interviewer asks for decisions because a decision shows how you weigh a cost against a gain. Saying you left a stable role for a smaller team tells them you will accept ambiguity. Saying you stayed on the technical track instead of moving into coordination tells them where you want to be in two years. Saying you picked a co-op over a research role tells them you prefer a user and a deadline over a paper.
Weigh the trade-off aloud in one sentence. Name what you gave up, then name what you got. "I gave up a bigger team and a faster promotion path. I got on-call for a service with 40,000 orders a day, and I learned how retries behave under load." That sentence lets the interviewer test judgement. They can follow up with "What would you do differently?" and you have material ready. A decision without a cost sounds like a preference. A preference alone does not predict how you will act when a migration goes wrong at 2 a.m.
A concrete example to adapt
The details below are invented. Replace every bracket with your own history and keep only stories you can defend under follow-up questions.
| Chapter | Work I can describe | Cost I accepted |
|---|---|---|
| University, 2019 to 2023 | Built an inventory tool in Go for a local shop. It tracked stock for 3 locations and was used daily for two years. | Chose a co-op placement in third year. That delayed graduation by eight months. |
| First job, 2023 to 2024 | Rails engineer at a logistics startup. Owned order import, tracking pages and weekend on-call after the team shrank. | Stayed through a reorg when two teammates left. My scope doubled and my salary stayed flat for a year. |
| Second job, 2024 to 2026 | Payments engineer. Worked on idempotent webhook delivery and a retry queue that cut merchant reconciliation time from 12 hours to 20 minutes. | Declined a move into program coordination. I kept hands-on work and accepted slower title growth. |
For a new graduate, the same shape works with internships, open source and part-time work. A project that handled 10,000 concurrent connections, or a co-op bug fix you can walk through line by line, counts as evidence. Keep the timeline short. Two minutes leaves room for the interviewer to probe.
Where this answer fails in practice
Reading dates in order is the most common failure. The interviewer hears a list, learns nothing about judgement, and moves on with a weak signal. Fix it by cutting any chapter that has no decision attached to it.
Vague decisions fail in a different way. "I wanted a new challenge" gives the interviewer nothing to probe. They will ask what challenge, what you risked, and what changed in your work afterward. If you cannot answer those, pick a smaller decision you can answer. Choosing a project, dropping a feature, or moving cities for a role all work.
Generic praise for Shopify also fails. "Great culture and exciting growth" could be said about any company. Tie the reason to work you have done. Name a system, a constraint or a metric from your past job and explain why you want to work on it at larger scale. If you have no direct commerce experience, say what transfers. Latency budgets, data migrations and API design transfer across domains.
Oversharing personal history creates a second problem. Details about family, health or finances pull the conversation away from work and can make the interviewer uncomfortable. Keep personal context to one line if it explains a move, then return to work.
Finally, check the story against your resume before the loop. Interviewers compare dates and titles across rounds. A mismatch, even a small one, raises questions about honesty that a strong technical answer later cannot erase."
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Build an autocomplete/search system from a list of search frequencies?
Reported in Shopify Software Engineer interview experience (June 2026)
The 90-second answer
Build a trie where each node stores the top completions for its prefix, ranked by the frequency of the completion itself. Insert every term once and add it to the top list of every node on its path. A query then walks one character at a time and returns the list already stored there, so lookup costs O(prefix length + k) for k suggestions, with no sorting at query time.
That precomputation is the whole trade. You pay memory and update cost up front to make the hot path, product and shop search typed on a phone, a pointer chase.
Assume the input is a list of (term, frequency) pairs, for example ("running shoes", 120000). In the interview I would state that frequencies are static during the build, then handle updates after.
# Python 3.11, checked against CPython 3.11
class Node:
__slots__ = ("children", "top")
def __init__(self):
self.children = {}
self.top = [] # list of (term, freq), sorted desc, capped at K
class Autocomplete:
K = 5
def __init__(self):
self.root = Node()
def add(self, term: str, freq: int):
term = term.lower()
node = self.root
for ch in term:
node = node.children.setdefault(ch, Node())
lst = node.top
lst.append((term, freq))
lst.sort(key=lambda x: -x[1])
del lst[self.K:]
def suggest(self, prefix: str, k: int = 5):
node = self.root
for ch in prefix.lower():
node = node.children.get(ch)
if node is None:
return []
return [t for t, _ in node.top[:k]]Each node stores term frequencies, not subtree totals. That distinction matters for ranking. At node s, shoes is scored 900 because 900 searches were for shoes, not because 1600 searches passed through s. Subtree totals would inflate short terms that happen to sit above many others and would make the trace below inconsistent with the input data.
In production code I would not re-sort on every insert. I would collect terms first, then compute each node's top list in one pass, or keep a heap of size K. The interview version above keeps the invariant visible: every node on the path can answer immediately. It also assumes each term is added once with its total frequency. Repeated adds of the same term would need a replace step, not another append.
Worked trace with terms shoes 900, shopify 800, shoes sale 700, shirt 600:
| Prefix typed | Node reached | Returned (K=3) |
|---|---|---|
s | s | shoes, shopify, shoes sale |
sh | sh | shoes, shopify, shoes sale |
sho | sho | shoes, shopify, shoes sale |
shop | shop | shopify |
shoe | shoe | shoes, shoes sale |
x | missing | [] |
At s and sh, all four terms are in the subtree, so the top three by term frequency are 900, 800 and 700. shirt at 600 is fourth and drops out at K=3. At sho, shirt is no longer in the subtree, but the top three are unchanged because shirt was not in them. At shop, only shopify remains.
Why a trie over the alternatives:
| Approach | Lookup | Memory for 10M terms, avg 12 chars | Update |
|---|---|---|---|
| Trie with top-K per node | O(L + K) | High: up to ~120M nodes worst case, far less with shared prefixes, ~2-4 GB in a naive dict-of-dicts, far less with array or double-array encoding | O(L * K) to refresh lists on path |
| Sorted list + binary search | O(L log N + scan) | Low: terms only, ~200 MB | Rebuild or insert O(N) |
| Hash map from every prefix to top-K | O(L + K) hash lookups | Very high: sum of all prefix lengths, ~120M entries | O(L) per term, same blowup |
| Trie without stored top-K, collect subtree at query time | O(L + subtree) | Medium | O(L), but query can scan thousands of nodes under s |
The sorted list is the credible fallback and I would mention it first. It is simpler, cache friendly, and fine up to a few hundred thousand terms. It loses when the prefix is short, because you then scan a large contiguous range to find the highest frequency items. The trie with stored top-K wins exactly there, which is the common case in search-as-you-type.
Scale arithmetic, labelled as rough: 10M distinct terms at an average of 12 characters gives an upper bound of 120M nodes if no prefixes were shared. Shared prefixes cut that well below the bound, say 30M nodes in practice. At 32 bytes per node in a compact encoding that is about 1 GB, plus top-K lists. That fits on one search host, which is why Shopify style systems often shard by first character or by locale and replicate the shard, rather than distributing a single trie across machines. Sharding by first letter keeps lookup to one shard and makes rebuilds independent.
Failure modes I would name before being asked:
- Stale frequencies. Search trends shift hourly. A static build drifts within a day. Fix: rebuild from a rolling window, for example last 7 days of query logs, and swap the whole trie atomically. Incremental updates are possible but the top-K lists on a hot path like
schurn constantly. - Hot prefixes.
s,a,ehave enormous subtrees. Storing top-K there is cheap, but updating them on every insert is the bottleneck. Batch updates and rebuilds avoid per-keystroke writes. - Normalization.
Café,cafe, andCAFÉshould meet at one node. Lowercase, strip accents, and normalize Unicode (NFC) before insert and before lookup, or the trie fragments. - Personalization leakage. Global frequencies suggest popular terms, which is fine. Mixing in a user's private history into a shared trie would leak one shopper's queries to another. Keep personalization in a separate per-user layer merged at request time.
- Cold start and typos. A trie returns nothing for a misspelled prefix. Production systems add a fallback: if the walk fails, try edit distance 1 from the last valid node, or fall back to the sorted list scan. I would flag that as out of scope for the core design, not pretend the trie handles it.
Follow-up I expect: how to handle a stream of new frequencies. Answer: keep the trie read-only for serving, apply updates in a batch job, publish a new snapshot, and flip a pointer. If the interviewer pushes for online updates, update the top lists along the path and recompute lazily on read with a dirty flag, accepting that the first read after an update pays the sort.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Implement a simple bank system?
Reported in Shopify Software Engineer Interview Guide
The 90-second answer
I would build accounts keyed by ID, store balances as integer cents, and make every money movement go through one atomic transfer operation that appends to a ledger. Deposit and withdraw are transfers to and from a system account. That single rule gives me a balance I can recompute, an audit trail, and a place to enforce invariants.
Assumptions I would state first: single process for this exercise, no persistence layer, no authentication, amounts are non-negative integers in cents, and concurrent calls from multiple threads are in scope. If persistence were required, the same interface works with a database transaction replacing the lock.
import threading
from dataclasses import dataclass
@dataclass
class Entry:
account_id: str
delta_cents: int
transfer_id: str
class Bank:
SYSTEM = "__system__"
def __init__(self):
self._balances = {self.SYSTEM: 0}
self._ledger = []
self._seen = {} # idempotency_key -> transfer_id
self._lock = threading.Lock()
self._seq = 0
def open_account(self, account_id: str):
with self._lock:
if account_id in self._balances:
raise ValueError("account exists")
self._balances[account_id] = 0
def transfer(self, src, dst, amount_cents, idempotency_key=None):
if amount_cents <= 0:
raise ValueError("amount must be positive")
with self._lock:
if idempotency_key and idempotency_key in self._seen:
return self._seen[idempotency_key]
if src not in self._balances or dst not in self._balances:
raise KeyError("unknown account")
if self._balances[src] < amount_cents:
raise ValueError("insufficient funds")
self._seq += 1
tid = f"t{self._seq}"
self._balances[src] -= amount_cents
self._balances[dst] += amount_cents
self._ledger.append(Entry(src, -amount_cents, tid))
self._ledger.append(Entry(dst, amount_cents, tid))
if idempotency_key:
self._seen[idempotency_key] = tid
return tid
def deposit(self, dst, amount_cents, idempotency_key=None):
return self.transfer(self.SYSTEM, dst, amount_cents, idempotency_key)
def withdraw(self, src, amount_cents, idempotency_key=None):
return self.transfer(src, self.SYSTEM, amount_cents, idempotency_key)
def balance(self, account_id):
with self._lock:
return self._balances[account_id]The system account is allowed to go negative. That models money entering the bank from outside without a special case in the transfer logic. Every other account is checked for sufficient funds before any mutation.
Worked trace
| Step | Call | Alice | Bob | System | Ledger added |
|---|---|---|---|---|---|
| 1 | deposit("alice", 10000, "k1") | 10000 | 0 | -10000 | -10000 system, +10000 alice |
| 2 | transfer("alice", "bob", 2500, "k2") | 7500 | 2500 | -10000 | -2500 alice, +2500 bob |
| 3 | retry step 2 with "k2" | 7500 | 2500 | -10000 | none, returns t2 |
| 4 | transfer("bob", "alice", 9999) | 7500 | 2500 | -10000 | none, raises insufficient funds |
Step 3 is the idempotency check. A client that times out after step 2 and retries with the same key gets the original transfer ID instead of a second debit. Without the key, the bank cannot distinguish a retry from a deliberate second payment.
Failure modes I would name
Race on the balance check. Two threads can both read a balance of 10000 and both pass a check for 8000. The lock around check plus mutation closes that window in this version. In a database version, the equivalent is a row lock on both account rows in a fixed order, or a conditional update such as UPDATE accounts SET balance = balance - 8000 WHERE id = ? AND balance >= 8000 and checking the affected row count. Fixed ordering also prevents deadlock when two transfers run in opposite directions between the same pair.
Partial update. If the debit lands and the credit does not, money disappears. The lock makes the pair atomic here. With persistence, both balance updates and both ledger rows must commit in one transaction, and the ledger is the source of truth for reconciliation. A nightly job can recompute each balance from the ledger and alert on drift.
Floats and overflow. Floats would make 0.1 + 0.2 style errors real money errors, so cents as integers. Python integers do not overflow, but in Ruby or Java I would use a 64-bit integer and reject amounts above a stated cap, since a balance near 9.22e18 cents is a bug, not a deposit.
What I would add next for a Shopify style payments context: a double entry ledger as the permanent record with balances as a derived cache, idempotency keys required on every mutating endpoint, and an explicit pending state for transfers that need external settlement, such as a payout to a merchant bank account, where the debit is reserved immediately and the credit completes asynchronously.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Design a webhook delivery system with retries, exponential backoff, idempotency, ordering guarantees and dead-letter queues?
Reported in Shopify Software Engineer Interview Guide
The 90-second answer
A merchant app subscribes to a topic, say orders/create for a shop. When an order changes, we publish an event once and deliver it to every subscription. Delivery is at-least-once, never exactly-once, because the network can drop an acknowledgement after the receiver has processed the request. So the design rests on three promises we can keep: every event carries a stable id the receiver can deduplicate on, retries follow a bounded backoff schedule, and ordering is guaranteed only within one subscription, not across shops or topics.
Core flow
The order write and the event insert share one database transaction. That outbox pattern avoids the classic gap where the order commits and the webhook is lost, or the webhook fires for an order that rolled back. A dispatcher polls or is notified of due outbox rows, claims them with a lease so two workers do not send the same row at once, and posts the payload.
Each delivery carries headers a receiver can verify and deduplicate:
X-Shopify-Topic: orders/create
X-Shopify-Shop-Domain: example.myshopify.com
X-Shopify-Webhook-Id: wh_01J8EXAMPLE
X-Shopify-Event-Id: evt_01J8EXAMPLE
X-Shopify-Hmac-Sha256: <base64 hmac of raw body>The receiver recomputes the HMAC over the raw bytes with the app secret and rejects mismatches before parsing JSON. Signing the raw body matters. Re-serialising JSON changes whitespace and key order and breaks the signature.
Retries and backoff
Retry only on failures that can clear: timeouts, connection errors, 408, 429, and 5xx. A 400, 401, 403, or 404 from the endpoint will fail the same way on attempt ten, so those go straight to the dead-letter queue. A 429 or 503 may carry Retry-After, and we honour it over our own schedule.
Hypothetical schedule for one subscription, with full jitter applied in code:
| Attempt | Delay before it | Cumulative elapsed |
|---|---|---|
| 1 | immediate | 0 |
| 2 | 5 min | 5 min |
| 3 | 15 min | 20 min |
| 4 | 1 h | 80 min |
| 5 | 4 h | 5.3 h |
| 6 | 12 h | 17.3 h |
| 7 | 24 h | 41.3 h |
# Ruby, checked against Ruby 3.3
def next_delay_seconds(attempt)
base = 300 # 5 minutes
cap = 86_400 # 24 hours
exp = base * (2**(attempt - 1))
[cap, exp].min * (0.5 + rand) # jitter in [0.5, 1.5)
endJitter spreads retries from thousands of shops after an outage instead of releasing them in lockstep. Without it, recovery creates a second outage at the receiver. The cap stops a permanently broken endpoint from consuming a worker forever, and the total window, about 48 hours here, bounds how stale an event can be when it finally lands.
Idempotency
Because a timeout can hide a success, the same event may arrive twice. We send the same X-Shopify-Event-Id on every attempt. The receiver stores seen event ids for at least as long as our retry window, 48 hours in this example, and returns 200 for a duplicate without reprocessing. That makes the receiver's handler idempotent even though delivery is not. On our side, the delivery row is the idempotency record: one row per event per subscription, updated in place, so a retry never creates a second logical delivery.
Ordering
Global ordering is neither possible nor needed. Two shops have no causal relationship, and forcing one queue through all deliveries would make one slow app block every other shop. We assign a monotonically increasing sequence per subscription, meaning per shop plus topic plus app endpoint, and deliver in that order for that subscription. If delivery 12 is retrying and delivery 13 is ready, we hold 13 until 12 succeeds or exhausts retries. That preserves orders/create before orders/updated for the same order at the same app. The cost is head-of-line blocking: one failing event stalls later events for that subscription. The dead-letter step is what releases the block, after the retry window, so a poison event cannot stall a shop indefinitely.
Dead-letter queue and operations
After the final attempt, or immediately on a terminal status, the delivery moves to a dead-letter queue with the event id, subscription, last status, response snippet, and attempt history. Merchants and app developers see failed deliveries in a dashboard and can inspect, replay, or discard them. Replay reuses the original event id, so a receiver that already processed it will deduplicate it. Alerts fire on dead-letter rate per app, not per event, since a single broken deploy can produce thousands of failures in minutes. Detection for silent loss is simpler: compare outbox rows older than the retry window with no terminal state. Any row in that state means the dispatcher or lease logic has a bug, and that check runs continuously rather than waiting for a merchant to complain.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Design a photo upload and review service for merchant product photography with reshoot requests?
Reported in Shopify interview process 2026: rounds, questions and tips
The 90-second answer
Split it into three planes that fail independently: upload, processing, and review. The merchant uploads to object storage through a presigned URL, never through the app server. A worker then validates, strips metadata, and generates derivatives. Only after that does a photo become reviewable. Review is a state machine on the photo, not a boolean flag, and a reshoot request creates a new photo attempt linked to the old one instead of overwriting it.
That separation matters at Shopify scale. A 5 MB phone photo pushed through a Rails or Go request would tie up a server for seconds and lose the upload on a timeout. A presigned PUT goes straight to S3 or GCS, the client retries the same object key, and the server only learns about completion through a callback or a HEAD check.
Upload contract
POST /products/{id}/photo-uploads with an Idempotency-Key returns an upload session: upload_id, object_key, presigned_url, expires_at in 15 minutes, and limits. The client PUTs directly, then calls POST /photo-uploads/{id}/complete with the byte count and checksum. The API HEADs the object, checks size against a 25 MB cap and content type against JPEG, PNG, and WebP, then enqueues processing. If the client never completes, a sweeper deletes orphaned objects after 24 hours. Without that sweeper, a hypothetical 2% abandon rate on 100,000 uploads a day leaves 2,000 orphaned 5 MB objects daily, about 10 GB a day and a growing bill for files nobody can reference.
// Go, checked against Go 1.22. Transition guard for review.
func canTransition(from, to PhotoStatus) bool {
allowed := map[PhotoStatus][]PhotoStatus{
StatusUploaded: {StatusProcessing, StatusRejected},
StatusProcessing: {StatusInReview, StatusRejected},
StatusInReview: {StatusApproved, StatusReshootRequested, StatusRejected},
StatusReshootRequested: {StatusUploaded}, // new attempt, not this row
}
for _, s := range allowed[from] {
if s == to { return true }
}
return false
}Processing
The worker downloads the original to ephemeral disk, runs antivirus and format sniffing (never trust the extension), strips EXIF and GPS, checks dimensions, and writes derivatives: a 2048px original for zoom, 800px and 400px for listings, and a 200px thumbnail. Each derivative gets its own object key derived from the photo ID, so a CDN cache key never changes meaning. Processing is idempotent on photo_id: re-running overwrites the same keys. If the worker dies mid-job, the photo stays in processing with a lease timestamp, and a reaper requeues it after 5 minutes. That beats a distributed transaction here. The object store and the database cannot commit atomically, so the database is the source of truth and the worker reconciles toward it.
Review and reshoot
| State | Meaning | Who can move it |
|---|---|---|
uploaded | bytes landed, not yet checked | system |
processing | scan and derivatives running | worker |
in_review | derivatives ready, awaiting a human or model check | reviewer |
approved | attached to a product slot, live on CDN | reviewer |
reshoot_requested | reviewer asked for a new shot, with a reason code | reviewer |
rejected | policy or quality failure, terminal for this attempt | reviewer or scanner |
A reshoot request does not mutate the old photo. It creates a new photo_upload with supersedes_id pointing at the old one, resets it to uploaded, and keeps the old one readable for comparison. The product slot keeps pointing at the last approved photo until the replacement is approved, so a storefront never shows a gap. Reviewers see side by side: old approved shot, new attempt, and the reason code from the last request, such as too_dark, background_clutter, or wrong_angle. Reason codes matter because merchants act on them and because you can later measure whether a code actually predicts a second reshoot.
Concurrency is the usual trap. Two reviewers open the same in_review photo. The approve call carries the photo's version as If-Match. The first commit bumps the version. The second gets 409 and reloads instead of silently overwriting the first decision. The same guard protects the merchant uploading a replacement while a reviewer is mid-review.
Failure modes I would name in the loop
A client PUT succeeds but the complete call times out. The retry with the same idempotency key returns the existing upload session, and a HEAD check confirms the bytes, so no duplicate photo appears. A derivative write succeeds but the database update fails. The photo stays in processing, the reaper requeues, and the idempotent worker rewrites the same keys. A CDN serves a stale approved image after a slot swap. The fix is a new photo ID per attempt, so the CDN URL changes and there is nothing stale to purge. A merchant uploads a HEIC file the pipeline cannot decode. The scanner rejects it with a specific code and the merchant sees unsupported_format instead of a generic failure, which cuts support tickets.
I would close by stating what I would not build: no direct uploads through the app tier, no in-place overwrite of an approved photo, and no synchronous image processing inside the request. Each of those looks simpler in a diagram and costs you under load.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Implement an in-memory file system with list, change directory, add and remove?
Reported in Shopify interview process 2026: rounds, questions and tips
The 90-second answer
Model the filesystem as a tree. Each node is either a directory with named children or a file with no children. Keep two pointers: root, which never moves, and cwd, the current working directory. Every operation resolves a path to a node, then acts on that node.
Path resolution does most of the work. Split on /, start from root for an absolute path or from cwd for a relative one, skip ., pop on .., and walk down one child at a time. If a component is missing, the path does not exist. If a component is a file but more components remain, the path is invalid. ls, cd, add and remove then become small wrappers around that walk, which keeps their behaviour consistent.
# Python 3.11
from dataclasses import dataclass, field
@dataclass
class Node:
name: str
is_dir: bool
children: dict[str, "Node"] = field(default_factory=dict)
parent: "Node | None" = None
class FileSystem:
def __init__(self):
self.root = Node("/", True)
self.cwd = self.root
def _resolve(self, path: str) -> Node:
node = self.root if path.startswith("/") else self.cwd
for part in path.split("/"):
if part in ("", "."):
continue
if part == "..":
if node.parent is not None:
node = node.parent
continue
if not node.is_dir:
raise NotADirectoryError(path)
if part not in node.children:
raise FileNotFoundError(path)
node = node.children[part]
return node
def ls(self, path: str | None = None) -> list[str]:
node = self.cwd if path is None else self._resolve(path)
if not node.is_dir:
raise NotADirectoryError(path or ".")
return sorted(node.children)
def cd(self, path: str) -> None:
node = self._resolve(path)
if not node.is_dir:
raise NotADirectoryError(path)
self.cwd = node
def add(self, path: str, is_dir: bool = False) -> None:
parent_path, _, name = path.rstrip("/").rpartition("/")
if not name or name in (".", ".."):
raise ValueError(f"bad path: {path}")
parent = self._resolve(parent_path or "/")
if not parent.is_dir:
raise NotADirectoryError(parent_path)
if name in parent.children:
raise FileExistsError(path)
parent.children[name] = Node(name, is_dir, parent=parent)
def remove(self, path: str) -> None:
node = self._resolve(path)
if node is self.root:
raise ValueError("cannot remove root")
# Refuse to strand cwd inside a deleted subtree.
cur = self.cwd
while cur is not None:
if cur is node:
raise ValueError("cannot remove cwd or its ancestor")
cur = cur.parent
del node.parent.children[node.name]
node.parent = NoneWorked trace
| Call | Result | Why |
|---|---|---|
add("/docs", is_dir=True) | ok | parent / exists, docs is new |
add("/docs/a.txt") | ok | parent /docs is a directory |
cd("docs") | cwd = /docs | relative path starts at / |
ls() | ["a.txt"] | lists cwd, sorted |
add("../b.txt") | ok, creates /b.txt | .. from /docs is / |
cd("a.txt") | NotADirectoryError | target exists but is a file |
remove("/docs") | ValueError | cwd is inside the subtree |
cd("/") then remove("/docs") | ok | cwd no longer inside it |
ls("/") | ["b.txt"] | subtree gone with its parent link |
Decisions worth stating out loud
Duplicate add raises FileExistsError instead of overwriting. Overwriting a directory silently would delete its children, and overwriting a file hides caller bugs. If the interviewer wants overwrite semantics, that is a one line change, but the default should be explicit.
remove on a directory deletes the whole subtree by dropping the parent link, since children are only reachable through it. That is O(1) for the unlink itself. The cost is that a caller holding a reference to a child node keeps stale data alive, which is fine for an in-memory exercise and worth naming if asked about memory.
Removing cwd or an ancestor raises rather than resetting to /. Resetting is also defensible, but a dangling cwd pointing at a detached node is the classic bug here, so refusing makes the invariant obvious: cwd is always reachable from root.
Complexity and limits
Resolution is O(depth), ls is O(k log k) for k children because of the sort, add and remove are O(depth) plus O(1) for the dict operation. Memory is O(total nodes). This version is single threaded. If several threads share one instance, guard each public method with a lock, because _resolve and the mutation in add are not atomic together. For a Shopify scale follow up, the same tree maps onto a database table with parent_id, and ls becomes an indexed query on parent_id instead of a dict scan.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Build an automatic refund decision system from written requirements?
Reported in Shopify interview process 2026: rounds, questions and tips
The 90-second answer
I would start by asking what the written requirements actually decide, because "automatic refund" hides three different systems: eligibility, amount, and fraud or abuse checks. I would ask for the source document, the refund window, whether partial refunds are allowed, who can override, and what happens when the order is already fulfilled, cancelled, or charged back. If I have to proceed in the interview, I state my assumptions: refunds are decided per order line, money is integer minor units, every decision is recorded against a versioned policy, and a human queue takes anything the rules cannot settle.
Then I would separate parsing the requirements from executing them. The document becomes a decision table that a merchant or policy owner can review. The service evaluates that table deterministically, writes the decision and its inputs to an audit record, and only then calls the payment provider. That order matters. If the process crashes after calling the provider but before recording the decision, a retry must not pay twice.
Turning prose into rules
A typical requirement set, with figures I would confirm with the interviewer, looks like this:
| Rule | Condition | Outcome |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| R1 | now - delivered_at <= 30 days | eligible |
| R2 | order not already refunded in full | eligible |
| R3 | requested amount <= total - refunded_so_far | amount accepted |
| R4 | fraud_score >= 0.85 or chargeback open | manual review |
| R5 | digital goods, already downloaded | reject unless policy exception |
Worked trace on an order of 12,999 cents, delivered 12 days ago, with 2,000 cents already refunded:
| Request | Checks | Decision |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| 10,999 cents | R1 pass, R2 pass, R3: 10,999 <= 10,999 pass, R4 clear | approve 10,999 |
| 11,000 cents | R3 fails by 1 cent | reject exceeds_remaining_balance |
| 5,000 cents, fraud score 0.91 | R4 triggers | queue for review, no provider call |
| same request retried with same idempotency key | key found in store | replay stored decision, no second charge |
Implementation sketch
In Ruby, the core stays boring on purpose. Rules are data, the evaluator is pure, and side effects happen in one place.
# Ruby 3.2, checked against the interview sketch
class RefundDecider
POLICY_VERSION = "2026-01"
def decide(order:, request:, policy:)
return reject(:outside_window) unless within_window?(order, policy)
return reject(:already_refunded) if order.refunded_cents >= order.total_cents
remaining = order.total_cents - order.refunded_cents
return reject(:exceeds_remaining_balance) if request.amount_cents > remaining
return review(:high_fraud_score) if request.fraud_score >= policy.fraud_threshold
approve(request.amount_cents, POLICY_VERSION)
end
endThe caller wraps this in a transaction: insert a refund record in pending with a unique idempotency key, reserve the amount against the order balance, call the provider with that key, then mark the record succeeded with the provider reference. A database constraint on (order_id, idempotency_key) plus a check constraint that cumulative refunds never exceed the order total gives a second line of defence if two workers race.
Failure modes I would name
Duplicate payment on retry is the main one. Detection is a nightly reconciliation between refund records and provider payouts, plus an alert when sum(refunded_cents) > total_cents for any order, which the constraint should make impossible. A second failure is policy drift: the document changes but the code does not. Storing policy_version and the full input snapshot on every decision makes old decisions reproducible and lets me replay a cohort after a rule change. A third is a race with fulfilment or a chargeback arriving mid-refund. I would re-check order state inside the same transaction that reserves the amount, and treat a chargeback as a terminal state that cancels pending refunds. Rounding is a quieter bug: I keep amounts in minor units end to end and never convert through floats, since 12,999 cents split across lines can drift by a cent otherwise.
For scale at Shopify, the decision path is cheap, a few indexed reads and one write, so the bottleneck is the provider call. I would keep provider calls off the request path where the product allows it, return the pending refund resource, and let a worker reconcile its status. That keeps p99 latency for the API call in tens of milliseconds instead of inheriting provider latency.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Find the shortest path through an array or table?
Reported in Shopify Software Engineer interview experience (December 2025)
The 90-second answer
I would clarify the grid before coding. Is movement 4-directional or 8-directional? Are some cells blocked? Is every step the same cost, or do cells carry weights? Is there one start and one target, or many targets? Those answers pick the algorithm.
For the common case, an unweighted grid with blocked cells, breadth-first search gives the shortest path. BFS expands cells in order of distance from the start, so the first time it reaches the target it has found a path with the fewest steps. I would store each cell's parent when I first visit it, then walk parents back from the target to reconstruct the path.
from collections import deque
def shortest_path(grid, start, goal):
rows, cols = len(grid), len(grid[0])
if grid[start[0]][start[1]] == 1 or grid[goal[0]][goal[1]] == 1:
return None
queue = deque([start])
parent = {start: None}
while queue:
r, c = queue.popleft()
if (r, c) == goal:
break
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
if grid[nr][nc] == 0 and (nr, nc) not in parent:
parent[(nr, nc)] = (r, c)
queue.append((nr, nc))
if goal not in parent:
return None
path, node = [], goal
while node is not None:
path.append(node)
node = parent[node]
return path[::-1]Here 1 means blocked and 0 means free. Time is O(rows * cols) because each cell is enqueued once, and memory is the same order for the queue and parent map.
Worked trace
Grid below, S is (0,0), G is (2,2), # is blocked. BFS visits in rings of increasing distance.
| Step | Cell dequeued | Newly visited |
|---|---|---|
| 0 | (0,0) | (1,0), (0,1) |
| 1 | (1,0) | (2,0) |
| 2 | (0,1) | (0,2) |
| 3 | (2,0) | (2,1) |
| 4 | (0,2) | (1,2) |
| 5 | (2,1) | none, (2,2) is next |
| 6 | (1,2) | (2,2) |
| 7 | (2,2) | target reached, stop |
Parent links give (0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2), length 5 cells, 4 moves. No shorter route exists because every cell at distance 3 was dequeued before any cell at distance 4, and the target first appears at distance 4.
When BFS is the wrong tool
| Situation | Use instead | Why |
|---|---|---|
| Every step costs 1, blocked cells only | BFS | Optimal, simplest, O(V+E) |
| Cells have different costs, for example terrain or congestion | Dijkstra | BFS would treat a costly cell as cheap and return a longer-cost path |
| Large grid, single target, good distance estimate available | A* with Manhattan distance | Prunes cells that cannot improve on the current best, often visits far fewer cells |
| Many queries on a static grid | Precompute, or bidirectional BFS | Bidirectional search meets in the middle and cuts the explored area sharply |
Dijkstra replaces the queue with a priority queue keyed by accumulated cost. A* adds a heuristic, the Manhattan distance |r - gr| + |c - gc| for 4-directional movement, to that key. Both need the heuristic to never overestimate the true remaining cost, or A* can return a suboptimal path.
Failure modes I would name in the interview
Unreachable target: the queue empties and goal never enters parent, so I return None rather than an empty list, which callers often misread as a zero-length path. Blocked start or goal: check before the loop, as in the code above. Memory on a huge grid: a 10,000 by 10,000 grid has 100 million cells, so the parent dict alone can exceed RAM. There I would switch to bidirectional BFS, store parents as arrays of ints instead of tuples, or run A* to explore less. Diagonal movement changes the neighbour list and the heuristic, and it also allows cutting corners between two blocked orthogonal cells unless the spec forbids it. I would ask which rule applies instead of assuming.
In a Shopify setting, say routing a picker through a warehouse aisle grid, I would expect weights to appear quickly, because aisle congestion and one-way aisles make step counts a poor proxy for time. That pushes the design to Dijkstra or A* with edge weights, and to re-running the search when the grid changes rather than caching a stale path.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Why do you want this job?
Reported in Shopify Software Engineer interview experience (December 2025)
The 90-second answer
I want to work on commerce infrastructure at a scale my current job cannot give me, and I want the work judged by merchant outcomes. I build order and payment flows for one retail brand now. We have one merchant, one tax setup and traffic we can predict a month ahead. That taught me correctness, but it hides the hard part. At Shopify, the same checkout code has to serve merchants with different apps, fulfilment rules and payment providers, and it has to hold during Black Friday and Cyber Monday peaks. I want to learn how to make that work without special cases piling up in the core.
The second reason is the constraint. Shopify does not compete with its merchants for the customer. That changes engineering choices. A breaking API change is not an internal refactor, it is a cost pushed onto thousands of small businesses. I prefer that discipline to a job where I can ship fast because only my own team feels the breakage.
The trade-off I have weighed
This move costs me things I value now. I have end to end ownership of a small service and I can change its contract in a week. At Shopify, I expect slower decisions, more review layers and work on a platform I do not control alone. If I wanted maximum autonomy or greenfield projects, staying would be the better choice. I am choosing the opposite trade. I would rather have less ownership of a larger system, with stricter compatibility and observability, than full ownership of a system that never has to support a merchant I did not design for.
| Dimension | Current role | Shopify, as I understand it |
|---|---|---|
| Merchant model | One brand, rules coded in the service | Many merchants, customisation pushed to extensions and apps |
| Peak load | Predictable, we freeze deploys before campaigns | BFCM surge, deploys and capacity planned months ahead |
| API change | Coordinate with one client team | Version, deprecate and support third party clients for years |
| Feedback loop | I see our own sales dashboard | Impact shows up as merchant support tickets and churn, slower and noisier |
That last row is a real risk. I will not get the quick feedback I get now, so I need to learn to read merchant signals instead of assuming a clean deploy means success.
What could go wrong, and how I would catch it
The first failure mode is ramp. I have not worked in a monorepo at this size or on call for a system where a bad deploy affects merchants I cannot call directly. If I underestimate that, my first months become a drag on the team. I would catch it early by asking for a small, well scoped change first, pairing on on call shadows before taking a rotation, and reading past BFCM incident reviews before I touch checkout code.
The second failure mode is misjudging the merchant first constraint. A candidate from a single tenant system, me included, tends to solve a merchant request by adding a branch in the core. That looks fast in review and creates the exact coupling Shopify is trying to remove with extensible checkout. I would catch it by asking in design review who else pays for this branch, and whether it belongs in an extension point, a config or the core.
The third is stack mismatch. My experience is strongest in the services I have run, not in Shopify's current stack. I am not going to claim fluency I do not have. My plan is to be explicit about that in the loop, show the idempotency and retry work I have done in concrete terms, and ask the team what it expects a new hire to learn in the first quarter. If the answer is that the role needs immediate depth in an area I lack, that is information I want before I accept, not after.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Build a simple shopping cart class that supports adding items, removing items, applying a discount code, and computing the total?
Reported in 10 Shopify Software Engineer (New Grad) Interview Questions (2026)
The 90-second answer
I would model the cart as a map from SKU to quantity, keep money in integer cents, and keep discount logic separate from line items. Adding an existing SKU increments its quantity instead of creating a duplicate line. Removing decrements, and deletes the line at zero. Applying a code stores the code on the cart and validates it at total time, so an expired or inapplicable code fails loudly instead of silently changing the price.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Item:
sku: str
name: str
price_cents: int # never float for money
@dataclass
class Discount:
code: str
kind: str # "percent" or "fixed"
value: int # percent 0-100, or cents for fixed
min_subtotal_cents: int = 0
expires_at: int | None = None # epoch seconds
class Cart:
def __init__(self, now: int):
self._lines: dict[str, tuple[Item, int]] = {} # sku -> (item, qty)
self._discount: Discount | None = None
self._now = now
def add(self, item: Item, qty: int = 1) -> None:
if qty <= 0:
raise ValueError("qty must be positive")
if item.sku in self._lines:
existing, n = self._lines[item.sku]
self._lines[item.sku] = (existing, n + qty)
else:
self._lines[item.sku] = (item, qty)
def remove(self, sku: str, qty: int = 1) -> None:
if sku not in self._lines:
raise KeyError(sku)
item, n = self._lines[sku]
if qty >= n:
del self._lines[sku]
else:
self._lines[sku] = (item, n - qty)
def apply_discount(self, discount: Discount) -> None:
if discount.expires_at is not None and discount.expires_at < self._now:
raise ValueError("discount expired")
self._discount = discount # one active code; replace, do not stack silently
def subtotal_cents(self) -> int:
return sum(item.price_cents * qty for item, qty in self._lines.values())
def total_cents(self) -> int:
subtotal = self.subtotal_cents()
if self._discount is None:
return subtotal
d = self._discount
if subtotal < d.min_subtotal_cents:
raise ValueError("discount minimum not met")
if d.kind == "percent":
discount_cents = subtotal * d.value // 100
else:
discount_cents = min(d.value, subtotal)
return subtotal - discount_centsWorked trace
| Step | Call | Cart state | Total |
|---|---|---|---|
| 1 | add(Item("mug", "Mug", 1200), 2) | mug x2 | 2400 |
| 2 | add(Item("mug", "Mug", 1200), 1) | mug x3, one line | 3600 |
| 3 | add(Item("tee", "Tee", 2500), 1) | mug x3, tee x1 | 6100 |
| 4 | apply_discount(Discount("SAVE10", "percent", 10)) | code stored | 5490 |
| 5 | remove("mug", 3) | tee x1 | 2250 |
Step 5 shows why validation at total time matters. The 10% code still applies to the new subtotal of 2500, giving 2250. If the code had a 5000 minimum, total_cents() would raise instead of returning a stale discounted price from step 4.
Decisions an interviewer will probe
Price changes: storing the Item snapshot in the line means a later catalogue price change does not mutate an open cart. At checkout, reprice against the catalogue and surface the diff. That matches how Shopify treats a cart as a snapshot and checkout as the point of truth.
Rounding: integer division truncates. For percent discounts I would state the rounding rule in the contract, for example round half up per line rather than on the subtotal, because per-line rounding is what tax engines and refunds can reproduce line by line. A fixed discount larger than the subtotal is capped at the subtotal, so the total never goes negative.
Failure modes: removing a SKU that is not present raises KeyError rather than no-opping, so a client bug that double-submits a remove is visible in logs. Applying a second code replaces the first. If the product allows stacking, I would make that an explicit list with an ordering rule and a cap, not an accident of repeated calls.
Tests I would write before calling it done: merge on duplicate add, remove to exactly zero deletes the line, remove more than present deletes the line, expired code rejected, minimum not met rejected at total time, fixed discount capped, and empty cart totals zero with or without a code.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Given a string of parentheses, brackets, and braces, determine if it is balanced?
Reported in 10 Shopify Software Engineer (New Grad) Interview Questions (2026)
The 90-second answer
Use a stack. Scan left to right, push every opening bracket, and on a closing bracket pop and check that the popped opener matches. At the end the string is balanced only if the stack is empty. That is O(n) time and O(n) space, and it handles nesting correctly because the most recent unmatched opener is always the one that must close next.
I will assume the input contains only (), [], and {}. Empty string returns true. If the real input can contain other characters, I would ignore them by default and say so, rather than failing the whole string.
# Ruby 3.3
def balanced?(s)
pairs = { ')' => '(', ']' => '[', '}' => '{' }
stack = []
s.each_char do |c|
if pairs.key?(c)
return false if stack.pop != pairs[c]
elsif '([{'.include?(c)
stack.push(c)
end
end
stack.empty?
endstack.pop on an empty stack returns nil in Ruby, so a leading closer like ) fails the comparison and returns false without a special case. The early return also matters: once a mismatch is found, no later character can repair it.
Worked trace
For {[()]}:
| Char | Action | Stack after | Result |
|---|---|---|---|
{ | push | { | continue |
[ | push | {[ | continue |
( | push | {[( | continue |
) | pop, matches ( | {[ | continue |
] | pop, matches [ | { | continue |
} | pop, matches { | empty | balanced |
For ([)], the trace diverges at the third character: ) pops [, the expected opener is (, so the function returns false immediately. A simple count of openers versus closers would miss this, because both counts are equal.
| Approach | Handles ([)] | Handles }{ | Extra space |
|---|---|---|---|
| Count openers and closers per type | No, counts match | No, counts match | O(1) |
| Stack of openers | Yes, order is checked | Yes, first pop is empty | O(n) worst case |
| Recursion on nested substrings | Yes | Yes | O(n) call stack, risks overflow on deep input |
Follow-ups I would expect
If the string is very long, the stack is the cost. A string of 10 million openers needs 10 million stack entries, so I would stream characters instead of loading the whole string and, for untrusted input, cap depth and reject beyond that cap rather than growing memory without bound. Recursion has the same depth problem in a less visible form, which is why I would not use it here.
If the question changes to finding the longest balanced substring or the minimum insertions to balance, the stack idea still applies but the bookkeeping changes. I would clarify which variant is being asked before coding, since the single pass above answers only the yes or no version. Testing would cover the empty string, a single pair, a leading closer, interleaved types, and a trailing opener left on the stack, since each exercises a different return path in the code above.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Find the first non-repeating character in a string?
Reported in Shopify Software Engineer interview experience (June 2024)
The 90-second answer
I would clarify two things first: case sensitivity, and what to return when every character repeats. Assuming case-sensitive matching and nil for no answer, I do two passes. First pass counts each character. Second pass walks the string in order and returns the first character whose count is 1.
# Ruby 3.x
def first_non_repeating(str)
counts = Hash.new(0)
str.each_char { |c| counts[c] += 1 }
str.each_char { |c| return c if counts[c] == 1 }
nil
end
first_non_repeating("swiss") # => "w"
first_non_repeating("aabb") # => nil
first_non_repeating("") # => nilThat is O(n) time and O(k) space, where k is the number of distinct characters. For ASCII input k is at most 256, so the map stays tiny even on a long string.
Worked trace
For "swiss":
| Step | Character | Count after step |
|---|---|---|
| 1 | s | s:1 |
| 2 | w | s:1, w:1 |
| 3 | i | s:1, w:1, i:1 |
| 4 | s | s:2, w:1, i:1 |
| 5 | s | s:3, w:1, i:1 |
Second pass checks s (count 3, skip), then w (count 1, return). The order matters. A single pass that returns the first character seen once so far would be wrong, because a later repeat can disqualify it.
Why not the alternatives
| Approach | Time | Space | Problem |
|---|---|---|---|
| Brute force: for each character, scan the rest | O(n^2) | O(1) | 10^6 characters means roughly 10^12 comparisons |
| Two-pass hash, as above | O(n) | O(k) | Needs a second pass, but each pass is a simple scan |
| One pass storing first index plus count | O(n) | O(k) | Same complexity, slightly more bookkeeping, no real win |
The brute force version is fine for a string of length 20 in a take-home. It falls apart on a product description or a log line at Shopify scale, where strings can be megabytes. The hash version trades a small map for linear time, which is the right trade here.
Edge cases I would name in the interview
Empty string returns nil, not an error. All-repeating input like "aabb" also returns nil. Case sensitivity is a contract choice: "Aa" has two non-repeating characters under case-sensitive rules and zero under case-insensitive rules, so I would ask rather than guess.
Unicode is the subtle one. Ruby's each_char iterates by codepoint, so "é" written as e plus a combining accent counts as two characters. If the interviewer means user-visible characters, I would switch to grapheme clusters with str.scan(/\X/) and say so. For ASCII SKUs and handles, which is most of what we process internally, the distinction never comes up.
If the follow-up is a stream, where characters arrive one at a time and I must answer after each arrival, the same map works with a queue of candidates in first-seen order. I pop from the front while the front character's count exceeds 1. That keeps each step amortized O(1). The failure mode to watch is memory: on a stream over a large alphabet the map grows with distinct characters, so I would cap it or switch to a bounded structure if the stream is unbounded.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Solve a graph traversal problem using BFS or DFS?
Reported in Shopify Software Engineer interview experience (June 2026)
The 90-second answer
I would first pin down the graph shape, because that decides the algorithm. Is it directed or undirected, weighted or unweighted, and do I need shortest path, reachability, cycle detection, or a full traversal order? For an unweighted graph where I need the shortest path or level order, I use BFS. For reachability, connected components, cycle detection, or topological order, I use DFS. Both run in O(V + E) time with an adjacency list, and both need a visited set or cycles will loop forever.
Assume an adjacency list, dict[node, list[node]], which is the usual interview input and gives O(1) neighbour lookup. If the input is an edge list, I build that dict first in O(E). If nodes are dense and numbered from 0, an adjacency matrix works, but it costs O(V^2) space, so I would not pick it for a sparse merchant or order graph.
from collections import deque
def bfs_shortest_path(graph, start, goal):
if start == goal:
return [start]
queue = deque([start])
visited = {start}
parent = {}
while queue:
node = queue.popleft()
for nxt in graph.get(node, []):
if nxt in visited:
continue
visited.add(nxt)
parent[nxt] = node
if nxt == goal:
path = [goal]
while path[-1] != start:
path.append(parent[path[-1]])
return path[::-1]
queue.append(nxt)
return [] # goal unreachable
def dfs_reachable(graph, start):
seen, stack = set(), [start]
while stack:
node = stack.pop()
if node in seen:
continue
seen.add(node)
stack.extend(graph.get(node, []))
return seenBFS stores a parent map only for nodes on the frontier path, so reconstruction is O(path length). DFS with an explicit stack avoids Python recursion limits, which matter on a graph with 100k nodes. Recursive DFS is shorter to write, but I would flag the recursion depth risk in an interview and switch to iterative.
Worked trace. Graph: A -> B, C, B -> D, C -> D, D -> E. BFS from A to E:
| Step | Dequeued | Enqueued | Visited after step |
|---|---|---|---|
| 1 | A | B, C | A, B, C |
| 2 | B | D | A, B, C, D |
| 3 | C | (D already visited) | A, B, C, D |
| 4 | D | E | A, B, C, D, E |
| 5 | E | goal found | path A, B, D, E |
That path has 3 edges. BFS guarantees it is shortest because it expands nodes in nondecreasing distance from A. DFS might return A, C, D, E first, also length 3 here, but on a graph with a long detour it can return a much longer path and give no shortest guarantee.
| BFS | DFS | |
|---|---|---|
| Data structure | queue (FIFO) | stack (LIFO) |
| Shortest path, unweighted | yes | no |
| Memory | O(V) worst case, holds a whole level | O(V) worst case, holds one path plus frontier |
| Best fit | level order, shortest path, bipartite check | components, cycles, topological sort, maze reachability |
| Weighted shortest path | no, use Dijkstra | no, use Dijkstra |
Failure modes I would name. Disconnected graph: BFS or DFS from one start never visits other components, so I loop over all nodes and start a new traversal for each unvisited one. Cycles: the visited set handles undirected cycles, but directed cycle detection needs a recursion stack or colour marking (white, grey, black), not just visited, or a cross edge looks like a back edge. Self loops and duplicate edges: the visited check before enqueue covers both. Missing keys: graph.get(node, []) stops a KeyError when a node appears only as a target, common with Shopify order or fulfilment graphs where a warehouse has no outgoing edges.
If the interviewer then says the edges have weights, I stop and switch to Dijkstra with a heap, O(E log V), and note that BFS would silently return a wrong answer. That distinction is usually what they are probing for.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18How would the solution change if the graph contained cycles?
Reported in Shopify Software Engineer interview experience (June 2026)
The 90-second answer
Assume the original solution was a DAG solution: topological order, DP over predecessors, or a DFS that assumes it can finish a node before revisiting it. Cycles break all three assumptions. Traversal still works if I add visited state, but ordering and DP do not. I would first ask what the graph represents and what the task needs, because the fix depends on that. For reachability or traversal, a visited set is enough. For ordering or counting paths, I would collapse each strongly connected component into one node, which turns the graph back into a DAG, then run the original algorithm on that condensation. For shortest paths, I would switch from DAG DP or Dijkstra to Bellman-Ford and explicitly check for negative cycles.
What breaks, concretely
A recursive DFS written for a DAG often marks a node visited only when it finishes. On A -> B -> A, it recurses forever. Marking on entry fixes traversal, but it hides the cycle. I need two colours, or an explicit stack state: grey means on the current path, black means fully explored. Encountering a grey neighbour is a back edge and proves a cycle. Encountering a black neighbour is safe.
# Python 3.11, iterative to avoid recursion limits on deep graphs
def find_cycle(graph):
WHITE, GREY, BLACK = 0, 1, 2
colour = {n: WHITE for n in graph}
for start in graph:
if colour[start] != WHITE:
continue
stack = [(start, iter(graph[start]))]
colour[start] = GREY
while stack:
node, neighbours = stack[-1]
advanced = False
for nxt in neighbours:
if colour[nxt] == GREY:
return nxt # back edge: cycle through nxt
if colour[nxt] == WHITE:
colour[nxt] = GREY
stack.append((nxt, iter(graph.get(nxt, []))))
advanced = True
break
if not advanced:
colour[node] = BLACK
stack.pop()
return NoneThat runs in O(V + E) time and O(V) extra space. Recursion would use the same space but risks a RecursionError around 1,000 frames in CPython, which matters for a dependency graph with a long chain of merchant customisations.
| Task | DAG approach | With cycles |
|---|---|---|
| Visit every node once | DFS/BFS | Same, with visited on entry |
| Topological order | Kahn or DFS postorder | Impossible for nodes in a cycle; order SCCs instead |
| Count paths, DP over predecessors | Process in topo order | Diverges or undercounts; infinite paths if a cycle is reachable |
| Shortest path, non-negative weights | Dijkstra O((V+E) log V) | Still valid, cycles do not break it |
| Shortest path, negative weights | Not applicable | Bellman-Ford O(VE), then one extra pass to detect a negative cycle |
| Detect a cycle | Side effect of topo sort | Tarjan or Kosaraju SCC, O(V+E) |
Condensation, the general fix
Tarjan's algorithm finds strongly connected components in one DFS pass. Contract each component to a single supernode and every edge between components now points one way. The result is a DAG by construction, so the original topo sort, DP, or scheduling logic runs unchanged on the components. Inside a component, I report the cycle explicitly instead of pretending an order exists. At Shopify scale, say a graph of app dependencies or fulfilment steps with 50,000 nodes and 200,000 edges, Tarjan stays linear where a naive all-pairs check would not.
Failure modes I would name
A self-loop is a cycle of length one and is easy to miss if the code only checks neighbours already on the stack through another node. A negative cycle reachable from the source makes shortest path undefined, not just slow, and Bellman-Ford must surface that rather than return a number. Finally, if the graph is directed in the problem but stored as undirected, every edge looks like a two-node cycle, so I would confirm direction before running any of this.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Design a library system from scratch, assuming nothing was in place?
Reported in Shopify Software Engineer interview experience (September 2024)
The 90-second answer
I would clarify scope first, then state my assumptions out loud. One branch or many, physical books only or ebooks too, and does the system handle money for fines. I will assume a single library network with multiple branches, physical copies, members, loans, holds and fines, and no existing data to migrate. That gives me four core entities and one rule that drives the design: a copy can be in exactly one state at a time, and every transition is recorded.
Data model
| Table | Key fields | Notes |
|---|---|---|
titles | id, isbn, title, author | One row per work, many copies |
copies | id, title_id, branch_id, barcode, status | Status: available, on_loan, held, lost |
members | id, email, card_status, fine_balance_cents | Blocked above a threshold |
loans | id, copy_id, member_id, checked_out_at, due_at, returned_at | Partial index on open loans |
holds | id, title_id, member_id, branch_id, queue_position, state | FIFO per title and branch |
Scale assumption, labelled as such: 50,000 titles, 200,000 copies, 20,000 members, 500 checkouts per minute at peak. That is a modest relational workload. Postgres handles it without sharding. The hot contention point is not total volume, it is two members checking out the last copy of the same title in the same second.
API surface
| Operation | Endpoint | Contract detail |
|---|---|---|
| search | GET /titles?q=…&cursor=… | Keyset pagination, returns available count per branch |
| checkout | POST /loans | Idempotency-Key required, body has copy_id, member_id |
| return | POST /loans/{id}/return | Creates hold offer if queue is non-empty |
| renew | POST /loans/{id}/renewal | Rejected if a hold exists on that title |
| place hold | POST /holds | Returns queue position, 202 if not first |
| pay fine | POST /payments | Amount in cents, idempotent like checkout |
The race that breaks naive implementations
Checkout must be a transaction that locks the copy row, checks eligibility, and inserts the loan. Two concurrent requests for the same copy then serialize on the row lock instead of both succeeding.
# Ruby, checked against a Rails 7 / Postgres setup
def checkout(copy_id:, member_id:, idempotency_key:)
ActiveRecord::Base.transaction do
copy = Copy.lock.find(copy_id)
member = Member.lock.find(member_id)
return Result.failure(:copy_unavailable) unless copy.available?
return Result.failure(:member_blocked) if member.blocked?
loan = Loan.create!(copy:, member:, due_at: 21.days.from_now)
copy.update!(status: :on_loan)
loan
end
endIdempotency matters here for a different reason than in payments. A self-checkout kiosk retries after a timeout and the member gets charged a fine for a book they never took. Storing idempotency_key -> loan_id for 24 hours and replaying the original response removes that class of complaint.
Loan lifecycle and failure modes
| From | To | Trigger | Guard |
|---|---|---|---|
available | on_loan | checkout | member not blocked, fine balance under 1,000 cents |
on_loan | held | return with waiting hold | hold expires after 3 days, then next member is offered |
held | on_loan | pickup checkout | only the offered member, within the window |
on_loan | available | return, no hold | copy inspected, damage flag optional |
| any | lost | marked lost after 30 days overdue | fine assessed once, loan closed |
Three failures I would name in the interview. First, a hold offer that nobody picks up: without an expiry job the copy sits in held forever, so a scheduled job advances the queue every hour and emits a webhook, hold.ready, that the notification service consumes. Second, clock and timezone drift on due dates: store due_at as a timestamp in UTC and compute the date at the branch, otherwise a book returned at 23:30 local time looks overdue. Third, fine disputes: never mutate fine_balance_cents in place, append to a fine_events ledger with a reason code, so a member can see exactly which loan produced which charge.
If the interviewer pushes on scale, my next step would be read replicas for search and a separate index for title search, not sharding the loan tables. If they push on multiple branches, copies already carry branch_id and holds are scoped per branch, so a member can only pick up where they placed the hold. That keeps the model intact while the deployment grows.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Design a flash sale system where inventory must be accurate to prevent overselling?
Reported in Interview Guides
The 90-second answer
I would treat inventory as a ledger in one primary database, not a cache. A flash sale fails when two requests both read "3 left" and both succeed. So every purchase path goes through a single atomic reservation against the SKU row, and the cache only serves the product page. If the database says no, the user gets sold out, even if a stale cache said otherwise.
Assume one sale, say 1,000 units of a hot SKU, 50,000 concurrent shoppers in the first minute, and checkout that can take 30 seconds. I need to hold stock during checkout without losing it if payment fails, and I need retries from the client to not create two orders.
The core mechanism
Keep three counters per SKU, updated in the same transaction: on_hand, held, and sold. Available is on_hand - held - sold, never stored separately, so it cannot drift from its inputs. A reservation does an atomic conditional update:
-- PostgreSQL, checked against 15/16 semantics
UPDATE inventory
SET held = held + 1
WHERE sku_id = $1
AND on_hand - held - sold >= 1
RETURNING sku_id;
-- No row returned means sold out. No read-then-write race.The reservation row is inserted in that same transaction, with idempotency_key, expires_at = now() + interval '120 seconds', and status held. A retry with the same key returns the existing reservation instead of decrementing again. Confirming the order flips the reservation to confirmed and moves the unit from held to sold in one transaction. Expiry is handled by a sweeper that flips expired held reservations to expired and decrements held, using SELECT ... FOR UPDATE SKIP LOCKED so multiple sweepers do not double-release.
Worked trace for the last unit, two requests in parallel:
| Time | Request | Transaction | Result |
|---|---|---|---|
| t0 | A reserves | held: 0 -> 1, reservation A inserted | 201, held |
| t0+5ms | B reserves | update matches 0 rows, available is 0 | 409 sold_out |
| t0+90s | A payment fails | reservation A to expired, held: 1 -> 0 | unit available again |
| t0+91s | C reserves | held: 0 -> 1, reservation C inserted | 201, held |
Where it breaks, and what I would watch
Hot row contention is the first problem. One row lock per reservation means a single SKU serialises at roughly the transaction rate of the primary, often a few thousand per second in practice. At 50,000 requests in 60 seconds that is fine in aggregate but the hot SKU queue will grow. I would shed load at the edge with a per-SKU queue or a short-lived in-memory gate that returns 429 before requests hit the database, and I would measure p99 reservation latency and lock wait time, not just throughput.
The second problem is the gap between hold and payment. A 120 second hold on 1,000 units with a 20% payment failure rate means about 200 units cycle back. If the sweeper lags by a minute, real buyers see sold out while stock sits held. I would alert on held older than the TTL and on sweeper lag, and I would make expiry lazy as well: the confirm path checks expires_at and rejects a late confirm instead of honouring it.
The third problem is Shopify specific. Inventory is shared across online store, POS, and other channels, and merchants adjust stock manually. Every adjustment, restock, and channel sale must go through the same counters, or the ledger lies. I would put all writes behind one inventory service with an audit log of every counter change, and reconcile sold against confirmed orders nightly. A cache, Redis or CDN, can show the sale badge and the remaining count for the product page, with a TTL of a few seconds, but it never authorises a purchase. When the cache and the database disagree, the database wins and the cache is invalidated on every reservation change for that SKU.
I would not shard the hot SKU across rows to gain write throughput unless the lock queue proved to be the bottleneck in a load test, because splitting counters makes the available calculation a sum across shards and reintroduces the race I removed. Accuracy first, then partition only with measured evidence.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Design and implement a word guessing game?
Reported in Shopify Software Engineer Interview Experience (2026) - Aced (formerly Exponent)
The 90-second answer
I would clarify the rules first, because "word guessing" covers two different games. I will assume the Wordle variant most pairs use: a fixed-length secret word, six guesses, and per-letter feedback for correct position, present elsewhere, or absent. If the interviewer meant Hangman, the state machine below stays the same and only the feedback function changes.
I would split the code into a pure game core with no UI imports, and a thin React layer on top. That lets us test win, loss, duplicate letters, and invalid guesses without rendering anything, which matters in a timed pair.
// TypeScript, checked against React 18
type Feedback = 'correct' | 'present' | 'absent';
type GameState = 'playing' | 'won' | 'lost';
function evaluateGuess(guess: string, secret: string): Feedback[] {
const result: Feedback[] = Array(guess.length).fill('absent');
const remaining = new Map<string, number>();
guess.split('').forEach((ch, i) => {
if (ch === secret[i]) result[i] = 'correct';
else remaining.set(ch, (remaining.get(ch) ?? 0) + 1);
});
guess.split('').forEach((ch, i) => {
if (result[i] === 'correct') return;
const count = remaining.get(ch) ?? 0;
if (count > 0) { result[i] = 'present'; remaining.set(ch, count - 1); }
});
return result;
}The two passes are the whole trick. A single pass marks the second E in EERIE as present even when the secret has only one E already matched in position. Pass one reserves exact matches, pass two spends the leftover letter counts.
State lives in one reducer: secret, guesses: string[], current: string, status. Actions are TYPE, DELETE, SUBMIT, RESET. SUBMIT validates before it appends: length equals word length, word is in the dictionary, game is still playing. Invalid input sets an error message and leaves guesses untouched, so a rejected guess never burns an attempt.
Worked trace, secret APPLE, guess PAPER:
| Position | Guess | Secret | Feedback | Why |
|---|---|---|---|---|
| 1 | P | A | present | P exists at position 2, not yet matched |
| 2 | A | P | present | A exists at position 1 |
| 3 | P | P | correct | exact match, reserved in pass one |
| 4 | E | L | present | E exists at position 5 |
| 5 | R | E | absent | no R in secret |
The UI is a grid of tiles plus a keyboard. Each tile is a div with aria-label set from the feedback, for example "P, present". The keyboard buttons show the best known state per letter, with correct outranking present outranking absent, and they are real <button> elements so keyboard and screen reader users can play without a pointer. Focus moves to the status region on win or loss, and that region announces "You won in 4 guesses" or reveals the secret on loss.
Edge cases I would name before coding: duplicate letters as above, uppercase input normalized once at the boundary, a guess repeated verbatim allowed or rejected by a stated rule, and RESET picking a new secret from the word list rather than reusing the old one. For a Shopify storefront context I would also keep the bundle small, avoid a game library, and make the grid responsive at 320 px width, since a merchant previewing a theme on a phone is a realistic user. Tests I would write first: evaluateGuess on duplicate-letter cases, reducer transitions for the sixth guess, and a component test that an invalid-length submit does not increment the guess count.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22How did you get into tech?
Reported in Shopify Software Engineer Interview Questions | Screna AI
The 90-second answer
I got into tech because I was tired of rebuilding the same stock spreadsheet every Monday. I worked in retail operations for a 12 store chain, and that report took me about three hours. It was also wrong often enough that nobody fully trusted it. I taught myself Python over a few weekends to automate it. The first version was slow and messy, but it cut the job to roughly 20 minutes and gave the same answer each week. That was enough to make me curious about what else I could remove.
I started with scripting instead of a bootcamp or a degree, and that choice was deliberate. A bootcamp would have given me structure and a cohort, and I looked at two of them seriously. The cost was about four months of savings, and the curriculum was aimed at web development, which was not the problem in front of me. A degree would have taken years and I already had a job I needed to keep. Scripting had a faster feedback loop. I could test a change against last week's file the same evening, and if the totals matched, I knew it worked. The trade-off was real. I had no one to tell me my code was hard to read, and I spent a year writing scripts I later had to rewrite properly.
The work grew in a predictable way. After stock, I automated supplier invoice reconciliation and a report for items that had not sold in 90 days. Each script replaced a manual task, and each one taught me a new failure mode. Duplicate SKUs, blank quantities, a supplier sending quantities in cases instead of units. I added a check that stopped the run if the weekly total moved by more than 5 percent, and that check caught the cases problem. It also taught me to distrust my own output until I had compared it with something independent.
The decision to make it a career came when someone else needed to run the tool. I had to write documentation, make error messages a store manager could act on, and put the script on a schedule with a log file. A script only I could run was not finished, and fixing that was my first lesson in building software for other people. My manager gave me one day a week for internal tooling, and that became my role. I applied for a junior engineering position internally, then moved to backend work on APIs and data pipelines.
I have stayed because the pattern keeps repeating at larger scale. A merchant or a teammate has a manual process, the data is messy, and a tested piece of software makes the result repeatable. That is why Shopify appeals to me. I supported the kind of merchants Shopify builds for, and I know how much it matters when an order report matches what the warehouse counted. I want to work on that layer, where correctness is visible to someone running a business.
My gap, honestly, is that I came in through scripting, so I learned testing, code review and API design later and on the job. I am still fastest when I build something small, put it in front of a real user, and fix what the real data does to it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23What's your take on 40% growth as a target or benchmark?
Reported in Shopify Software Engineer Interview Questions | Screna AI
I would ask what the 40% is attached to before I judged it. Growth of what, over what period, and from what base? Revenue, GMV, active merchants, and orders can all grow 40% while meaning very different things for the business.
My take is that 40% is a reasonable stretch target for a young product or a new market, and a poor universal benchmark. Applied blindly across teams, it rewards the easiest base and punishes the team that already scaled.
The base decides the difficulty
Assume a hypothetical business unit, figures labelled as an example:
| Starting point | After 1 year at 40% | After 3 years at 40% | Absolute gain in year 1 |
|---|---|---|---|
| $1m revenue | $1.4m | $2.74m | $0.4m |
| $100m revenue | $140m | $274m | $40m |
The percentage is identical. The second team must find 100 times the absolute money, usually in a more saturated market, with more support load and more churn to offset. Compounding also hides the later years: year 3 at 40% on $100m adds $78.4m, almost double the year 1 gain. A benchmark that ignores that will keep declaring mature teams underperformers.
Target, benchmark, and forecast are different tools
| Use | What 40% does well | Where it breaks |
|---|---|---|
| --- | --- | --- |
| Target | Forces a team to find a step change, not incremental tuning | Invites discounting, loose merchant onboarding, or pulling revenue forward |
| Benchmark | Gives a shared language for comparing experiments | Compares a new checkout flow with a mature payments product as if they had the same headroom |
| Forecast | Sets a planning assumption for hiring and infrastructure | Becomes a promise, so teams hide bad news until the quarter ends |
At Shopify scale, I would pair any growth number with guardrails I could check in a dashboard: net merchant retention, churn, refund and chargeback rate, support contacts per merchant, and gross margin. If GMV grows 40% because we onboarded merchants who churn in 60 days, the headline passes and the business gets worse. I have seen that pattern with referral and discount campaigns: acquisition spikes, cohort retention drops, and the team spends the next two quarters cleaning up.
How I would use it in practice
I would set 40% as a target only where three conditions hold. First, the base is small enough that the absolute gain is plausible with the team we have. Second, we can name the mechanism: a new segment, a new geography, a price change, or a conversion fix with measured headroom. Third, the guardrails above are tracked weekly, not reviewed at quarter end.
As a benchmark, I would convert it into a range by maturity. A product in its first year might be judged against 40% or more. A core product growing from a large base might be judged on absolute incremental revenue and retention, with 40% treated as exceptional rather than expected. That keeps the ambition without pretending every surface has the same curve.
If an interviewer pushed me, I would say 40% is a useful question, not a useful answer. It forces the team to state the metric, the base, and the cost of getting there. Without those three, it is just a number people will optimise around, including in ways we would regret.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24Would you push this to production?
Reported in Shopify Software Engineer interview experience (August 2024)
The 90-second answer
I would not give a yes or no until I know what "this" is and what it touches. If it is a change to checkout, payments, inventory or order creation at Shopify, the bar is different from an internal admin tool. I would ask three things first: what is the blast radius if it is wrong, how do we detect that within minutes, and how do we reverse it without a deploy.
Assuming tests pass in staging, I would push only if all three are concrete. A feature flag or canary that limits exposure, a dashboard and alert tied to the merchant-facing symptom rather than a generic CPU graph, and a rollback path that does not require a database fix. If any of those is "we will watch the logs", I would hold it and say why.
How I decide in the room
| Signal | Push | Hold |
|---|---|---|
| Blast radius | Flagged, 1% canary, non-payment path first | Global deploy to checkout or payments |
| Detection | Named metric and alert, for example checkout error rate by merchant cohort | No metric, or only server logs |
| Rollback | Flag off in under a minute, no irreversible migration | Schema change that drops or rewrites data |
| Load | Tested at peak, including BFCM style spikes for merchant traffic | Tested only at average traffic |
| Ownership | Owner on call who wrote it, runbook linked from the flag | Author unavailable, no runbook |
The payment example makes the trade-off clear. A 0.1% increase in checkout failures sounds small until you multiply it. At a hypothetical 10,000 checkout attempts per minute, 0.1% is 10 failed checkouts per minute, and those are merchants losing sales in real time. That is why I want the canary compared against a control group on the same metric, not just overall error rate, which can hide a regression behind traffic mix.
What I would check before flipping the flag
A preflight check I can run in the interview, in Ruby since much of Shopify's merchant stack is Rails:
# checked against a hypothetical flag service, Ruby 3.3
def safe_to_ramp?(flag, metrics)
flag.enabled_for_canary? &&
metrics.error_rate_delta < 0.001 && # <0.1pp vs control
metrics.p99_latency_ms < 300 &&
metrics.alert_armed? &&
flag.rollback_owner_on_call?
endIf that returns false, the answer is no, and I name the missing piece instead of shipping and hoping. Common failure modes I would call out: a flag that controls the code path but not the background job that writes the same data, a migration that is safe on a small table and locks on a large one, and a metric averaged across all merchants that misses a cohort, for example one payment provider or one region.
If the change is low risk, reversible and observable, I would push it, stay on the canary until the metric window closes, and write down what would make me roll back before I ramp. That is the difference between pushing to production and pushing and hoping.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25Simulate alternating Tic-Tac-Toe moves and detect a winner, draw, or unfinished game?
Reported in Shopify Software Engineer Interview Questions | Dataford
The 90-second answer
I would keep a 3 by 3 board and eight counters: three rows, three columns, and two diagonals. Each counter holds a signed sum, +1 for X and -1 for O. A move adds the player's sign to its row, column, and any diagonal it touches. If any counter reaches +3 or -3 in absolute value, that player has won. If nine legal moves are played with no winner, it is a draw. Fewer than nine moves with no winner means unfinished. That gives O(1) work per move instead of rescanning the board.
Assumptions I would state up front: X moves first, players alternate, a move is a (row, col) pair with 0-based indices, and play stops at a win. I would also reject a move that is out of bounds, lands on an occupied cell, or arrives after the game has ended. Without that last check, a later move could overwrite the result.
# Python 3.11
class TicTacToe:
def __init__(self, n: int = 3):
self.n = n
self.board = [[None] * n for _ in range(n)]
self.rows = [0] * n
self.cols = [0] * n
self.diag = 0 # top-left to bottom-right
self.anti_diag = 0 # top-right to bottom-left
self.moves = 0
self.winner = None # 1 for X, -1 for O
def move(self, row: int, col: int, player: int) -> str:
if self.winner is not None or self.moves == self.n * self.n:
return "game_over"
if not (0 <= row < self.n and 0 <= col < self.n):
return "out_of_bounds"
if self.board[row][col] is not None:
return "occupied"
self.board[row][col] = player
self.moves += 1
self.rows[row] += player
self.cols[col] += player
if row == col:
self.diag += player
if row + col == self.n - 1:
self.anti_diag += player
if self.n in (self.rows[row], self.cols[col], self.diag, self.anti_diag) or \
-self.n in (self.rows[row], self.cols[col], self.diag, self.anti_diag):
self.winner = player
return "X wins" if player == 1 else "O wins"
if self.moves == self.n * self.n:
return "draw"
return "unfinished"Worked trace for X winning on the anti-diagonal:
| Move | Player | (row, col) | rows | cols | diag | anti | Result |
|---|---|---|---|---|---|---|---|
| 1 | X | (0, 2) | [1, 0, 0] | [0, 0, 1] | 0 | 1 | unfinished |
| 2 | O | (0, 0) | [0, 0, 0] | [-1, 0, 1] | -1 | 1 | unfinished |
| 3 | X | (1, 1) | [0, 1, 0] | [-1, 1, 1] | 1 | 2 | unfinished |
| 4 | O | (2, 2) | [0, 1, -1] | [-1, 1, 0] | 0 | 2 | unfinished |
| 5 | X | (2, 0) | [0, 1, 0] | [0, 1, 1] | 0 | 3 | X wins |
Only the counters touched by the move change, so checking the current row, column, and diagonals is enough. A counter for an untouched line cannot have changed on this move.
Why signed counters instead of rescanning
| Approach | Cost per move | Cost to check | Risk |
|---|---|---|---|
| Rescan all lines | O(n) | O(n) | Simple, but repeats work on every move |
| Signed counters | O(1) | O(1) | Must update every counter the cell touches |
| Store per-player counters | O(1) | O(1) | More state, clearer debugging |
For a fixed 3 by 3 board the difference is trivial in practice. The counters matter when the interviewer extends n, or when moves arrive as a stream and you want constant work per event. Signed counters also handle both players with one set of arrays. The trade-off is a subtler bug surface: forgetting the anti-diagonal condition row + col == n - 1 silently misses wins, and using separate X and O counters makes the win test two comparisons instead of one absolute value check.
Failure modes I would test
Occupied cell: return an error and do not increment counters or move count, otherwise a retry inflates the draw check. Move after a win: reject it, because a board with two completed lines is unreachable in real play and accepting it hides a caller bug. Full board with a winning final move: check the win before the draw, as in the trace above, or a last-move win gets reported as a draw. Off-by-one on indices: decide 0-based versus 1-based before coding and test (0, 0) and (2, 2) explicitly. If the input comes from an untrusted client, validate that player alternation matches the move count, since counters alone will happily accept two X moves in a row and produce a board no legal game could reach.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: