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:

  1. Record matching: Every EligibilityLookup passed to record_lookup or included in lookups for reconcile_from_history must have lookup.user_insurance_id == user_insurance.id; otherwise raise ValueError.
  2. Non-decreasing verification time: Payer responses (ACTIVE, INACTIVE, PENDING) are ordered by checked_at. When last_verified_at is already populated, any lookup with checked_at < last_verified_at must be ignored. When last_verified_at is None or lookup.checked_at > last_verified_at, a non-ERROR lookup updates both cached_status and last_verified_at.
  3. Upstream communication errors (Status.ERROR): An ERROR lookup indicates a transport or gateway failure rather than a payer coverage decision. It must never overwrite ACTIVE or INACTIVE, and it must never set or advance last_verified_at. Only when a record has never been verified (last_verified_at is None) and its cached_status is neither ACTIVE nor INACTIVE does an ERROR set cached_status = Status.ERROR (leaving last_verified_at as None).
  4. Same-timestamp priority: If a non-ERROR lookup has checked_at == last_verified_at, break ties strictly in order ACTIVE > INACTIVE > PENDING. Equal- or lower-priority statuses at the same timestamp leave the cached state untouched.
  5. Version bumps and immutability: Whenever cached_status or last_verified_at changes, return a new UserInsurance instance with version increased by 1 (leaving the input object unmutated). When neither field changes, version must not change.
  6. Full-history repair (reconcile_from_history): Ignore the current cached_status and last_verified_at on user_insurance and recompute the canonical pair from lookups starting from an unverified baseline (Status.PENDING, None) under Rules 1–4. Compare only the final recomputed pair against user_insurance: increment version by 1 if the repaired state differs from the existing row, or keep version unchanged 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 datetime values within a call are comparable (either all naive UTC timestamps or all timezone-aware).
  • user_insurance.version >= 0
  • record_lookup must run in O(1) time and reconcile_from_history in O(m log m) time or better for m = len(lookups).

Step-by-step walkthrough

  1. Understand the goal and pin down the rules

    In this architecture, EligibilityLookup serves as an append-only log (each external payer response is written once and never mutated), whereas UserInsurance stores denormalized summary fields (cached_status and last_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:

    • ERROR never sets last_verified_at. A gateway timeout did not verify coverage. If an ERROR at 14:25 set last_verified_at = 14:25, then a valid ACTIVE check completed at 14:20 that arrived late would appear older than 14:25 and be discarded forever.
    • ERROR only marks an unverified policy. It sets cached_status = Status.ERROR (keeping last_verified_at = None) only when last_verified_at is None and cached_status is neither ACTIVE nor INACTIVE.
    • PENDING is a real payer status. Unlike ERROR, PENDING advances last_verified_at and participates in same-timestamp priority (ACTIVE > INACTIVE > PENDING).
    • A history rebuild increments version at most once. reconcile_from_history starts from (Status.PENDING, None) and compares only the final rebuilt pair against user_insurance, adding 1 to version if anything changed and 0 otherwise.
    • Record matching and immutability. Passing a lookup whose user_insurance_id differs from user_insurance.id raises ValueError. Whenever state changes, we return a new UserInsurance copy via dataclasses.replace rather than mutating the caller's instance.
  2. Diagnose the bug: why "last writer wins" fails

    Stale statuses appear in production when background consumers blindly overwrite UserInsurance in 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_insurance
    

    Watch 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.

  3. 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 newest checked_at, breaking exact ties in order ACTIVE > 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_at first and consulting STATUS_RANK only 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:20 wins.
    • Idempotency (processing the same callback twice has the exact same effect as processing it once): Replaying ACTIVE @ 14:20 fails the strict > check, leaving state and version untouched.
  4. 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:

    1. Upstream ERROR (Rule 3): If current_verified_at is None and current_status is not in (ACTIVE, INACTIVE), return (Status.ERROR, None). Otherwise keep (current_status, current_verified_at).
    2. First or strictly newer payer check (Rule 2): If current_verified_at is None or lookup.checked_at > current_verified_at, accept (lookup.status, lookup.checked_at).
    3. Identical timestamp tie (Rule 4): If lookup.checked_at == current_verified_at, accept lookup.status strictly when STATUS_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
    
  5. Increment version only when cached state changes

    Rule 5 bumps version by 1 if 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_insurance to reject mismatched policy IDs and _build_updated_row to construct the updated UserInsurance instance:

    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_lookup validates the ID, computes the next pair, and returns _build_updated_row(...).

  6. Rebuild a damaged cache from the full history

    Consider Example 2 (pol_77): a past bug left user_insurance holding INACTIVE @ 16:00 at version = 5, whereas the audit log only contains checks between 09:30 and 09:50. If reconcile_from_history folded on top of user_insurance, that bogus 16:00 timestamp would reject every real check in lookups!

    Instead, reconcile_from_history discards the existing cache fields, resets to (Status.PENDING, None), orders lookups deterministically 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 as INACTIVE @ 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).
    
  7. Guard concurrent database writes with optimistic locking

    Returning a new UserInsurance while leaving user_insurance.version intact 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 UPDATE time that the row's version still 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).

  8. Complete solution

    Putting the data models, pure state-transition helpers, and EligibilityReconciler together 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:

  1. ERROR @ 09:50 arrives first: Because last_verified_at is None, cached_status becomes ERROR, last_verified_at stays None, and version moves to 1.
  2. INACTIVE @ 09:45 arrives late: Since last_verified_at remained None, this real response lands cleanly: (INACTIVE, 09:45, version=2).
  3. ACTIVE @ 09:45 arrives (timestamp tie): ACTIVE (rank 3) outranks INACTIVE (rank 2) at 09:45, updating the row to (ACTIVE, 09:45, version=3).
  4. PENDING @ 09:30 and ERROR @ 09:55 arrive: 09:30 < 09:45 is stale, and ERROR never replaces ACTIVE, 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 one datetime and one integer rank in STATUS_RANK, and allocate a new UserInsurance instance only when the cached state changes.
  • reconcile_from_history: O(m log m) time and O(m) space, where m is len(lookups). Sorting m records by (checked_at, rank, id) takes O(m log m) time and O(m) auxiliary memory for the sorted list, followed by a single O(m) fold calling the O(1) transition helper. (Because taking the maximum (checked_at, rank) is commutative, an unsorted linear scan could achieve O(m) time and O(1) extra space, though chronological sorting makes audit logs easier to trace.)

