Dealing with Contention
Dealing with Database Contention
High-scale systems face contention when multiple concurrent requests attempt to read and write to the same database records.
1. Concurrency Patterns
- Pessimistic Locking:
Locks database rows explicitly (SELECT ... FOR UPDATE in SQL) during the transaction. Blocks other clients until the transaction commits. Prevents updates but risks deadlocks.
- Optimistic Concurrency Control (OCC):
Rows include a version or timestamp column. When writing, SQL checks:
UPDATE table SET val = x, version = version + 1 WHERE id = 1 AND version = current_version
If another write completed in the meantime, the statement fails, and the application retries. Best for read-heavy systems.
- Distributed Locking (Redlock):
Coordinates lock acquisitions across multiple independent Redis masters using lease timeouts (TTL) to avoid lock starvation.
2. Queue-Based Writes
To eliminate database locks entirely, writes stream to partition queues (Kafka/RabbitMQ) and a single-threaded background worker processes updates sequentially.
3. References & Tech Blogs
Related Topics
Expand your knowledge by learning about adjacent concepts in system design.
Consistent Hashing Basic
Deconstruct routing rings, virtual nodes, and distribution keys.
Networking Essentials
Learn the important parts of networking that you'll need to know for your system design interviews
API Design
Learn about API design for system design interviews
Cheat Sheet Utility
View and print a concise system design reference card.