Escalation Counters and Level Changes in a Review Pipeline
Data Structure DesignModel answerLast updated
Design a cached repeat-alert counter that triggers rejection of a work order, then extend it so an alert's severity can change without corrupting counts or past decisions.
You are building part of a work-order approval pipeline. During review, the system may raise alerts against a work order (for example, a missing certification or a budget mismatch). Product wants two behaviors:
- A cache tracks how often alerts repeat, and a work order is rejected automatically once a repeat-count rule is satisfied.
- An existing alert's level (severity) can later be changed.
The brief deliberately leaves several rules open: the cache key, the count threshold, any time window, what the levels mean, and whether a level change applies retroactively. You are expected to surface these ambiguities, pick sensible defaults, and state them clearly before designing.
Part 1: Count alerts and apply the rejection rule
Describe:
- What you store and what the cache key is. What exactly counts as one qualifying occurrence?
- How the threshold and any expiry or window are configured.
- The operation that records an alert and returns a reject or continue decision.
- How you handle duplicate event delivery, concurrent updates, and the relationship between the cache and the authoritative store.
Part 2: Update an alert's level
Describe:
- Whether a level belongs to an alert instance, an alert category, or the approval policy.
- Whether a level change rewrites history or only affects future decisions.
- How you keep cached counts correct afterward (invalidation, versioning, recomputation) and how earlier decisions remain auditable.
You do not need to write full production code, but concrete data shapes, pseudocode, or API signatures are welcome.
Hints
Hint 1
Start by listing the open questions (key, threshold, window, level semantics, retroactivity) and choose explicit defaults. Interviewers value stated assumptions more than a particular number.
Hint 2
Treat the durable alert log as the source of truth and the cache as a derived, rebuildable counter. Give every alert event a unique ID so retries do not double count, and make the count-and-decide step atomic.
Hint 3
For level changes, record them as new events or versions rather than editing rows in place. If the level affects counting, key or version the counter by the policy or level so stale entries cannot be read, and store the inputs of each decision for audit.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the open rules first
The brief does not fix several things, so I would state defaults and make each one configurable:
- Counted entity: alerts per work order, grouped by alert type. Key:
(work_order_id, alert_type). - Qualifying occurrence: a distinct alert event, identified by a unique
alert_idorevent_id, with level at or above a configured minimum. A retried delivery of the same event is not a new occurrence. - Threshold and window: reject when the count reaches
Nwithin a rolling windowW, for exampleN = 3andW = 24h. Both live in configuration, not code. - Level semantics: level is a property of the alert instance (severity at the time it was raised), while the policy decides how each level contributes.
- Retroactivity: I would default to non-retroactive for decisions already made, but allow counts for pending work orders to reflect the new level.
Part 1: Recording alerts and deciding
Authoritative store (relational table or append-only log):
alerts(alert_id PK, work_order_id, alert_type, level, created_at, status)
decisions(decision_id, work_order_id, outcome, rule_version, inputs_json, decided_at)
Cache (for example Redis): key cnt:{work_order_id}:{alert_type} holding either a counter with TTL W, or a sorted set of alert_id scored by timestamp. The sorted set is better for a rolling window because old entries can be trimmed by score, and adding the same alert_id twice is naturally idempotent.
Operation record_alert(event):
- Insert into
alertswith a unique constraint onalert_id. If it already exists, return the previously computed decision (idempotent retry). - Atomically (a Lua script, or a transaction) run: add
alert_idto the sorted set, trim entries older thannow - W, and return the cardinality. - If
count >= Nand the work order is not already terminal, write aREJECTEDdecision with the rule version and the counted alert IDs, using a conditional update (WHERE status = 'PENDING') so only one writer wins. - Return
REJECTorCONTINUE.
Concurrency: the atomic add-and-count removes the read-modify-write race. The conditional status transition removes the double-reject race. Without these, two simultaneous alerts could both read N-1 and neither reject, or both reject and emit duplicate notifications.
Cache versus truth: if the cache is lost or evicted, rebuild it from alerts with a bounded query (WHERE work_order_id = ? AND alert_type = ? AND created_at > now - W). On a cache miss, rebuild before deciding, never treat a miss as zero. Write order matters: persist to the store first, then update the cache, so a crash leaves the cache under-counting (repairable) rather than over-counting with no record.
Part 2: Updating an alert's level
Model the change as an event, not an overwrite. Add an alert_level_changes(alert_id, old_level, new_level, changed_by, changed_at) table, and keep the current level on the alert row for fast reads. This preserves history and supports audit.
Effect on counts: it depends on whether level participates in the rule.
- If only alerts at or above a minimum level count, a change can move an alert in or out of the qualifying set. Recompute that one counter: add or remove the
alert_idfrom the sorted set, then re-evaluate the rule. - If the count is per-level (for example, 2 critical alerts), key by level or store the level with the member, so the change is a targeted move rather than a full flush.
- If the level change is a policy-wide change (thresholds per level change), version the configuration:
rule_versionbecomes part of the cache key or is checked on read, so entries from an older version are ignored and lazily rebuilt.
Retroactivity:
- Past decisions are never rewritten. Each decision stores
rule_version, the alert IDs and levels used, and the count, so it can be explained later. - For pending work orders, re-evaluation after a level change may produce a new rejection. That is a new decision record referencing the triggering level change.
- If a downgrade would have avoided an earlier rejection, do not silently reverse it. Surface it through an explicit reopen or appeal path with its own audit entry.
Ordering and concurrency: a level update racing with a new alert should serialize per work order, for example by partitioning events by work_order_id in a queue or taking a short row lock. Alternatively use optimistic versioning (alert.version) and retry on conflict. Reject stale updates whose version does not match.
Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Sorted set with IDs vs plain counter | Idempotent, exact rolling window, easy removal on level change | More memory per key |
| Per-work-order partitioned processing | Simple ordering guarantees | Hot work orders limit throughput |
| Versioned cache keys | Cheap invalidation | Old keys linger until TTL |
| Non-retroactive decisions | Auditable, predictable | Needs a manual path to correct mistakes |
Sizing: if there are 1M active work orders with up to about 10 alerts each at roughly 100 bytes per member, the cache is on the order of 1 GB, which is manageable. TTL equal to W keeps it bounded.
Common mistakes
- Inventing a threshold or severity taxonomy as if it were given, instead of asking or labeling it an assumption.
- Counting retries as new alerts because there is no event ID.
- Treating a cache miss as a count of zero, which lets bad work orders through after eviction.
- Non-atomic read-then-write on the counter.
- Updating a level in place with no history, making past rejections unexplainable.
- Rewriting prior decisions when a level changes.
- Updating the cache before the durable write, so a crash leaves unrecoverable phantom counts.
Tests worth mentioning
Duplicate delivery of the same alert_id; two concurrent alerts at N-1; expiry exactly at the window boundary; cache flush mid-stream followed by rebuild; level upgrade pushing a work order over the threshold; level downgrade after a rejection; and a rule-version change while counters are live.