Insurance Coverage Cache Reconciler
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
A clinical scheduling application stores each member's current coverage summary directly on a UserInsurance record (cached_status and last_verified_at) so staff roster screens can render without querying historical logs. Separately, background polling workers and asynchronous payer callbacks append immutable EligibilityLookup records whenever an external check finishes.
Because network callbacks can arrive out of chronological order, be delivered more than once, or fail mid-flight due to upstream outages, naive "overwrite on arrival" logic corrupts UserInsurance—for instance, letting a delayed check from ten minutes ago overwrite a newer result, or letting a gateway timeout wipe out confirmed coverage.
Implement EligibilityReconciler using the data definitions below so incremental updates and full-history repairs always converge to the same deterministic coverage state:
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import List, 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
class EligibilityReconciler:
def record_lookup(
self,
user_insurance: UserInsurance,
lookup: EligibilityLookup,
) -> UserInsurance:
...
def reconcile_from_history(
self,
user_insurance: UserInsurance,
lookups: List[EligibilityLookup],
) -> UserInsurance:
...
Your implementation must enforce the following rules:
- Record matching: Every
EligibilityLookuppassed torecord_lookupor included inlookupsforreconcile_from_historymust havelookup.user_insurance_id == user_insurance.id; otherwise raiseValueError. - Non-decreasing verification time: Payer responses (
ACTIVE,INACTIVE,PENDING) are ordered bychecked_at. Whenlast_verified_atis already populated, any lookup withchecked_at < last_verified_atmust be ignored. Whenlast_verified_at is Noneorlookup.checked_at > last_verified_at, a non-ERRORlookup updates bothcached_statusandlast_verified_at. - Upstream communication errors (
Status.ERROR): AnERRORlookup indicates a transport or gateway failure rather than a payer coverage decision. It must never overwriteACTIVEorINACTIVE, and it must never set or advancelast_verified_at. Only when a record has never been verified (last_verified_at is None) and itscached_statusis neitherACTIVEnorINACTIVEdoes anERRORsetcached_status = Status.ERROR(leavinglast_verified_atasNone). - Same-timestamp priority: If a non-
ERRORlookup haschecked_at == last_verified_at, break ties strictly in orderACTIVE > INACTIVE > PENDING. Equal- or lower-priority statuses at the same timestamp leave the cached state untouched. - Version bumps and immutability: Whenever
cached_statusorlast_verified_atchanges, return a newUserInsuranceinstance withversionincreased by1(leaving the input object unmutated). When neither field changes,versionmust not change. - Full-history repair (
reconcile_from_history): Ignore the currentcached_statusandlast_verified_atonuser_insuranceand recompute the canonical pair fromlookupsstarting from an unverified baseline(Status.PENDING, None)under Rules 1–4. Compare only the final recomputed pair againstuser_insurance: incrementversionby1if the repaired state differs from the existing row, or keepversionunchanged if they already match.
Examples
Example 1
policy = UserInsurance(
id="pol_42",
patient_id="mem_9",
cached_status=Status.ACTIVE,
last_verified_at=datetime(2026, 3, 15, 14, 20, 0),
version=2,
)
delayed_check = EligibilityLookup(
id="lkp_101",
user_insurance_id="pol_42",
status=Status.INACTIVE,
checked_at=datetime(2026, 3, 15, 14, 12, 0),
)
timeout_check = EligibilityLookup(
id="lkp_102",
user_insurance_id="pol_42",
status=Status.ERROR,
checked_at=datetime(2026, 3, 15, 14, 25, 0),
error_code="GATEWAY_TIMEOUT",
)
reconciler = EligibilityReconciler()
after_delayed = reconciler.record_lookup(policy, delayed_check)
after_timeout = reconciler.record_lookup(after_delayed, timeout_check)
# Both return:
# UserInsurance(id="pol_42", patient_id="mem_9", cached_status=Status.ACTIVE,
# last_verified_at=datetime(2026, 3, 15, 14, 20, 0), version=2)
Walk-through: delayed_check carries checked_at = 14:12:00, which is earlier than 14:20:00, so Rule 2 ignores it. Next, timeout_check arrives with a newer timestamp (14:25:00) but status = Status.ERROR; Rule 3 prevents ERROR from replacing ACTIVE or advancing last_verified_at. Because neither call alters the cached fields, version stays 2.
Example 2
corrupted_policy = UserInsurance(
id="pol_77",
patient_id="mem_3",
cached_status=Status.INACTIVE,
last_verified_at=datetime(2026, 3, 15, 16, 0, 0),
version=5,
)
lookups = [
EligibilityLookup("lkp_d", "pol_77", Status.ERROR, datetime(2026, 3, 15, 9, 50, 0), "UPSTREAM_503"),
EligibilityLookup("lkp_b", "pol_77", Status.INACTIVE, datetime(2026, 3, 15, 9, 45, 0)),
EligibilityLookup("lkp_a", "pol_77", Status.PENDING, datetime(2026, 3, 15, 9, 30, 0)),
EligibilityLookup("lkp_c", "pol_77", Status.ACTIVE, datetime(2026, 3, 15, 9, 45, 0)),
]
repaired = EligibilityReconciler().reconcile_from_history(corrupted_policy, lookups)
# Returns:
# UserInsurance(id="pol_77", patient_id="mem_3", cached_status=Status.ACTIVE,
# last_verified_at=datetime(2026, 3, 15, 9, 45, 0), version=6)
Walk-through: reconcile_from_history discards the bogus cached 16:00:00 state and folds from (Status.PENDING, None). Chronologically, 09:30:00 PENDING sets (PENDING, 09:30:00), 09:45:00 INACTIVE advances to (INACTIVE, 09:45:00), 09:45:00 ACTIVE wins the exact-timestamp tie (ACTIVE > INACTIVE), and 09:50:00 ERROR is ignored. Because (ACTIVE, 09:45:00) differs from (INACTIVE, 16:00:00), version increments once from 5 to 6.
Constraints
0 <= len(lookups) <= 10^5- All
datetimevalues within a call are comparable (either all naive UTC timestamps or all timezone-aware). user_insurance.version >= 0record_lookupmust run inO(1)time andreconcile_from_historyinO(m log m)time or better form = len(lookups).
Step-by-step walkthrough
Understand the goal and pin down the rules
In this architecture,
EligibilityLookupserves as an append-only log (each external payer response is written once and never mutated), whereasUserInsurancestores denormalized summary fields (cached_statusandlast_verified_at) directly on the policy row so roster screens can render quickly without scanning historical events.We need two pure methods on
EligibilityReconciler:record_lookup(user_insurance, lookup): fold one newly delivered lookup into the summary row.reconcile_from_history(user_insurance, lookups): disregard the existing cached fields (which may be stale or damaged) and rebuild the canonical summary from the complete lookup list.
Before writing code, let's clarify the exact edge-case contracts required by the rules:
ERRORnever setslast_verified_at. A gateway timeout did not verify coverage. If anERRORat14:25setlast_verified_at = 14:25, then a validACTIVEcheck completed at14:20that arrived late would appear older than14:25and be discarded forever.ERRORonly marks an unverified policy. It setscached_status = Status.ERROR(keepinglast_verified_at = None) only whenlast_verified_at is Noneandcached_statusis neitherACTIVEnorINACTIVE.PENDINGis a real payer status. UnlikeERROR,PENDINGadvanceslast_verified_atand participates in same-timestamp priority (ACTIVE > INACTIVE > PENDING).- A history rebuild increments
versionat most once.reconcile_from_historystarts from(Status.PENDING, None)and compares only the final rebuilt pair againstuser_insurance, adding1toversionif anything changed and0otherwise. - Record matching and immutability. Passing a lookup whose
user_insurance_iddiffers fromuser_insurance.idraisesValueError. Whenever state changes, we return a newUserInsurancecopy viadataclasses.replacerather than mutating the caller's instance.
Diagnose the bug: why "last writer wins" fails
Stale statuses appear in production when background consumers blindly overwrite
UserInsurancein whatever order callbacks arrive over the network:def broken_record_lookup(user_insurance, lookup): # Bug: overwrites based on arrival order instead of checked_at, and treats ERROR like a real status! user_insurance.cached_status = lookup.status user_insurance.last_verified_at = lookup.checked_at user_insurance.version += 1 return user_insuranceWatch how Example 1's sequence (
pol_42) breaks under naive arrival-order writes:Arrival Event Broken cache result ------- ----------------------------------------- --------------------------------------------- 14:12 Slow polling worker starts check (14:12) (still in flight...) 14:20 Fast callback lands: ACTIVE @ 14:20 ACTIVE @ 14:20 (correct) 14:22 Slow worker finishes: INACTIVE @ 14:12 INACTIVE @ 14:12 <-- BUG 1: time went backward! 14:25 Gateway timeout lands: ERROR @ 14:25 ERROR @ 14:25 <-- BUG 2: valid answer erased!Network delivery order is unreliable because callbacks retry and polling queues back up. Every update must instead be judged by when coverage was actually checked (
checked_at) and whether the lookup carries a real payer status or a transport failure.Key insight: order real answers by (checked_at, rank)
For genuine payer responses (
ACTIVE,INACTIVE,PENDING), Rules 2 and 4 keep whichever lookup has the newestchecked_at, breaking exact ties in orderACTIVE > INACTIVE > PENDING.Mapping each status to an integer rank turns both rules into a single tuple comparison on
(checked_at, STATUS_RANK[status]):# STATUS_RANK: maps each Status to its integer tie-breaker priority -> {ACTIVE: 3, INACTIVE: 2, PENDING: 1, ERROR: 0}. # Higher numbers win when two lookups share the exact same checked_at timestamp. # ERROR gets 0 so any real answer at the same timestamp replaces a damaged ERROR row. STATUS_RANK: Dict[Status, int] = { Status.ACTIVE: 3, Status.INACTIVE: 2, Status.PENDING: 1, Status.ERROR: 0, } # CONCLUSIVE_STATUSES: definitive coverage answers that a transient network ERROR must never erase. CONCLUSIVE_STATUSES: Tuple[Status, Status] = (Status.ACTIVE, Status.INACTIVE)Because Python compares tuples left to right—checking
checked_atfirst and consultingSTATUS_RANKonly on an exact tie—retaining the maximum(checked_at, rank)guarantees two properties automatically:- Order independence: Whether
[INACTIVE @ 14:12, ACTIVE @ 14:20]arrives chronologically or in reverse,ACTIVE @ 14:20wins. - Idempotency (processing the same callback twice has the exact same effect as processing it once): Replaying
ACTIVE @ 14:20fails the strict>check, leaving state andversionuntouched.
- Order independence: Whether
Handle transient ERROR lookups without blocking real answers
Next, let's build
_compute_next_state(current_status, current_verified_at, lookup), which takes the current cached pair and one lookup and returns the resulting(status, last_verified_at)pair.We split the transition into three clear phases:
- Upstream
ERROR(Rule 3): Ifcurrent_verified_at is Noneandcurrent_statusis not in(ACTIVE, INACTIVE), return(Status.ERROR, None). Otherwise keep(current_status, current_verified_at). - First or strictly newer payer check (Rule 2): If
current_verified_at is Noneorlookup.checked_at > current_verified_at, accept(lookup.status, lookup.checked_at). - Identical timestamp tie (Rule 4): If
lookup.checked_at == current_verified_at, acceptlookup.statusstrictly whenSTATUS_RANK[lookup.status] > STATUS_RANK[current_status]. Using strict>guarantees duplicate callbacks and weaker statuses are clean no-ops.
def _compute_next_state( current_status: Status, current_verified_at: Optional[datetime], lookup: EligibilityLookup, ) -> Tuple[Status, Optional[datetime]]: """Compute the next (cached_status, last_verified_at) pair without mutating any object.""" # Phase 1: Handle transient network/clearinghouse failures (Rule 2). if lookup.status == Status.ERROR: # An ERROR verified nothing, so it only marks a never-verified, non-conclusive row. # Keep last_verified_at as None so an earlier real check arriving late can still win. if current_verified_at is None and current_status not in CONCLUSIVE_STATUSES: return Status.ERROR, None return current_status, current_verified_at # Phase 2: Handle real payer responses (ACTIVE, INACTIVE, PENDING). # If the row has never been verified or this lookup is strictly newer, accept it (Rule 1). if current_verified_at is None or lookup.checked_at > current_verified_at: return lookup.status, lookup.checked_at # Phase 3: Break exact timestamp ties by status precedence (Rule 3). # Strict '>' ensures duplicate deliveries or weaker ties leave the cached state untouched. if lookup.checked_at == current_verified_at: if STATUS_RANK[lookup.status] > STATUS_RANK[current_status]: return lookup.status, current_verified_at # Incoming lookup is strictly older than current_verified_at, or lost a timestamp tie. return current_status, current_verified_at- Upstream
Increment version only when cached state changes
Rule 5 bumps
versionby1if and only if(cached_status, last_verified_at)actually changes. Avoiding version bumps on ignored callbacks keeps retry storms from triggering spurious database write conflicts.Let's write
_validate_same_insuranceto reject mismatched policy IDs and_build_updated_rowto construct the updatedUserInsuranceinstance:def _validate_same_insurance( user_insurance: UserInsurance, lookup: EligibilityLookup, ) -> None: """Reject lookups that belong to a different UserInsurance record.""" if lookup.user_insurance_id != user_insurance.id: raise ValueError( f"lookup {lookup.id} belongs to {lookup.user_insurance_id}, " f"not {user_insurance.id}" ) def _build_updated_row( user_insurance: UserInsurance, next_status: Status, next_verified_at: Optional[datetime], ) -> UserInsurance: """Return a new UserInsurance with version + 1 if state changed, or the original row if not.""" # Rule 4: Do not increment version when cached_status and last_verified_at are unchanged. state_unchanged = ( next_status == user_insurance.cached_status and next_verified_at == user_insurance.last_verified_at ) if state_unchanged: return user_insurance # Return a fresh copy so the caller can still inspect user_insurance.version for DB locking. return replace( user_insurance, cached_status=next_status, last_verified_at=next_verified_at, version=user_insurance.version + 1, )With those helpers ready,
record_lookupvalidates the ID, computes the next pair, and returns_build_updated_row(...).Rebuild a damaged cache from the full history
Consider Example 2 (
pol_77): a past bug leftuser_insuranceholdingINACTIVE @ 16:00atversion = 5, whereas the audit log only contains checks between09:30and09:50. Ifreconcile_from_historyfolded on top ofuser_insurance, that bogus16:00timestamp would reject every real check inlookups!Instead,
reconcile_from_historydiscards the existing cache fields, resets to(Status.PENDING, None), orderslookupsdeterministically by(checked_at, rank, id), and folds each entry through_compute_next_state:def _history_sort_key(lookup: EligibilityLookup) -> Tuple[datetime, int, str]: """Sort key (checked_at, rank, id): oldest first, stronger tie-breakers last, id for stability.""" return (lookup.checked_at, STATUS_RANK[lookup.status], lookup.id)Tracing Example 2 (
pol_77, cached asINACTIVE @ 16:00, version=5) step by step:Step Sorted lookup Running rebuilt state Why ---- -------------------- ---------------------- --------------------------------------- init (start fresh) (PENDING, None) Ignore corrupt cache (INACTIVE @ 16:00) 1 PENDING @ 09:30 (PENDING, 09:30) First real lookup sets timestamp 2 INACTIVE @ 09:45 (INACTIVE, 09:45) 09:45 > 09:30 -> newer check wins 3 ACTIVE @ 09:45 (ACTIVE, 09:45) Same 09:45 timestamp; ACTIVE > INACTIVE 4 ERROR @ 09:50 (ACTIVE, 09:45) ERROR never overwrites ACTIVE Compare final (ACTIVE, 09:45) vs cached (INACTIVE, 16:00): -> Different! Return UserInsurance(cached_status=ACTIVE, last_verified_at=09:45, version=6).Guard concurrent database writes with optimistic locking
Returning a new
UserInsurancewhile leavinguser_insurance.versionintact lets persistence callers prevent lost updates—the race where two workers read the same row concurrently and the slower writer clobbers the faster one.With optimistic concurrency control (verifying at
UPDATEtime that the row'sversionstill matches what the worker originally read), concurrent writers converge without locking readers:Worker A (has ACTIVE @ 14:20) Worker B (has INACTIVE @ 14:12) --------------------------------------------- --------------------------------------------- 1. SELECT row -> (PENDING, None, version=0) 1. SELECT row -> (PENDING, None, version=0) 2. record_lookup -> (ACTIVE, 14:20, v=1) 2. record_lookup -> (INACTIVE, 14:12, v=1) 3. UPDATE ... SET ..., version = 1 WHERE id = 'pol_42' AND version = 0 -> 1 row updated! (DB is now v=1) 3. UPDATE ... SET ..., version = 1 WHERE id = 'pol_42' AND version = 0 -> 0 rows updated! (Conflict detected) 4. Re-read DB -> (ACTIVE, 14:20, version=1) 5. record_lookup -> unchanged (v=1), stop!Regardless of which worker wins the first database write, both converge cleanly to
(ACTIVE, 14:20, version=1).Complete solution
Putting the data models, pure state-transition helpers, and
EligibilityReconcilertogether gives the complete implementation:from typing import Dict, List, Optional, Tuple from dataclasses import dataclass, replace from datetime import datetime from enum import Enum 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 # STATUS_RANK: maps each Status to its integer tie-breaker priority -> {ACTIVE: 3, INACTIVE: 2, PENDING: 1, ERROR: 0}. # Higher numbers win when two lookups share the exact same checked_at timestamp. # ERROR gets 0 so any real answer at the same timestamp replaces a damaged ERROR row. STATUS_RANK: Dict[Status, int] = { Status.ACTIVE: 3, Status.INACTIVE: 2, Status.PENDING: 1, Status.ERROR: 0, } # CONCLUSIVE_STATUSES: definitive coverage answers that a transient network ERROR must never erase. CONCLUSIVE_STATUSES: Tuple[Status, Status] = (Status.ACTIVE, Status.INACTIVE) def _validate_same_insurance( user_insurance: UserInsurance, lookup: EligibilityLookup, ) -> None: """Reject lookups that belong to a different UserInsurance record.""" if lookup.user_insurance_id != user_insurance.id: raise ValueError( f"lookup {lookup.id} belongs to {lookup.user_insurance_id}, " f"not {user_insurance.id}" ) def _compute_next_state( current_status: Status, current_verified_at: Optional[datetime], lookup: EligibilityLookup, ) -> Tuple[Status, Optional[datetime]]: """Compute the next (cached_status, last_verified_at) pair without mutating any object.""" # Phase 1: Handle transient network/clearinghouse failures (Rule 2). if lookup.status == Status.ERROR: # An ERROR verified nothing, so it only marks a never-verified, non-conclusive row. # Keep last_verified_at as None so an earlier real check arriving late can still win. if current_verified_at is None and current_status not in CONCLUSIVE_STATUSES: return Status.ERROR, None return current_status, current_verified_at # Phase 2: Handle real payer responses (ACTIVE, INACTIVE, PENDING). # If the row has never been verified or this lookup is strictly newer, accept it (Rule 1). if current_verified_at is None or lookup.checked_at > current_verified_at: return lookup.status, lookup.checked_at # Phase 3: Break exact timestamp ties by status precedence (Rule 3). # Strict '>' ensures duplicate deliveries or weaker ties leave the cached state untouched. if lookup.checked_at == current_verified_at: if STATUS_RANK[lookup.status] > STATUS_RANK[current_status]: return lookup.status, current_verified_at # Incoming lookup is strictly older than current_verified_at, or lost a timestamp tie. return current_status, current_verified_at def _build_updated_row( user_insurance: UserInsurance, next_status: Status, next_verified_at: Optional[datetime], ) -> UserInsurance: """Return a new UserInsurance with version + 1 if state changed, or the original row if not.""" # Rule 4: Do not increment version when cached_status and last_verified_at are unchanged. state_unchanged = ( next_status == user_insurance.cached_status and next_verified_at == user_insurance.last_verified_at ) if state_unchanged: return user_insurance # Return a fresh copy so the caller can still inspect user_insurance.version for DB locking. return replace( user_insurance, cached_status=next_status, last_verified_at=next_verified_at, version=user_insurance.version + 1, ) def _history_sort_key(lookup: EligibilityLookup) -> Tuple[datetime, int, str]: """Sort key (checked_at, rank, id): oldest first, stronger tie-breakers last, id for stability.""" return (lookup.checked_at, STATUS_RANK[lookup.status], lookup.id) class EligibilityReconciler: def record_lookup( self, user_insurance: UserInsurance, lookup: EligibilityLookup, ) -> UserInsurance: """Apply a single lookup snapshot while enforcing monotonicity, error, and tie-break rules.""" _validate_same_insurance(user_insurance, lookup) next_status, next_verified_at = _compute_next_state( user_insurance.cached_status, user_insurance.last_verified_at, lookup, ) return _build_updated_row(user_insurance, next_status, next_verified_at) def reconcile_from_history( self, user_insurance: UserInsurance, lookups: List[EligibilityLookup], ) -> UserInsurance: """Rebuild cached state from scratch using all lookups; increment version at most once.""" # Start from a clean, never-verified baseline instead of trusting potentially corrupt cache fields. rebuilt_status: Status = Status.PENDING rebuilt_verified_at: Optional[datetime] = None # Validate every lookup and fold in chronological order. for lookup in sorted(lookups, key=_history_sort_key): _validate_same_insurance(user_insurance, lookup) rebuilt_status, rebuilt_verified_at = _compute_next_state( rebuilt_status, rebuilt_verified_at, lookup, ) # Compare only the final rebuilt state against user_insurance so version increments by 0 or 1. return _build_updated_row(user_insurance, rebuilt_status, rebuilt_verified_at)✅ Submit now — all tests should pass.
Intuition & how it works
Picture UserInsurance as the summary card clipped to the front of a member's folder, and EligibilityLookup as the stack of dated payer letters arriving in the mailroom. Couriers deliver envelopes out of order, and every so often a courier drops off a slip saying "phone line was unreachable" (ERROR). To keep the front summary card accurate, a clerk checks the inspection time printed inside the letter (checked_at) rather than when the courier arrived, ignores "phone line unreachable" slips once a real coverage answer is on file, and breaks exact timestamp ties with a fixed rule (ACTIVE > INACTIVE > PENDING).
Simply overwriting cached_status and last_verified_at whenever a worker finishes fails in two common scenarios. First, as in Example 1, a slow 14:12 check finishing late would overwrite a valid 14:20 ACTIVE result with an outdated INACTIVE answer. Second, a 14:25 gateway timeout (ERROR) would erase confirmed coverage—or, if it updated last_verified_at, block valid earlier checks arriving afterward.
Tracing four out-of-order lookups starting from an unverified policy (cached_status=PENDING, last_verified_at=None, version=0) shows how the rules cooperate:
ERROR @ 09:50arrives first: Becauselast_verified_atisNone,cached_statusbecomesERROR,last_verified_atstaysNone, andversionmoves to1.INACTIVE @ 09:45arrives late: Sincelast_verified_atremainedNone, this real response lands cleanly:(INACTIVE, 09:45, version=2).ACTIVE @ 09:45arrives (timestamp tie):ACTIVE(rank 3) outranksINACTIVE(rank 2) at09:45, updating the row to(ACTIVE, 09:45, version=3).PENDING @ 09:30andERROR @ 09:55arrive:09:30 < 09:45is stale, andERRORnever replacesACTIVE, so the policy stays(ACTIVE, 09:45, version=3).
Complexity
record_lookup: O(1) time and O(1) space. We verify the policy ID, compare at most onedatetimeand one integer rank inSTATUS_RANK, and allocate a newUserInsuranceinstance only when the cached state changes.reconcile_from_history: O(m log m) time and O(m) space, wheremislen(lookups). Sortingmrecords by(checked_at, rank, id)takesO(m log m)time andO(m)auxiliary memory for the sorted list, followed by a singleO(m)fold calling theO(1)transition helper. (Because taking the maximum(checked_at, rank)is commutative, an unsorted linear scan could achieveO(m)time andO(1)extra space, though chronological sorting makes audit logs easier to trace.)
Edge cases
- Duplicate callback deliveries: Applying the identical
EligibilityLookuptwice fails the strict>checks on bothchecked_atandSTATUS_RANK, leavingcached_status,last_verified_at, andversionuntouched. - Tied
checked_attimestamps:ACTIVEoutranksINACTIVEand both outrankPENDING, regardless of arrival order. ERRORarriving before an older valid lookup: Leavinglast_verified_at = Noneon an initialERRORensures a valid check from earlier (09:45arriving after a09:50timeout) still updates the policy.- Back-to-back
ERRORevents: The firstERRORon an unverified row transitionsPENDING -> ERROR(version + 1); any subsequentERRORseescached_status == ERRORand leavesversionunchanged. - Empty history (
lookups = []):reconcile_from_historyresets a corrupted cache back to(PENDING, None)in one version bump, or leaves an already(PENDING, None)row as-is. - Legacy
ACTIVE/INACTIVErows withlast_verified_at = None:CONCLUSIVE_STATUSESshields them fromERRORevents while allowing the next real check to stamplast_verified_at. - Mismatched
user_insurance_id: RaisesValueErrorimmediately so one member's lookup can never corrupt another member's policy.
Common mistakes
- Ordering by arrival wall-clock time (
datetime.now()) instead oflookup.checked_at: Queue backlogs and webhook retries routinely invert delivery order relative to when the payer evaluated coverage. - Advancing
last_verified_atonStatus.ERROR: Stampinglast_verified_aton a network error blocks valid earlier checks that arrive later. - Using
>=instead of>for timestamp ties: Letting equal- or lower-rank statuses overwrite at the samechecked_atmakes outcomes depend on arrival order and bumpsversionon duplicate retries. - Folding
reconcile_from_historyon top of existinguser_insurancefields: If a bug wrote a future timestamp like16:00ontouser_insurance, starting from that row rejects every historical check. Always fold from(Status.PENDING, None). - Incrementing
versioninside the history loop: Repairing a row from 40 historical lookups is a single state repair onUserInsurance, soversionmust increase by1or0, never by up to 40. - Mutating
user_insurancein place: Overwritinguser_insurance.versiondirectly erases the expected version number needed for an optimisticWHERE version = :old_versiondatabase write.
Alternative approaches
- Single conditional SQL
UPDATE: Encode the timestamp, rank tie-breaker, andERRORpredicates directly inside a SQLWHEREclause so PostgreSQL checks and updates the row atomically in a single round-trip without application-side retry loops. - Asynchronous stream projection: Treat
EligibilityLookupas an event stream (an ordered sequence of immutable domain facts) and materializeUserInsurancevia a background consumer, trading a brief projection lag (sub-second delay before roster views reflect a check) for simpler write paths.
Follow-up questions
- How can multiple workers update the same
UserInsurancerecord in PostgreSQL simultaneously without blocking read queries on clinician roster views? PostgreSQL uses MVCC (Multi-Version Concurrency Control)—writers create a new row version while plainSELECTqueries read the latest committed snapshot—so roster reads never wait onUPDATElocks as long as readers avoidSELECT ... FOR UPDATE. To serialize competing writers safely, either issue an optimistic-lock write (UPDATE user_insurance SET ..., version = version + 1 WHERE id = :id AND version = :expected_versionand re-read on0affected rows) or push the transition check directly into an atomic conditionalUPDATE. Under PostgreSQL's defaultREAD COMMITTEDisolation, a concurrent secondUPDATEwaits briefly for the first commit and re-evaluates itsWHEREpredicate against the newly committed row automatically:
-- Atomic conditional UPDATE for a non-ERROR lookup (:rank is 3 for ACTIVE, 2 for INACTIVE, 1 for PENDING)
UPDATE user_insurance
SET cached_status = :status,
last_verified_at = :checked_at,
version = version + 1
WHERE id = :id
AND (
last_verified_at IS NULL
OR last_verified_at < :checked_at
OR (
last_verified_at = :checked_at
AND CASE cached_status
WHEN 'ACTIVE' THEN 3
WHEN 'INACTIVE' THEN 2
WHEN 'PENDING' THEN 1
ELSE 0
END < :rank
)
);
-
Suppose an
ACTIVEpolicy must automatically expire once 30 days pass since its latest active check—how would you enforce that rule without running expensive table scans during reads? Whenevercached_statusequalsACTIVE,last_verified_atalready stores the exact timestamp of that latestACTIVEcheck (any newerINACTIVEorPENDINGcheck would have replacedcached_status, andERRORnever toucheslast_verified_at). That lets the read layer compute lazy expiration on the fly for just the 25–50 policies on screen—effective_status = 'EXPIRED' if (cached_status == 'ACTIVE' and last_verified_at < now - 30 days) else cached_status—inO(1)time per row with zero background sweeps. If SQL queries must filter by expired policies directly, add a partial index (an index restricted to rows matching a predicate),CREATE INDEX ON user_insurance (last_verified_at) WHERE cached_status = 'ACTIVE', and trigger proactive re-checks around day 27 so active members are refreshed before hitting the 30-day cutoff. -
What observability signals, alerting rules, and periodic audit jobs would you put in place to catch divergence between the
EligibilityLookuplog and cachedUserInsurancerows? Emit structured counters fromrecord_lookuplabeled by decision (updated,skipped_older,skipped_tie,skipped_error,duplicate_noop), monitor optimistic-lock retry rates, and track callback lag (now - checked_atat p50 and p99 per payer) to spot stalled queues or upstreamERRORspikes early. To catch cache drift (any discrepancy betweenUserInsuranceand its lookup log), run an incremental audit every 15 minutes overuser_insurance_ids that received lookups since the previous watermark, paired with a nightly full scan. Page or alert when settled rows (no lookups in the past 60 seconds, ruling out in-flight writes) diverge fromreconcile_from_history, and auto-heal drifted rows via version-checked updates.
Follow-up questions
- How can multiple workers update the same `UserInsurance` record in PostgreSQL simultaneously without blocking read queries on clinician roster views?
- Suppose an `ACTIVE` policy must automatically expire once 30 days pass since its latest active check—how would you enforce that rule without running expensive table scans during reads?
- What observability signals, alerting rules, and periodic audit jobs would you put in place to catch divergence between the `EligibilityLookup` log and cached `UserInsurance` rows?
Similar questions
- Global and Per-Domain Fixed-Window Rate Limiter
- Two-Tier Global and Route Rate Limiter
- Incomplete-Data Calls, AI Workflows, and Spec-Driven Engineering
- Course Run Statistics Simulator
- Short-Term Stay Search and Reservation Architecture
- Architecting an E-Commerce Cart with Concurrent Inventory Reservations
More Headway interview questions
- Global and Per-Domain Fixed-Window Rate Limiter Medium
- Incomplete-Data Calls, AI Workflows, and Spec-Driven Engineering Medium
- Course Run Statistics Simulator Medium Pro
- Short-Term Stay Search and Reservation Architecture Medium Pro
- Architecting an E-Commerce Cart with Concurrent Inventory Reservations Medium Pro
- Driving Technical Alignment and Peer Mentorship on a Complex Project Medium Pro
- Alphabetical Letter Combinations from Keypad Digits Medium Pro
- Diagnosing API Overload Surges and Sizing Backend Capacity Medium Pro
- Checkpoint Journey Speed Violation Detector Hard Pro
- Two-Tier Global and Route Rate Limiter Medium Pro