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:
T1fetchesXand observes500.T2fetchesXand also observes500.T1adds40to its fetched value and storesX = 540.T2subtracts25from the500it fetched at step 2 and storesX = 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 queriesXtwice 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) andT2(-25) sequentially in either serial order leavesX = 515. In the interleaved schedule,T2computes500 - 25 = 475from its stale read of500and overwrites540, completely discardingT1's+40increment.
Constraints
classify_concurrency_anomaly()takes no parameters and returns a 1-character uppercase string in{"A", "B", "C", "D"}.X = 500is committed prior to step 1, and bothT1andT2commit after step 4 without rolling back.
Step-by-step walkthrough
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
40points to a balance or deducting25points from it.Here
T1andT2share one recordXthat starts at500. Let's trace what lives inT1's memory, in the database recordX, and inT2'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 500Look closely at step 4:
T2does not subtract25from the database's current value (540). Instead,T2subtracts25from the500it fetched back at step 2 and stores475intoX. Our functionclassify_concurrency_anomaly()must return the option letter ("A","B","C", or"D") naming what went wrong.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) andT2(-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 = 515In both valid orders, adding
40and subtracting25produceX = 515. Because our interleaved schedule ended atX = 475instead of515, data integrity was genuinely broken — which eliminates Option B ("conflict-free serializable execution").Identify the lost update (Option D)
Why did
Xend at475instead of515? Follow what happened toT1's+40increment:T1andT2both fetched the initial valueX = 500.T1stored its updated value540.T2computed500 - 25 = 475from its outdated read and overwrote540with475.
T1's+40update vanished completely — the final state475looks as ifT1never 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.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 500Neither 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
T1andT2observe the clean, already-committed value500. - Not A (unrepeatable read):
T1fetchesXonce (step 1) andT2fetchesXonce (step 2). Neither session ever readsXa second time.
- Not C (dirty read): Both reads happen at steps 1 and 2, before any write occurs at steps 3 and 4. Both
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:
T2waits to read untilT1commits (R1 -> W1(540) -> Commit1 -> R2(540) -> W2(515) -> Commit2):T2observes540and writes540 - 25 = 515, matching a serial schedule with zero anomalies (Option B).T2reads afterT1writes, beforeT1commits (R1 -> W1(540) -> R2(540)):T2observes uncommitted data, which is a dirty read (Option C). IfT1subsequently rolls back (aborts and restoresXto500),T2acted on a540that officially never existed.T1queriesXtwice whileT2updatesXin between (R1(500) -> W2(475) -> Commit2 -> R1(475)): The same sessionT1observes500first and475second, which is an unrepeatable read (Option A).- Row write locks held until commit: Even when a database engine blocks
T2's step-4 write untilT1commits540(preventing an uncommitted dirty write),T2still writes475computed from its stale step-2 read of500once the lock releases, soT1's+40update is still lost! - Atomic in-place SQL
UPDATEvs. application read-modify-write: IssuingUPDATE inventory SET x = x + 40andUPDATE inventory SET x = x - 25directly 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 cached500became stale: An unrepeatable read requires the same transaction to readXat least twice and observe two different values; here each session readsXonly 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 defaultREPEATABLE READ, a plainSELECTfollowed by an application-computedUPDATEstill 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, forcingT2to wait untilT1commits) or apply optimistic concurrency control (storing aversioncolumn and executingUPDATE 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 COMMITTEDpermits the lost update everywhere because plainSELECTqueries release read locks immediately. UnderREPEATABLE READ, PostgreSQL uses snapshot isolation with first-committer-wins conflict detection and abortsT2with a serialization error whenT2tries to overwrite a row modified since its snapshot began, while SQL Server holds shared read locks until commit (causingT1andT2to deadlock so one aborts and retries). By contrast, MySQL InnoDB's defaultREPEATABLE READserves a lock-free snapshot on plainSELECTyet lets a subsequentUPDATEoverwrite the newest row without aborting — so InnoDB still requiresFOR UPDATE, optimistic versioning, orSERIALIZABLE. - 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 that2doctors are currently scheduled, and each updates their own shift record to sign off, leaving0doctors on duty. Snapshot isolation automatically blocks lost updates on a single row, whereas preventing write skew across multiple rows requiresSERIALIZABLEisolation or explicitSELECT ... FOR UPDATElocks on the queried rows.
Follow-up questions
- Which SQL patterns or locking mechanisms prevent this lost update in a production application?
- How do standard SQL isolation levels (Read Committed, Repeatable Read, and Serializable) behave on this read-modify-write schedule across major databases?
- How is a lost update different from write skew when two transactions run concurrently?
Similar questions
- TCP Handshake Endpoint State Transitions
- Effective Prompting Strategies for AI-Assisted Debugging
- Midpoint Probe Counts in Binary Search
- Iteration Count of a C For-Loop with Assignment
- Smallest 8-Bit Two's-Complement Number Using Three Set Bits
- Spotting the Flawed HTTP Status Code Claim
More Bitkernel interview questions
- TCP Handshake Endpoint State Transitions Medium
- Effective Prompting Strategies for AI-Assisted Debugging Medium
- Midpoint Probe Counts in Binary Search Medium Pro
- Iteration Count of a C For-Loop with Assignment Medium Pro
- Smallest 8-Bit Two's-Complement Number Using Three Set Bits Medium Pro
- Spotting the Flawed HTTP Status Code Claim Medium Pro
- Popup Dialog Followed by Conditional Page Redirect Hard Pro
- Conceptual Evaluation Order of SQL Clauses Medium Pro
- Deduce Contents from Four Labeled Cups Medium Pro
- Array State After Initial Max-Heap Extraction Medium Pro