Edge cases

  • Duplicate callback deliveries: Applying the identical EligibilityLookup twice fails the strict > checks on both checked_at and STATUS_RANK, leaving cached_status, last_verified_at, and version untouched.
  • Tied checked_at timestamps: ACTIVE outranks INACTIVE and both outrank PENDING, regardless of arrival order.
  • ERROR arriving before an older valid lookup: Leaving last_verified_at = None on an initial ERROR ensures a valid check from earlier (09:45 arriving after a 09:50 timeout) still updates the policy.
  • Back-to-back ERROR events: The first ERROR on an unverified row transitions PENDING -> ERROR (version + 1); any subsequent ERROR sees cached_status == ERROR and leaves version unchanged.
  • Empty history (lookups = []): reconcile_from_history resets a corrupted cache back to (PENDING, None) in one version bump, or leaves an already (PENDING, None) row as-is.
  • Legacy ACTIVE/INACTIVE rows with last_verified_at = None: CONCLUSIVE_STATUSES shields them from ERROR events while allowing the next real check to stamp last_verified_at.
  • Mismatched user_insurance_id: Raises ValueError immediately so one member's lookup can never corrupt another member's policy.

Common mistakes

  • Ordering by arrival wall-clock time (datetime.now()) instead of lookup.checked_at: Queue backlogs and webhook retries routinely invert delivery order relative to when the payer evaluated coverage.
  • Advancing last_verified_at on Status.ERROR: Stamping last_verified_at on 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 same checked_at makes outcomes depend on arrival order and bumps version on duplicate retries.
  • Folding reconcile_from_history on top of existing user_insurance fields: If a bug wrote a future timestamp like 16:00 onto user_insurance, starting from that row rejects every historical check. Always fold from (Status.PENDING, None).
  • Incrementing version inside the history loop: Repairing a row from 40 historical lookups is a single state repair on UserInsurance, so version must increase by 1 or 0, never by up to 40.
  • Mutating user_insurance in place: Overwriting user_insurance.version directly erases the expected version number needed for an optimistic WHERE version = :old_version database write.

Alternative approaches

  • Single conditional SQL UPDATE: Encode the timestamp, rank tie-breaker, and ERROR predicates directly inside a SQL WHERE clause so PostgreSQL checks and updates the row atomically in a single round-trip without application-side retry loops.
  • Asynchronous stream projection: Treat EligibilityLookup as an event stream (an ordered sequence of immutable domain facts) and materialize UserInsurance via 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 UserInsurance record 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 plain SELECT queries read the latest committed snapshot—so roster reads never wait on UPDATE locks as long as readers avoid SELECT ... 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_version and re-read on 0 affected rows) or push the transition check directly into an atomic conditional UPDATE. Under PostgreSQL's default READ COMMITTED isolation, a concurrent second UPDATE waits briefly for the first commit and re-evaluates its WHERE predicate 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 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? Whenever cached_status equals ACTIVE, last_verified_at already stores the exact timestamp of that latest ACTIVE check (any newer INACTIVE or PENDING check would have replaced cached_status, and ERROR never touches last_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—in O(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 EligibilityLookup log and cached UserInsurance rows? Emit structured counters from record_lookup labeled by decision (updated, skipped_older, skipped_tie, skipped_error, duplicate_noop), monitor optimistic-lock retry rates, and track callback lag (now - checked_at at p50 and p99 per payer) to spot stalled queues or upstream ERROR spikes early. To catch cache drift (any discrepancy between UserInsurance and its lookup log), run an incremental audit every 15 minutes over user_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 from reconcile_from_history, and auto-heal drifted rows via version-checked updates.

Follow-up questions

Similar questions

More Headway interview questions

All 11 Headway questions →