KatInterview

Backend Fundamentals: GIL, PUT vs PATCH, Cyclic GC, Lock Ordering

System DesignModel answer
MediumModel answerSystem Designpythongilhttp

Last 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, and asyncio.
  • 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 PUT and PATCH differ 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 ETag and conditional request headers such as If-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.