Concurrency vs Parallelism
Concurrency is about structure: managing multiple tasks by interleaving execution (e.g. Node.js single-threaded event loops handling concurrent I/O).
Parallelism is about execution: performing multiple calculations at the exact same moment on multi-core CPUs.
Race Conditions
A race condition occurs when the correctness of a program depends on the relative timing of threads or requests. For example, if two requests read a balance of $100, calculate a withdrawal of $20, and write back the result ($80) sequentially, the second write will overwrite the first, losing $20.
Preventing Corruption with Locking
- Pessimistic Locking: Locks rows in the database, preventing other requests from reading them until the transaction finishes.
- Optimistic Locking: Adds a version number column to the row. The update succeeds only if the version matches the read version, throwing a conflict if another write occurred.
