Lazy Pipelines, Memoization, Indexes, and Safe Payment Retries
System DesignModel answerLast updated
A multi-part fundamentals question covering lazy vs eager iteration, a multi-argument cache decorator, B+ tree index trade-offs, process vs thread, and testing idempotent retries.
Answer each of the following as you would in a technical conversation. Be concrete, give numbers where they help, and name the trade-offs.
Part 1: Python
- You must aggregate a field from a text file with 10 million rows. Compare building a list with a list comprehension against using a generator expression. What changes in memory use, time to first result, and reusability?
- Write a decorator that caches the return value of a function that takes several positional and keyword arguments. Explain how you build the cache key and what happens when the same call is repeated, for example
compute(1, 2)invoked many times. Mention the edge cases you would handle.
Part 2: Databases
A Users table holds 100 million rows, and a query filters with WHERE email = '...'.
- Explain why a B+ tree index on
emailis far faster than a full table scan. Estimate the number of page reads in each case. - Suppose five secondary indexes are added to the table. Discuss the effect on write latency and on disk and memory usage, and how you would decide which indexes to keep.
Part 3: Systems and testing
- Contrast a process with a thread in terms of memory isolation and context-switch cost.
- You own a payment module that retries calls after transient network failures. How would you test the retry logic, and how would you guarantee the operation is idempotent so a customer is never charged twice?
Hint on scope: separate what you verify with fast unit tests (logic with fakes) from what needs integration tests (real network behavior and faults).
Hints
Hint 1
For the file, ask what must be alive in memory at the same instant, and whether you need a second pass over the data.
Hint 2
A cache key must be hashable and must treat keyword-argument order as irrelevant. Think about what to do for unhashable inputs and unbounded growth.
Hint 3
Estimate index depth as log base fanout of the row count, and compare it with rows divided by rows per page for a scan.
Hint 4
The nastiest payment failure is when the request succeeds on the server but the response is lost. Design the idempotency key and a unique constraint around that case.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Python
List comprehension vs generator expression
A list comprehension is eager: it builds every element before you can use any of them. A generator expression is lazy: it yields one element at a time as the consumer asks.
# Eager: all parsed rows live in memory together
rows = [parse(line) for line in open("data.csv")]
total = sum(r.amount for r in rows)
# Lazy: one row alive at a time
with open("data.csv") as f:
total = sum(parse(line).amount for line in f)
- Memory. Each parsed row is a full Python object, often 100+ bytes with headers, strings and tuples. Ten million rows can reach several GB and risk swapping or an OOM kill. The generator uses O(1) memory.
- Time to first result. The generator produces output immediately. The list must read the whole file first.
- Composability. Generators chain into a streaming pipeline (read, filter, transform, aggregate) without materializing anything.
- Costs. A generator is single-pass, has no
len()and no indexing, and has slightly higher per-item overhead. Use a list when the data is small and you need several passes or random access.
Caching decorator
Build a hashable key from args and kwargs, and store results in a dict.
import functools
_MISSING = object()
def memoize(func):
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
try:
hash(key)
except TypeError:
return func(*args, **kwargs) # unhashable: bypass cache
result = cache.get(key, _MISSING)
if result is _MISSING:
result = func(*args, **kwargs)
cache[key] = result
return result
wrapper.cache_clear = cache.clear
return wrapper
@memoize
def compute(x, y):
return x ** y
The first compute(1, 2) runs the function. Later identical calls produce an equal key and return the stored value. The sentinel lets a legitimate None result be cached.
Complexity. Building and hashing the key is O(k) for k arguments, then O(1) average dict access. Space is O(n) for n distinct calls.
Edge cases.
- Unhashable arguments (lists, dicts): bypass the cache or convert them.
compute(1, 2)vscompute(x=1, y=2)give different keys. Normalize withinspect.signature(func).bind.- Unbounded growth: use LRU eviction or a
maxsize. - Thread safety: guard with a lock, accepting that two threads may compute the same value once.
- Only cache pure (deterministic, side-effect-free) functions.
In production prefer functools.lru_cache(maxsize=...) or functools.cache.
Part 2: Databases
B+ tree vs full scan
With about 50 rows per 8 KB page, 100M rows occupy roughly 2M pages, around 16 GB. A full scan reads all of them: seconds to minutes.
A B+ tree has high fanout because internal nodes store only keys and child pointers. With a fanout near 500, the depth is log₅₀₀(10⁸) ≈ 3, so a lookup touches about 3 to 4 pages. The root and upper levels stay in the buffer pool, so in practice that is 1 to 2 physical reads. Leaves are sorted and linked, so the same index also supports range scans and ORDER BY email. With a unique index the engine stops after the first match. Cost goes from O(N) to O(log_f N).
Five secondary indexes
Write latency. Each insert updates the table plus five trees: more random page writes, possible page splits, more WAL/redo volume, and more latch and lock contention. Deletes touch all indexes; updates touch only indexes on changed columns. Expect write throughput to fall by a multiple.
Space. Each entry holds the key plus a row pointer or primary key. Roughly 40 bytes of email plus 8 bytes of PK, times 100M, plus about 30% slack, is around 6 GB per index. Five indexes add tens of GB and compete with table pages for buffer-pool memory.
Decision rule. Index for real query patterns, prefer composite or covering indexes over many single-column ones, and drop indexes that usage statistics show are unused.
Part 3: Systems and testing
Process vs thread
- Isolation. Processes have separate virtual address spaces, so one crashing or corrupting memory does not affect another. They communicate through IPC (pipes, sockets, shared memory). Threads share heap, globals and file descriptors, with only a private stack and registers. Sharing is cheap but invites data races.
- Context switch. A process switch changes page tables, typically flushes the TLB (unless ASIDs/PCIDs are used) and causes more cache misses. A thread switch within a process keeps the address space and is cheaper.
Testing payment retries
Unit tests (logic). Inject a fake transport and fake clock.
- Simulate timeouts, resets and 503s; assert retry count, exponential backoff with jitter, and the max-attempts cap.
- Assert no retry for non-transient errors such as a card decline or 4xx.
- Assert the same idempotency key is sent on every attempt.
Integration tests (network). Use a fault-injecting proxy (for example Toxiproxy) or a provider sandbox to add latency, drop connections and truncate responses. The key scenario is request delivered, response lost: the charge happened, the client times out and retries. Assert exactly one charge exists. Also test concurrent duplicate submissions (double-click) and a crash between "charge succeeded" and "result recorded".
Guaranteeing idempotency
Networks give at-least-once delivery, so duplicates will happen. The design:
- The client creates a unique idempotency key (UUID) per payment intent and reuses it on every retry.
- The server stores
(key, request_hash, status, response)under a unique constraint, inserting it in the same transaction as the ledger entry. - On a repeated key: if completed, return the stored response; if still in progress, return a conflict or wait; if the request hash differs, reject it as key misuse.
- Pass the same key to the downstream payment provider, and run a reconciliation job for ambiguous outcomes.
- Expire keys after a retention window such as 24 hours to 7 days.
Common mistakes
- Generating a new idempotency key per attempt, which defeats the purpose.
- Retrying non-transient errors or retrying without backoff and jitter, causing retry storms.
- Checking for the key with a read and then writing, instead of relying on a unique constraint, which races.
- Adding many single-column indexes without measuring query use.
- Caching impure functions or ignoring unhashable arguments.