Identify the Interleaved Transaction Anomaly

Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment

Problem Statement

Suppose a shared database record X initially holds the committed integer 500. Two concurrent database sessions, T1 and T2, perform the following four steps in strict time order:

  1. T1 fetches X and observes 500.
  2. T2 fetches X and also observes 500.
  3. T1 adds 40 to its fetched value and stores X = 540.
  4. T2 subtracts 25 from the 500 it fetched at step 2 and stores X = 475.

Implement classify_concurrency_anomaly() -> str to return the single uppercase letter ("A", "B", "C", or "D") that accurately classifies the concurrency behavior of this four-step schedule:

  • "A" — Unrepeatable read: one session queries X twice within the same transaction and observes two different values.
  • "B" — Conflict-free serializable execution: no anomaly occurs; the final database state matches running one session completely before the other.
  • "C" — Dirty read: one session fetches an uncommitted value written by another active session.
  • "D" — Lost update: a later write computed from an outdated read overwrites and erases an earlier session's modification.

Examples

Example 1

  • Input: classify_concurrency_anomaly()
  • Output: "D"
  • Explanation: Running T1 (+40) and T2 (-25) sequentially in either serial order leaves X = 515. In the interleaved schedule, T2 computes 500 - 25 = 475 from its stale read of 500 and overwrites 540, completely discarding T1's +40 increment.

Constraints

  • classify_concurrency_anomaly() takes no parameters and returns a 1-character uppercase string in {"A", "B", "C", "D"}.
  • X = 500 is committed prior to step 1, and both T1 and T2 commit after step 4 without rolling back.

Step-by-step walkthrough

  1. Understand the timeline on shared record X

    A transaction is a grouped sequence of database reads and writes treated as one logical unit of work — such as crediting 40 points to a balance or deducting 25 points from it.

    Here T1 and T2 share one record X that starts at 500. Let's trace what lives in T1's memory, in the database record X, and in T2's memory at each time step:

    Time   Action                        T1's read   Database X   T2's read
    ----   ---------------------------   ---------   ----------   ---------
    start  (initial committed state)         -          500           -
      1    T1 fetches X                    500          500           -
      2    T2 fetches X                    500          500          500
      3    T1 writes 500 + 40 = 540        500          540          500
      4    T2 writes 500 - 25 = 475        500          475          500
    

    Look closely at step 4: T2 does not subtract 25 from the database's current value (540). Instead, T2 subtracts 25 from the 500 it fetched back at step 2 and stores 475 into X. Our function classify_concurrency_anomaly() must return the option letter ("A", "B", "C", or "D") naming what went wrong.

  2. Check what a correct execution would produce

    In database systems, the benchmark for concurrent correctness is serializability: executing transactions concurrently must leave the exact same final state as executing them one after another with zero overlap (a serial schedule).

    With two sessions T1 (+40) and T2 (-25), there are only two possible one-at-a-time orders:

    Serial order 1 (T1 then T2):
      X = 500  --[T1 reads 500, writes 540]-->  X = 540  --[T2 reads 540, writes 515]-->  X = 515
    
    Serial order 2 (T2 then T1):
      X = 500  --[T2 reads 500, writes 475]-->  X = 475  --[T1 reads 475, writes 515]-->  X = 515
    

    In both valid orders, adding 40 and subtracting 25 produce X = 515. Because our interleaved schedule ended at X = 475 instead of 515, data integrity was genuinely broken — which eliminates Option B ("conflict-free serializable execution").

  3. Identify the lost update (Option D)

    Why did X end at 475 instead of 515? Follow what happened to T1's +40 increment:

    1. T1 and T2 both fetched the initial value X = 500.
    2. T1 stored its updated value 540.
    3. T2 computed 500 - 25 = 475 from its outdated read and overwrote 540 with 475.

    T1's +40 update vanished completely — the final state 475 looks as if T1 never executed at all. When two concurrent sessions read the same record and both write back values derived from what they read, causing the later write to overwrite and discard the earlier write, that anomaly is a lost update. That matches Option D.

  4. Rule out dirty read (Option C) and unrepeatable read (Option A)

    Options A and C describe distinct database anomalies, so comparing their exact read/write shapes against our timeline confirms why neither applies:

    Option C — Dirty read (reading uncommitted data):
      T1 writes X = 540 (not committed yet!)
      T2 fetches X = 540  <-- T2 sees uncommitted data; if T1 rolls back, 540 never existed
    
    Option A — Unrepeatable read (same session reads twice, sees two values):
      T1 fetches X = 500
      T2 writes  X = 475 and commits
      T1 fetches X = 475  <-- T1 re-read X and observed 475 instead of 500
    

    Neither pattern appears in our four-step schedule:

    • Not C (dirty read): Both reads happen at steps 1 and 2, before any write occurs at steps 3 and 4. Both T1 and T2 observe the clean, already-committed value 500.
    • Not A (unrepeatable read): T1 fetches X once (step 1) and T2 fetches X once (step 2). Neither session ever reads X a second time.
  5. Complete solution

    Since classify_concurrency_anomaly() evaluates this fixed schedule, it returns "D" directly while documenting why each alternative option is ruled out.

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def classify_concurrency_anomaly() -> str:
        """Return the option letter ('A'-'D') naming the concurrency anomaly in the T1/T2 schedule."""
        # Timeline on shared record X (initial committed value = 500):
        #   t=1: T1 fetches X = 500        -> sees committed data (not a dirty read, rules out C)
        #   t=2: T2 fetches X = 500        -> each session reads X once (not a re-read, rules out A)
        #   t=3: T1 writes X = 500 + 40    -> X becomes 540
        #   t=4: T2 writes X = 500 - 25    -> X becomes 475, computed from T2's stale read of 500
        #
        # Both serial orders (T1 then T2, or T2 then T1) leave X = 515, whereas this schedule leaves
        # X = 475 (rules out B). Because T2's write overwrites and erases T1's +40 update, the anomaly
        # is a lost update (option D).
        return "D"
    
    
    if __name__ == "__main__":
        print(classify_concurrency_anomaly())
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine two coworkers, T1 and T2, updating a shared inventory card that currently shows 500 units in stock. At 9:00 AM, T1 glances at the card and notes 500; at 9:01 AM, T2 also glances at the card and notes 500. At 9:02 AM, T1 unpacks a 40-unit delivery and writes 500 + 40 = 540 on the card. At 9:03 AM, T2 ships 25 units, calculates 500 - 25 = 475 from the 500 T2 saw earlier, and writes 475 on the card! T1's +40 restock has been wiped from the record even though 515 units are actually on the shelf. In database systems, a transaction (a sequence of reads and writes executed as one logical unit of work) that suffers this overwrite bug has hit a lost update (an anomaly where two concurrent transactions read the same item and both write back values derived from that read, causing the later write to erase the earlier write).

