Reconcile Cached Coverage Status with Out-of-Order Checks
Data Structure DesignModel answerLast updated
Build a reconciler that keeps a cached insurance status correct when verification results arrive late, duplicated, or as failures, and that can rebuild the status from full history.
Context
A clinical dashboard lists patients along with their insurance coverage status. To keep roster pages fast, each UserInsurance row stores a denormalized copy of the latest status (cached_status) and the time it was confirmed (last_verified_at). The source of truth is an append-only log of EligibilityLookup records, written by scheduled jobs and by webhooks from an external clearinghouse.
Because jobs and webhooks run concurrently and deliveries can be delayed or repeated, the cache is often wrong. A late INACTIVE result can overwrite a newer ACTIVE one, and a failed call can erase a perfectly good verification.
Data models
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Optional
class Status(str, Enum):
ACTIVE = "ACTIVE"
INACTIVE = "INACTIVE"
PENDING = "PENDING"
ERROR = "ERROR"
@dataclass
class EligibilityLookup:
id: str
user_insurance_id: str
status: Status
checked_at: datetime
error_code: Optional[str] = None
@dataclass
class UserInsurance:
id: str
patient_id: str
cached_status: Status
last_verified_at: Optional[datetime]
version: int = 0
Your task
Implement EligibilityReconciler:
class EligibilityReconciler:
def record_lookup(self, user_insurance: UserInsurance,
lookup: EligibilityLookup) -> UserInsurance:
"""Apply one new lookup to the cached record, honoring the rules below.
Return the resulting UserInsurance."""
def reconcile_from_history(self, user_insurance: UserInsurance,
lookups: list[EligibilityLookup]) -> UserInsurance:
"""Rebuild the correct cached state from the complete lookup history,
repairing any out-of-order or corrupted cache values."""
Rules
- Time never goes backwards. If
lookup.checked_atis strictly earlier thanlast_verified_at, the lookup must not changecached_status. - Errors are not answers. A lookup with status
ERROR(a communication failure with the third party) must never replace an existingACTIVEorINACTIVEstate. If the record has never been verified (last_verified_at is None), anERRORlookup does setcached_statustoERROR. - Deterministic ties. When two lookups share the same
checked_at,ACTIVEbeatsINACTIVE, and both beatPENDING. - Versioning. Each real change to the record increases
versionby exactly 1. If the lookup leaves the cached values unchanged,versionstays the same.
Example
t0 = datetime(2025, 1, 1, 10, 0, 0)
t1 = datetime(2025, 1, 1, 10, 5, 0)
insurance = UserInsurance(id="ins_1", patient_id="pat_1",
cached_status=Status.ACTIVE,
last_verified_at=t1, version=1)
late = EligibilityLookup(id="chk_old", user_insurance_id="ins_1",
status=Status.INACTIVE, checked_at=t0)
result = EligibilityReconciler().record_lookup(insurance, late)
assert result.cached_status == Status.ACTIVE
assert result.last_verified_at == t1
assert result.version == 1 # nothing changed
What to deliver
Write both methods, explain your design choices, and describe how you handle edge cases such as duplicate deliveries, an empty history, a history of only errors, and lookups belonging to a different insurance record.
Hints
Hint 1
Stop thinking in terms of arrival order. Ask what single value the cache should equal if you could see every lookup at once, then make incremental updates converge to that value.
Hint 2
Split statuses into two groups: ACTIVE, INACTIVE and PENDING are real answers that compete on (checked_at, precedence), while ERROR carries no coverage information and only fills in when nothing has ever been verified. Decide whether an ERROR should set last_verified_at.
Hint 3
Write one pure function that maps (current state, lookup) to a new state. record_lookup applies it once; reconcile_from_history folds it over the history starting from a blank state. Bump version in one place only, by comparing old and new (status, timestamp).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The bug comes from "last write wins by arrival time". The fix is to make the cached fields a deterministic function of the set of lookups, independent of delivery order, retries, or duplicates.
Treat the statuses in two classes:
- Conclusive answers:
ACTIVE,INACTIVE,PENDING. They compete using the key(checked_at, precedence)withACTIVE > INACTIVE > PENDING. The cached state is the maximum under this key. - Failures:
ERROR. They say nothing about coverage, so they matter only when there is nothing better, meaning the record has never been verified.
Taking a maximum is commutative, associative and idempotent. Any ordering of the same lookups, with any duplicates, yields the same final state. That is exactly what lets the incremental path and the batch repair path agree.
Design decisions worth stating
ERRORdoes not setlast_verified_at. A failed call is not a verification. If it stamped a timestamp, a failure at 10:10 would block a legitimate (late-arriving) success from 10:05. Leaving the timestampNonemeans a later conclusive lookup, even an older one, still applies.- One shared transition function.
record_lookupruns it once;reconcile_from_historyfolds it over all lookups from a blank state. There is no second code path to drift out of sync. - Return a new object (
dataclasses.replace) instead of mutating. The caller can then do a conditional write on the originalversion, giving optimistic concurrency. The in-memory logic here is only half of the production fix; the database update should beUPDATE ... WHERE id = ? AND version = ?, with a retry on conflict. - Version bump in one place. Compare
(cached_status, last_verified_at)before and after; increment only if they differ. A newer lookup with the same status still moves the timestamp forward, so it counts as a change.
Transition rules
For a conclusive lookup, with v = last_verified_at:
v is None: accept.checked_at > v: accept.checked_at == vand the incoming precedence is strictly higher than the current status: accept.- Otherwise ignore.
For an ERROR lookup: set ERROR (timestamp stays None) only if v is None and the current status is not ACTIVE/INACTIVE. Otherwise ignore.
Code
from dataclasses import replace
_RANK = {Status.ACTIVE: 3, Status.INACTIVE: 2, Status.PENDING: 1, Status.ERROR: 0}
_FINAL = {Status.ACTIVE, Status.INACTIVE}
class EligibilityReconciler:
def record_lookup(self, user_insurance, lookup):
self._check_owner(user_insurance, lookup)
state = (user_insurance.cached_status, user_insurance.last_verified_at)
return self._commit(user_insurance, self._apply(state, lookup))
def reconcile_from_history(self, user_insurance, lookups):
if not lookups: # no evidence: do not wipe the cache
return user_insurance
for lk in lookups:
self._check_owner(user_insurance, lk)
state = (Status.PENDING, None) # blank "never verified" state
for lk in sorted(lookups, key=lambda l: (l.checked_at, _RANK[l.status])):
state = self._apply(state, lk)
return self._commit(user_insurance, state)
@staticmethod
def _apply(state, lk):
status, verified = state
if lk.status is Status.ERROR:
if verified is None and status not in _FINAL:
return (Status.ERROR, None)
return state
if (verified is None
or lk.checked_at > verified
or (lk.checked_at == verified and _RANK[lk.status] > _RANK[status])):
return (lk.status, lk.checked_at)
return state
@staticmethod
def _commit(ins, state):
if state == (ins.cached_status, ins.last_verified_at):
return ins
return replace(ins, cached_status=state[0],
last_verified_at=state[1], version=ins.version + 1)
@staticmethod
def _check_owner(ins, lk):
if lk.user_insurance_id != ins.id:
raise ValueError("lookup belongs to a different insurance record")
Why the rules hold
- Monotonic time: a conclusive lookup is accepted only if the stored timestamp is empty, older, or equal with higher precedence, so the timestamp never decreases and an older lookup never touches the status.
- Errors: an error can only ever move a never-verified record to
ERROR, and since the timestamp staysNone, the error never "sticks". - Ties: precedence decides equal-timestamp conflicts regardless of arrival order.
- Version: a single comparison in
_commitguarantees no-ops leave it unchanged.
Complexity
record_lookup: O(1) time and space.reconcile_from_history: O(n log n) for the sort and O(n) space. Because the reducer is commutative, a single O(n) pass keeping the maximum would also work. Sorting is optional but makes the audit trail easy to read.
Edge cases
- Stale lookup (the example): no-op, version unchanged.
- Duplicate webhook delivery: the second application is a no-op.
ERRORfirst, then an olderACTIVE: theACTIVEapplies, because the error left no timestamp.ERRORafter a verification: ignored.- Same
checked_atforACTIVEandINACTIVE:ACTIVEwins in either order. - Newer lookup with identical status: the timestamp advances and the version increments.
- Empty history: return the record unchanged.
- History with only errors: result is
ERRORwith aNonetimestamp, which also repairs rows that claim a verification nobody can prove. - Lookup for another record: raise
ValueError. - Mixed naive and timezone-aware datetimes raise
TypeErroron comparison, so normalize to UTC at ingestion.
Common mistakes
- Using arrival order or "latest row inserted" as the tiebreaker.
- Letting
ERRORwrite a timestamp, which blocks later valid results. - Bumping
versionon every call rather than only on real changes. - Having separate logic for the incremental and batch paths, so they disagree.
- Ignoring concurrency: pure in-memory correctness still needs a version-checked write at the storage layer.