[aryan@dev]
← cd ~/work
Idekavan GroupTechnical Manager & Backend Engineer2025 - 2026

How Monotonic State Guards + ORDER BY updated_at Starved 84,000 Messages

A production failure analysis in Go, Kafka, and ClickHouse ReplacingMergeTree: why write-gated timestamps break round-robin polling, and how an upstream TTL purge turned monotonic state weights into a permanent corruption ratchet.

Drained 84k starved backlog in ~70 min
Zero extra DB writes or schema changes
Stopped 2-week false-failure corruption ratchet
GoKafkaClickHouseReplacingMergeTree

Individually, every piece of our Go, Kafka, and ClickHouse messaging pipeline looked solid:

  • Outbound SMS events and delivery receipts stored in ClickHouse ReplacingMergeTree(updated_at).
  • A monotonic status state machine so out-of-order webhooks could never regress Delivered back to Sent.
  • A periodic status poller querying pending messages ordered by updated_at ASC LIMIT 200 so recently checked rows would rotate to the back of the queue.
  • A 48-hour look-back window to reconcile messages whose delivery webhooks never arrived.

In production, the interaction between these invariants caused two incidents: first, silent starvation of ~84,000 pending messages (processed=200 updated=0 every tick); second, a two-week climb in false Failed statuses that the monotonic guard permanently locked in.

1. Out-of-order webhooks vs. ReplacingMergeTree(updated_at)

Upstream telecom providers routinely delivered status webhooks before our Kafka consumer flushed the original MessageSent row into ClickHouse.

Two naive fixes fail in opposite directions: blocking retries on the Kafka consumer stall the entire partition while waiting for a missing parent row, while blindly inserting webhook updates either overwrites a terminal Delivered state when a delayed Sent event arrives or (if the writer forgets to advance updated_at) gets silently discarded by ReplacingMergeTree(updated_at) during background merges.

The monotonic weight ladder

We moved webhook reconciliation onto non-blocking exponential backoff (1s to 1h cap, 24h cutoff) and introduced an explicit monotonic weight ladder:

Delivered (100) > Failed (90) > Undelivered (80) > ... > Sent (10)

A status transition is written to ClickHouse only if newWeight > currentWeight, and every accepted write sets UpdatedAt = time.Now() so ReplacingMergeTree deterministically keeps the higher-weight row.

2. The ORDER BY updated_at ASC starvation trap

Not all providers reliably push webhooks, so a periodic poller scans pending messages in batches of 200 and queries the provider’s status API.

Initially, the poller queried ORDER BY created_at ASC LIMIT 200. When 7,517 old messages got stuck in a non-terminal state, they sat permanently at the front of the query and starved 113,964 newer messages behind them.

We changed the query to:

SELECT ...
FROM sms_logs FINAL
WHERE status NOT IN (...)
  AND created_at >= now() - INTERVAL 48 HOUR
ORDER BY updated_at ASC
LIMIT 200

The idea was that once we polled a row, its updated_at would move to now() and rotate it to the back of the queue.

Why it failed in production

Within hours, metrics showed the poller running every tick with:

processed=200 updated=0

Roughly 84,000 messages were starved again.

The bug came from the monotonic guard: we only write a new row (and bump updated_at) when a message’s status changes. When the poller checked those 200 stuck messages and the provider still returned the same non-terminal status, the monotonic guard skipped the write. Their updated_at stayed frozen in the past, pinning the same 200 rows to the head of ORDER BY updated_at ASC on every tick.

Writing a no-op row just to bump updated_at would have turned ClickHouse into a write-amplified queue, generating tens of thousands of redundant ReplacingMergeTree parts per hour.

Fix: an immutable keyset-pagination cursor on (created_at, trace_id)

Instead of mutating rows to track polling progress, we decoupled queue traversal from row writes using a per-provider in-memory keyset cursor over two immutable columns: created_at (the ClickHouse primary-key prefix, which never mutates) and trace_id (a deterministic tiebreaker for same-second bursts, where we observed up to ~491 msg/s sharing the same created_at second).

SELECT ...
FROM sms_logs FINAL
WHERE provider = ?
  AND status NOT IN (...)
  AND created_at >= now() - INTERVAL 44 HOUR
  AND (created_at, trace_id) > (?, ?)
ORDER BY created_at ASC, trace_id ASC
LIMIT 200

On each tick, the poller advances the provider’s cursor to the last (created_at, trace_id) returned; when a page comes back short, the cursor wraps back to the start of the window.

This required zero extra ClickHouse writes and zero schema migrations. Every pending row is visited once per sweep regardless of whether its status changes. After deploying, the 84,000-message backlog drained in ~70 minutes.

3. Upstream TTL purge + monotonicity = permanent corruption ratchet

Once the poller could traverse the full look-back window, recorded Failed rates climbed steadily for two weeks on one provider even though real delivery rates had not changed.

Root cause

Three details combined into a data-corruption loop:

  1. Our poller looked back 48 hours, while Provider B purged message IDs from its status API at roughly 48 hours. A message queried at 47 hours returned its real delivery state; queried at 50 hours (or after slight clock/retention drift), the API returned -1 (NotExist).
  2. Our response mapper translated -1 (NotExist) into Failed (weight 90).
  3. That provider’s delivery code was mapped to Received (weight 40) instead of Delivered (weight 100).
t = 0h   : Message sent            → Sent (weight 10)
t = 1m   : Delivered by carrier    → Received (weight 40)   [still polled as non-terminal!]
t = 48h+ : Provider purges ID      → API returns -1 (NotExist)
         → Mapper synthesizes      → Failed (weight 90) > 40 → OVERWRITES delivery!
t = 49h  : Any late confirmation   → weight 40 < 90         → REJECTED by monotonic guard

Because Received (40) was non-terminal, already-delivered messages kept getting polled until they crossed the provider’s 48h retention cliff. At that point, -1 synthesized Failed (90), which beat Received (40) and permanently latched into ClickHouse. The monotonic state guard had become a one-way corruption ratchet.

Fix

  • Reduced the poller look-back window from 48h to 44h so we stay inside upstream retention and never query IDs near the provider’s purge horizon.
  • Dropped -1 and unknown provider codes as no-ops so we never synthesize high-weight terminal states from absence.
  • Mapped the provider’s delivery confirmation directly to weight-100 Delivered, and extracted a single shared terminalStatusTexts constant across the repository and poller (keeping Undelivered non-terminal so temporary carrier delays still reconcile).

Takeaways

  • Do not use a write-gated timestamp (updated_at) as a round-robin queue cursor when your writer is idempotent or monotonic. Use an immutable keyset cursor (pk_prefix, tiebreaker) instead.
  • Monotonic state guards only prevent regressions if high-weight states are never synthesized from ambiguous signals. Mapping NotExist or TTL expiry to a high-weight Failed state turns monotonicity into a one-way corruption ratchet.
  • Keep poller look-back windows strictly shorter than upstream ID retention, with margin for clock skew and batching lag.
Discussion

Comments

Loading…

Leave a note

Comments are moderated before appearing publicly.