Backend Fundamentals: GIL, PUT vs PATCH, Cyclic GC, Lock Ordering
System DesignModel answerLast updated
Answer four backend fundamentals for a payments service: Python concurrency and the GIL, PUT/PATCH with optimistic locking, CPython garbage collection, and deadlock avoidance.
Context
You are doing a technical review of a banking-style backend written in Python. It offers HTTP endpoints for editing customer account profiles, calls several outside payment providers, periodically computes fraud-risk scores, and moves money between internal accounts.
Answer the four parts below. Explain the underlying mechanism first, then commit to a concrete design decision for this service.
Part 1: Concurrency in CPython
- Compare
threading,multiprocessing, andasyncio. - Explain what the Global Interpreter Lock does to CPU utilization on a multi-core machine.
- Pick a model for each workload and justify it:
- (a) Calling many third-party payment providers over HTTP and waiting for replies.
- (b) Computing cryptographic digests of transactions or running Monte Carlo risk simulations.
Part 2: Updating resources over HTTP
- Explain how
PUTandPATCHdiffer in meaning (full replacement vs partial change) and in idempotency. - Describe the "lost update" problem when two clients edit the same account profile at the same time.
- Design a standards-based way to prevent it, using
ETagand conditional request headers such asIf-Match.
Part 3: Memory management in CPython
- Describe how reference counting allocates and frees objects.
- Explain why it cannot reclaim objects that reference each other in a cycle.
- Describe how the generational cycle collector finds unreachable cycles, and how you would track down a leak caused by cycles in a long-running service.
Part 4: Deadlocks
- List the four Coffman conditions.
- Show a classic deadlock in which two threads transfer money between Account A and Account B in opposite directions.
- Give a deterministic locking discipline (for example, a global lock order) and pseudocode that acquires the locks safely.
Hints
Hint 1
For Part 1, ask what the code spends its time doing: waiting on sockets or burning CPU. Then ask which models can run Python bytecode on several cores at once.
Hint 2
For Part 2, a safe update needs a version check and a write that happen as one atomic step. Think about which status codes signal 'your version is stale' and 'you must send a precondition'.
Hint 3
For Part 4, a deadlock needs a circular wait. If every thread acquires locks in the same global order, a cycle cannot form. Decide what the order should be, and handle the case where both accounts are the same.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Python concurrency
| Model | Unit of work | Uses multiple cores for Python code? | Best for | Main costs |
|---|---|---|---|---|
threading | OS threads in one process | No (GIL) | Blocking I/O, synchronous SDKs | Stack memory per thread, preemptive data races |
multiprocessing | Separate processes | Yes, one GIL per process | CPU-bound Python | Startup time, pickling/IPC, duplicated memory |
asyncio | Coroutines on one event-loop thread | No | Large numbers of concurrent network calls | Needs async-aware libraries; one blocking call freezes the loop |
The GIL. Each CPython interpreter lets only one thread execute bytecode at any moment. A running thread is asked to yield every sys.getswitchinterval() seconds (5 ms by default), and it releases the lock during blocking system calls such as socket reads. The result is that threads overlap their waiting but take turns computing. Eight CPU-bound threads use roughly one core, plus switching overhead. Some C extensions (hashlib on large buffers, many NumPy operations, zlib) drop the GIL while working, so threads can scale there.
(a) Payment-gateway fan-out: asyncio. The work is almost entirely waiting. An async client such as httpx.AsyncClient or aiohttp keeps thousands of requests in flight at kilobytes each. Use asyncio.TaskGroup or gather with per-call timeouts, and a semaphore to cap concurrency per provider so that no gateway is flooded. If a provider only ships a blocking SDK, wrap calls in a ThreadPoolExecutor.
(b) Hashing and Monte Carlo: multiprocessing. Use a ProcessPoolExecutor with about one worker per core, and send work in batches so pickling cost is amortized. Exception: if the hot loop is vectorized NumPy or hashlib over large buffers, threads may be enough because the GIL is released. Never run CPU-heavy code on the event loop. Use loop.run_in_executor(process_pool, ...) instead. (Free-threaded CPython builds change this picture, but they are not the default yet.)
2. HTTP update semantics
PUT vs PATCH.
PUTreplaces the whole resource. Omitted fields are reset or removed. It is idempotent by definition: repeating the same request leaves the same final state.PATCHsends a delta (JSON Merge Patch or JSON Patch). It is not guaranteed to be idempotent. "Append tagvip" or "raise limit by 100" changes state again on every retry. A patch that only sets absolute values is idempotent in practice.
Lost update.
- Clients X and Y both read
/accounts/42at the same version. - X saves a new email.
- Y, working from the stale copy, saves a new phone number with a full
PUT. - Y's write silently erases X's email change. Last writer wins and nobody is told.
PATCH narrows the window when clients touch different fields, but it does not fix the problem. Two clients can edit the same field, and any read-modify-write from stale data is unsafe.
Optimistic concurrency with ETag / If-Match.
GET /accounts/42returnsETag: "v7"(a version number or a content hash).- The client sends its update with
If-Match: "v7". - The server does an atomic compare-and-set:
UPDATE accounts SET email = :email, version = version + 1 WHERE id = 42 AND version = 7; - One row changed: return
200withETag: "v8". Zero rows changed: return412 Precondition Failed, and the client re-reads, re-applies its change, and retries. - Require the header on every mutation. If it is absent, return
428 Precondition Required.
The check and the write must be one statement or one transaction. "Read version, compare in app code, then write" brings the race back. For money movement, add an Idempotency-Key header so retried POSTs are deduplicated.
3. Memory management and garbage collection
Reference counting. Every object carries a count (ob_refcnt) that goes up when a name, container slot, or argument refers to it, and down when the reference goes away. At zero, the object's deallocator runs immediately, which gives deterministic cleanup such as files closing at scope exit. Small objects (up to 512 bytes) come from pymalloc, which manages arenas, pools, and size-class blocks. Freed blocks return to pools, and an arena goes back to the OS only when completely empty, so resident memory often stays high after a spike even when nothing leaks.
Why cycles break it. If a.peer = b and b.peer = a and the outside names are deleted, each object still has a count of 1 from the other. Neither reaches zero, so neither is freed.
The cycle collector. It tracks only container objects (lists, dicts, instances, closures). For the generation being collected it:
- Copies each object's refcount into a scratch field,
gc_refs. - Traverses each object's referents and subtracts one for every reference coming from inside the set.
- Treats objects whose
gc_refsis still above zero as externally referenced roots, and marks everything reachable from them as alive. - Treats the remainder as unreachable. It handles weakref callbacks, runs finalizers (safe since PEP 442), and clears references so refcounting frees the objects.
Generations. Through 3.13 there are three generations with default thresholds (700, 10, 10). Most objects die young, so young objects are scanned often, and survivors are promoted and scanned rarely. Newer releases (3.14) use an incremental young/old scheme to shorten pauses, with the same reachability idea.
Diagnosing a leak in a long-running service.
- Compare two
tracemallocsnapshots (compare_to(old, "traceback")) to find the growing allocation sites. - Call
gc.collect(), then countgc.get_objects()by type, or useobjgraph.show_growth(), to see which types accumulate. - Use
gc.get_referrers(obj)orobjgraph.show_backrefsto see what keeps a sample object alive. - Set
gc.set_debug(gc.DEBUG_SAVEALL)and inspectgc.garbageto see which cycles were found. - Remember that many "leaks" are not cycles at all: unbounded caches, global registries, or lingering closures. Fix real cycles with
weakref, by breaking links explicitly, or by restructuring ownership.
4. Deadlocks
Coffman conditions (all four must hold):
- Mutual exclusion: a resource is held by one thread at a time.
- Hold and wait: a thread holds one resource while waiting for another.
- No preemption: resources cannot be forcibly taken away.
- Circular wait: a cycle of threads each waits for a resource held by the next.
Classic scenario. Thread 1 runs transfer(A, B) and locks A. Thread 2 runs transfer(B, A) and locks B. Thread 1 now waits for B, Thread 2 waits for A, and neither can proceed.
Fix: global lock ordering. Breaking circular wait is the cheapest option. Give every account a stable, unique key (its primary key) and always lock the lower key first, regardless of transfer direction.
def transfer(src, dst, amount):
if src.id == dst.id:
raise ValueError("same account") # avoid locking one lock twice
first, second = (src, dst) if src.id < dst.id else (dst, src)
with first.lock:
with second.lock:
if src.balance < amount:
raise InsufficientFunds()
src.balance -= amount
dst.balance += amount
Both directions now lock in the same order, so no cycle can form. In a database, the same rule applies: SELECT ... FOR UPDATE the two rows ordered by id within one transaction.
Other options and trade-offs.
try_lockwith timeout and backoff breaks hold-and-wait, but risks livelock and needs retry logic.- A single coarse lock is simple but serializes all transfers.
- Detection (wait-for graph) with a victim abort is what databases do, and the application must be ready to retry.
Common mistakes: ordering by object memory address when objects can be proxied or copied, forgetting the same-account case, holding locks across network calls, and releasing in an inconsistent order that hides other bugs.