Why do quick guesses often miss this? Viewed in isolation, neither session crashes and every arithmetic step (500 + 40 and 500 - 25) looks sensible, tempting candidates to pick Option B ("no anomaly"). Others spot two interleaved sessions and guess dirty read (reading a value written by another session that has not committed, meaning permanently saved, yet) or unrepeatable read (a single session reading the same record twice and getting two different answers) without checking the exact sequence of reads and writes. Comparing the final state against serializability (the rule that concurrent execution must match running transactions one after another with zero overlap) and checking each read/write dependency nails the classification every time.

Trace the four steps on X = 500:

Step   Operation                     Database X   Notes
----   ---------------------------   ----------   -------------------------------------------
 0     Initial committed state          500
 1     T1 fetches X -> gets 500         500       Clean committed read (not a dirty read)
 2     T2 fetches X -> gets 500         500       Clean committed read; neither re-reads later
 3     T1 writes 500 + 40 = 540         540       T1's +40 increment is stored
 4     T2 writes 500 - 25 = 475         475       T2 overwrites 540 using its stale read (500)!

Serial comparison:
  T1 then T2: 500 -> 540 -> 515
  T2 then T1: 500 -> 475 -> 515
  Actual end: 475 (T1's +40 was lost -> Option D)

Complexity

  • Time: O(1), because classify_concurrency_anomaly() evaluates a fixed four-step schedule and returns the constant string "D" in one step.
  • Space: O(1), because no auxiliary collections or growing buffers are allocated.

Edge cases

Small variations to the timeline produce each of the other three options, making a useful sanity check:

  • T2 waits to read until T1 commits (R1 -> W1(540) -> Commit1 -> R2(540) -> W2(515) -> Commit2): T2 observes 540 and writes 540 - 25 = 515, matching a serial schedule with zero anomalies (Option B).
  • T2 reads after T1 writes, before T1 commits (R1 -> W1(540) -> R2(540)): T2 observes uncommitted data, which is a dirty read (Option C). If T1 subsequently rolls back (aborts and restores X to 500), T2 acted on a 540 that officially never existed.
  • T1 queries X twice while T2 updates X in between (R1(500) -> W2(475) -> Commit2 -> R1(475)): The same session T1 observes 500 first and 475 second, which is an unrepeatable read (Option A).
  • Row write locks held until commit: Even when a database engine blocks T2's step-4 write until T1 commits 540 (preventing an uncommitted dirty write), T2 still writes 475 computed from its stale step-2 read of 500 once the lock releases, so T1's +40 update is still lost!
  • Atomic in-place SQL UPDATE vs. application read-modify-write: Issuing UPDATE inventory SET x = x + 40 and UPDATE inventory SET x = x - 25 directly inside SQL locks the row and computes from the newest committed value (540 - 25 = 515), avoiding the lost update.

Common mistakes

  • Picking Option A (unrepeatable read) because T2's cached 500 became stale: An unrepeatable read requires the same transaction to read X at least twice and observe two different values; here each session reads X only once.
  • Picking Option C (dirty read) merely because operations interleave: Both reads finish at steps 1 and 2 before the first write at step 3, so neither session reads uncommitted data.
  • Picking Option B (serializable) because neither session throws an error: Lost updates fail silently, dropping committed business updates without raising an exception unless concurrency control stops them.
  • Assuming default SQL isolation prevents lost updates automatically: An isolation level is a database setting controlling how strongly concurrent transactions are shielded from one another. Under READ COMMITTED (the default in PostgreSQL, Oracle, and SQL Server) and even MySQL InnoDB's default REPEATABLE READ, a plain SELECT followed by an application-computed UPDATE still loses updates unless explicit locking or version checks are used.
  • Returning "d" in lowercase or returning the full label: The judge checks for the exact 1-character uppercase string "D".

Follow-up questions

  • Which SQL patterns or locking mechanisms prevent this lost update in a production application? Whenever the change is a relative delta, use an atomic in-place update (UPDATE inventory SET x = x - 25 WHERE id = 1) so the database locks the row and subtracts from the latest committed value in one indivisible step. When business rules must run in application code first, either acquire a pessimistic exclusive lock on read (SELECT x FROM inventory WHERE id = 1 FOR UPDATE, forcing T2 to wait until T1 commits) or apply optimistic concurrency control (storing a version column and executing UPDATE inventory SET x = 475, version = version + 1 WHERE id = 1 AND version = 7, retrying the transaction if zero rows match).
  • How do standard SQL isolation levels (Read Committed, Repeatable Read, and Serializable) behave on this read-modify-write schedule across major databases? READ COMMITTED permits the lost update everywhere because plain SELECT queries release read locks immediately. Under REPEATABLE READ, PostgreSQL uses snapshot isolation with first-committer-wins conflict detection and aborts T2 with a serialization error when T2 tries to overwrite a row modified since its snapshot began, while SQL Server holds shared read locks until commit (causing T1 and T2 to deadlock so one aborts and retries). By contrast, MySQL InnoDB's default REPEATABLE READ serves a lock-free snapshot on plain SELECT yet lets a subsequent UPDATE overwrite the newest row without aborting — so InnoDB still requires FOR UPDATE, optimistic versioning, or SERIALIZABLE.
  • How is a lost update different from write skew when two transactions run concurrently? In a lost update, both transactions read and overwrite the same record X, so the second write directly clobbers the first. In write skew (an anomaly where two transactions read an overlapping set of rows, verify an invariant, and then modify disjoint rows so the combined state breaks the invariant), neither write overwrites the other's row — for instance, two on-call doctors both verify that 2 doctors are currently scheduled, and each updates their own shift record to sign off, leaving 0 doctors on duty. Snapshot isolation automatically blocks lost updates on a single row, whereas preventing write skew across multiple rows requires SERIALIZABLE isolation or explicit SELECT ... FOR UPDATE locks on the queried rows.

Follow-up questions

Similar questions

More Bitkernel interview questions

All 11 Bitkernel questions →