Replay-Safe Versioned Record Updates Simulator
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a record store that applies updates with optimistic version checks and per-record idempotency keys, replaying cached results for retries and rejecting reused keys.
Replay-Safe Versioned Record Updates
Clients of a data store often retry requests that appear to have failed, and several clients may try to modify the same record at once. A well-behaved store must make retries harmless (idempotency) and must refuse writes made against an outdated view of a record (optimistic concurrency).
You are given a script of operations to run against a fresh, empty in-memory store. Simulate the store and return the result of every operation, in order.
Records
A record is a dictionary with these fields:
"record_id": the string identifier"version": an integer, which is1when the record is created and goes up by exactly 1 per successful update"data": a dictionary of string keys to primitive values"updated_at": a number,0.0at creation, and later thecurrent_timeof the latest successful update
Operations
operations[i] is the name of the i-th operation, and arguments[i] is its list of arguments.
"put_initial" with arguments [record_id, data]
- Creates the record with version
1, a copy ofdata, andupdated_at = 0.0. - If a record with this id already exists, it is replaced entirely by the new version-1 record. Idempotency history already stored for that id is not cleared.
- The result is the newly created record (a dictionary).
"update_record" with arguments [record_id, expected_version, updates, idempotency_key, current_time]
The result is a three-element list [success, record, message]. Evaluate these checks in exactly this order and stop at the first one that applies:
- Unknown record. If no record with
record_idexists, return[False, None, "NOT_FOUND"]. - Key already used on this record. Idempotency keys are scoped per record, so the same key on two different records is two unrelated requests. If
idempotency_keywas previously stored for this record:- If the earlier request had the same
expected_versionand an equalupdatesdictionary (ordinary equality, so key order is irrelevant), return[True, saved_record, "IDEMPOTENT_REPLAY"]. Heresaved_recordis the record exactly as it was returned by that earlier successful call. Nothing in the store changes, even if the record has been updated several times since. - Otherwise return
[False, None, "IDEMPOTENCY_CONFLICT"].
- If the earlier request had the same
- Stale version. If
expected_versiondiffers from the record's current version, return[False, current_record, "VERSION_MISMATCH"], wherecurrent_recordis the record as it stands now. Nothing is stored for this key, so a later request reusing the key is evaluated from scratch. - Apply. Otherwise:
- Merge
updatesinto the record'sdata(top-level keys are overwritten or added; there is no deep merge). - Increase
versionby 1. - Set
updated_attocurrent_time. - Remember the request (its
expected_versionandupdates) together with a snapshot of the new record underidempotency_keyfor this record. - Return
[True, new_record, "OK"].
- Merge
An empty updates dictionary is a valid update: the version and timestamp still change.
Only successful updates ("OK") are remembered. Rejected requests leave no trace.
Errors
- Raise
ValueErrorif an"update_record"operation does not have exactly five arguments. - Raise
ValueErrorif an operation name is neither"put_initial"nor"update_record".
Output
Return a list with one entry per operation: a record dictionary for "put_initial", and a [success, record, message] list for "update_record". Results must be independent of the store's internal state, so later operations must not change a result that was already returned.
Constraints
operationsandargumentshave the same length.record_idandidempotency_keyare non-empty strings of length at most 128.updatesanddatahave string keys and primitive values (numbers, strings, booleans, null).expected_versionis an integer andcurrent_timeis a number.
Examples
Example 1
Input: simulate_record_store(['put_initial', 'update_record', 'update_record', 'update_record'], [['user_1', {'name': 'Alice', 'role': 'member'}], ['user_1', 1, {'role': 'admin'}, 'key-100', 1000], ['user_1', 1, {'role': 'admin'}, 'key-100', 1005], ['user_1', 1, {'role': 'editor'}, 'key-200', 1010]])
Output: [{'record_id': 'user_1', 'version': 1, 'data': {'name': 'Alice', 'role': 'member'}, 'updated_at': 0}, [True, {'record_id': 'user_1', 'version': 2, 'data': {'name': 'Alice', 'role': 'admin'}, 'updated_at': 1000}, 'OK'], [True, {'record_id': 'user_1', 'version': 2, 'data': {'name': 'Alice', 'role': 'admin'}, 'updated_at': 1000}, 'IDEMPOTENT_REPLAY'], [False, {'record_id': 'user_1', 'version': 2, 'data': {'name': 'Alice', 'role': 'admin'}, 'updated_at': 1000}, 'VERSION_MISMATCH']]
Example 2
Input: simulate_record_store(['update_record'], [['missing', 1, {'x': 1}, 'key', 1]])
Output: [[False, None, 'NOT_FOUND']]
Example 3
Input: simulate_record_store(['put_initial', 'update_record', 'update_record'], [['r', {'n': 0}], ['r', 1, {'n': 1}, 'k', 10], ['r', 1, {'n': 2}, 'k', 11]])
Output: [{'record_id': 'r', 'version': 1, 'data': {'n': 0}, 'updated_at': 0}, [True, {'record_id': 'r', 'version': 2, 'data': {'n': 1}, 'updated_at': 10}, 'OK'], [False, None, 'IDEMPOTENCY_CONFLICT']]
Example 4
Input: simulate_record_store(['put_initial', 'update_record', 'update_record'], [['r', {'x': 1}], ['r', 1, {'x': 2}, 'k', 1], ['r', 2, {'x': 3}, 'k2', 2]])
Output: [{'record_id': 'r', 'version': 1, 'data': {'x': 1}, 'updated_at': 0}, [True, {'record_id': 'r', 'version': 2, 'data': {'x': 2}, 'updated_at': 1}, 'OK'], [True, {'record_id': 'r', 'version': 3, 'data': {'x': 3}, 'updated_at': 2}, 'OK']]
Hints
Hint 1
Process the operations one by one while keeping two dictionaries: the current record for each id, and for each id a map from idempotency key to (request fingerprint, saved result).
Hint 2
Order of the checks matters: a retry carries the old expected version, so the idempotency lookup must happen before the version comparison, otherwise valid retries would look like version mismatches.
Hint 3
Store a deep-copied snapshot at commit time and return deep copies everywhere, so a replay returns the old record rather than the live one and callers cannot alias internal state.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through the script once, keeping two pieces of state:
records: record id to its current record.seen: record id to a map from idempotency key to(payload, snapshot), wherepayload = (expected_version, updates)andsnapshotis a copy of the record right after that update committed.
For put_initial, build a fresh version-1 record (overwriting any existing one) and return a copy.
For update_record, apply the checks in the required order:
- Missing record gives
NOT_FOUND. - If the key is already stored for this record, compare payloads. An equal payload returns the saved snapshot as
IDEMPOTENT_REPLAY. A different payload returnsIDEMPOTENCY_CONFLICT. - If
expected_versiondiffers from the current version, returnVERSION_MISMATCHwith the current record. - Otherwise merge the updates, bump the version, set the timestamp, store the key with its payload and snapshot, and return
OK.
Why it is correct
- Idempotency before version check. A retry carries the pre-update
expected_version, which no longer matches the record. Checking the key first lets legitimate retries succeed as replays instead of failing as mismatches. - Stable replays. The snapshot is taken when the update commits, so a replay returns what the original call returned even if the record has changed since.
- No side effects on rejection. Only
OKoutcomes write toseen, so mismatches leave no trace and can be retried freely. - Key misuse detection. Comparing
(expected_version, updates)with==treats dictionaries with the same entries as equal regardless of order, while any real difference is reported as a conflict. - Isolation. Deep copies on input and output stop returned results from aliasing internal state, so later operations cannot alter earlier results.
Complexity
Let U be the size of updates and D the size of the record's data.
- Time: O(U + D) per operation, from copying and comparing; dictionary lookups are O(1) on average.
- Space: O(R * D + K * D) for R records and K stored idempotency keys, since each key keeps a snapshot.
Reference solution
from copy import deepcopy
from typing import Any, List
def simulate_record_store(operations: List[str], arguments: List[List[Any]]) -> List[Any]:
records = {}
seen = {} # record_id -> {key: (payload, snapshot)}
results = []
for operation, args in zip(operations, arguments):
if operation == "put_initial":
record_id, data = args
record = {
"record_id": record_id,
"version": 1,
"data": deepcopy(data),
"updated_at": 0.0,
}
records[record_id] = record
results.append(deepcopy(record))
elif operation == "update_record":
if len(args) != 5:
raise ValueError("update_record requires five arguments")
record_id, expected_version, updates, key, current_time = args
if record_id not in records:
results.append([False, None, "NOT_FOUND"])
continue
record_keys = seen.setdefault(record_id, {})
payload = (expected_version, deepcopy(updates))
if key in record_keys:
previous_payload, snapshot = record_keys[key]
if previous_payload == payload:
results.append([True, deepcopy(snapshot), "IDEMPOTENT_REPLAY"])
else:
results.append([False, None, "IDEMPOTENCY_CONFLICT"])
continue
current = records[record_id]
if expected_version != current["version"]:
results.append([False, deepcopy(current), "VERSION_MISMATCH"])
continue
updated = deepcopy(current)
updated["data"].update(deepcopy(updates))
updated["version"] += 1
updated["updated_at"] = current_time
records[record_id] = updated
record_keys[key] = (payload, deepcopy(updated))
results.append([True, deepcopy(updated), "OK"])
else:
raise ValueError("Unknown operation: " + str(operation))
return results