KatInterview

Reconcile Cached Coverage Status with Out-of-Order Checks

Data Structure DesignModel answer
MediumModel answerData Structure Designidempotencyout-of-order eventscache consistency

Last 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

  1. Time never goes backwards. If lookup.checked_at is strictly earlier than last_verified_at, the lookup must not change cached_status.
  2. Errors are not answers. A lookup with status ERROR (a communication failure with the third party) must never replace an existing ACTIVE or INACTIVE state. If the record has never been verified (last_verified_at is None), an ERROR lookup does set cached_status to ERROR.
  3. Deterministic ties. When two lookups share the same checked_at, ACTIVE beats INACTIVE, and both beat PENDING.
  4. Versioning. Each real change to the record increases version by exactly 1. If the lookup leaves the cached values unchanged, version stays 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).