What is the difference between optimistic locking with version numbers and timestamps?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

Answer

Optimistic locking detects conflicts at write time by verifying the data hasn't changed since it was read. Two common implementations: Version number (integer counter): add a version INT NOT NULL DEFAULT 0 column. On read, fetch the version. On update: UPDATE products SET stock = stock - 1, version = version + 1 WHERE id = ? AND version = ? — check affected rows; 0 means conflict (another transaction already updated and incremented version). Increment version atomically. Advantages: no issues with precision or time synchronization; works reliably even on the same millisecond. Timestamp: add an updated_at DATETIME(6) column (microsecond precision). On update: UPDATE products SET stock = ?, updated_at = NOW(6) WHERE id = ? AND updated_at = ?. Disadvantages: requires microsecond precision to avoid conflicts when two updates happen in the same millisecond (still possible on fast hardware); clock synchronization issues in distributed systems; TIMESTAMP resolution matters. Recommendation: use integer version numbers — they are simpler, unambiguous, and not subject to clock issues. Version-based optimistic locking is natively supported by ORMs like Hibernate, TypeORM (@VersionColumn), and Sequelize (version: true).

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.