KatInterview

Database Concurrency and Code Verification Strategy

BehavioralModel answer
HardModel answerBehavioraldatabasesconcurrencydebugging

Last updated

Design a safe approach to fixing timestamp overwrites in a high-concurrency system while explaining how to validate code suggestions from automated tools.

Context

Your team operates a real-time system that tracks when users were last seen. The backend stores a last_seen_at timestamp for each user in a relational database. Under load, you've discovered that sometimes this timestamp gets set backward—a user active at 3:15 PM shows as last seen at 3:10 PM.

A code generation tool proposed fixing this by changing the update logic to:

UPDATE user_status 
SET last_seen_at = $new_time
WHERE user_id = $uid AND last_seen_at < $new_time

Your Task

Address three aspects of this problem:

  1. Concurrency Analysis: Explain what database-level issues could cause timestamps to move backward under concurrent writes. Discuss how transaction isolation levels affect the proposed solution and what risks remain.

  2. Production Debugging: Outline your methodology for diagnosing this issue in a live system where you cannot afford service interruption. What would you measure, what hypotheses would you test, and in what order?

  3. Code Verification Process: Describe your complete workflow for evaluating and validating suggestions from automated code generation tools before deploying them to production infrastructure.

Hints

Hint 1

Consider what happens when two processes read the same row value before either commits their write

Hint 2

Think about the differences between READ COMMITTED and SERIALIZABLE isolation and how databases handle concurrent updates to the same row

Hint 3

Remember that the conditional UPDATE itself may not be the problem—look for other code paths that touch the same column