TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation · 5.9K subscribers
Post #1434 347
🐛 SPOT THE BUG #6
Language: Python

python
class BankAccount:
def __init__(self, balance):
self.balance = balance

def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return True
return False

# Two threads calling withdraw(100) at nearly the same time
# on an account with balance = 100


What breaks here under concurrent access? 👇

.
.
.

The bug: Classic check-then-act race condition (a cousin of the counter bug from Spot the Bug #2, but with real money on the line). Thread A checks 100 <= 100 → true. Before it subtracts, Thread B also checks 100 <= 100 → true. Now BOTH threads proceed to withdraw, and the balance goes to -100 - the check and the action weren't atomic together.

Fixed version (using a lock):
python
import threading

class BankAccount:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()

def withdraw(self, amount):
with self.lock:
if amount <= self.balance:
self.balance -= amount
return True
return False


The lock ensures the check-and-subtract happens as one atomic unit - no other thread can interleave in the middle.

💡 This exact pattern (check-then-act on shared state) is one of the most common sources of real financial bugs in production systems, not just interview trivia. Any time you see "if condition, then modify shared state," ask: "can two threads see the same 'before' state at once?"

Have you seen a check-then-act bug in real code before? 👇
  • ❤ 1
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026💼 Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026💼 What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →