Skip to main content
← PROBLEMS / ARCHITECTURE
An end-to-end domain learning journey

Calibrating SQS Visibility
Timeouts & Heartbeats.

When an SQS Standard queue's VisibilityTimeout (30s) is shorter than p99 job duration (110s), SQS re-exposes in-flight messages to a second worker while the first worker is still running, causing 14% duplicate processing and wasted compute.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When an SQS Standard queue's `VisibilityTimeout` (30s) is shorter than p99 job duration (110s), SQS re-exposes in-f, because SQS guarantees at-least-once delivery, pair a calibrated visibility heartbeat (`ChangeMessageVisibility` every `T/2`) with a strict idempotent consumer store so neither long jobs nor worker crashes cause duplicate side effects.

TL;DR30-second simplified summary
▾

Core Mechanics: An invoice-OCR and billing-settlement fleet processes 400 jobs/sec from SQS Standard (VisibilityTimeout = 30 s). While average jobs take 8–12 s, multi-page PDFs take 48 s at p95 and 110 s at p99 (up to 900 s max).

Visual & Structural Flow: Depicts 110s p99 Job vs. 30s Default VisibilityTimeout (SQS Standard -> Worker 1 (Spot) -> Worker 2 (Spot) -> Payment Gateway); Worker Lease Heartbeat & Settlement State Machine (PROCESSING -> SETTLED -> CRASH / MAX 900s).

Trade-Offs & Production: Calling ChangeMessageVisibility on the same thread as blocking OCR/HTTP I/O never fires when the job stalls. Combine fast crash detection, bounded heartbeats, and strict consumer idempotency: 45 s Initial Visibility + 20 s Async Heartbeat: Set VisibilityTimeout = 45 s (crashed Spot workers recover in <= 45 s).

Failure Modes & Application: Lease-extension + idempotency is the universal pattern for variable-duration async workers: Document OCR, Video Transcoding & LLM Batch Jobs: Keeps crash recovery at 45s even for 15-minute jobs.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why SQS VisibilityTimeout=30s causes 14% duplicate billing.

Why this matters: The mechanism: understand how Why SQS VisibilityTimeout=30s causes 14% duplicate billing works from first principles.

An invoice-OCR and billing-settlement fleet processes 400 jobs/sec from SQS Standard (VisibilityTimeout = 30 s).

While average jobs take 8–12 s, multi-page PDFs take 48 s at p95 and 110 s at p99 (up to 900 s max).

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Irreversible double charges and 15-minute crash-recovery stalls.

Why this matters: The problem: see what breaks without Irreversible double charges and 15-minute crash-recovery stalls under real concurrency or scale.

Misconfigured SQS visibility timeouts create a painful trade-off:

  1. Too Short (30 s): Healthy 48–110 s jobs get picked up by Worker 2 while Worker 1 is still charging the payment gateway.
  2. Too Long (900 s): If a Spot worker gets SIGTERM at t = 2 s, the invoice sits invisible for 15 minutes.
Premature Visibility Expiry

110s p99 Job vs. 30s Default VisibilityTimeout

SQS StandardWorker 1 (Spot)Worker 2 (Spot)Payment Gateway1. ReceiveMessage (VT=30s)2. Multi-page OCR takes 110s3. t=30s VT expires -> delivers toW2!4. W1 charges invoice -> $5005. W2 charges AGAIN! (Fix:Heartbeat+Idem)

A 45s initial VT + 20s heartbeat detects crashes fast, while an idempotent consumer ledger blocks duplicate charges.

Engineering Decision Framework
Problem
How to implement Calibrating SQS Visibility Timeouts & Heartbeats without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When an SQS Standard queue's VisibilityTimeout (30s) is shorter than p99 job duration (110s), SQS re-exposes in-f, because SQS guarantees at-least-once delivery, pair a calibrated visibility heartbeat (ChangeMessageVisibility every T/2) with a strict idempotent consumer store so neither long jobs nor worker crashes cause duplicate side effects.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Calibrating SQS Visibility Timeouts & Heartbeats experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Why heartbeats alone do not guarantee exactly-once billing.

Why this matters: The problem: see what breaks without Why heartbeats alone do not guarantee exactly-once billing under real concurrency or scale.

Think of Why heartbeats alone do not guarantee exactly-once billing as the intuition layer for Calibrating SQS Visibility Timeouts & Heartbeats: The problem: see what breaks without Why heartbeats alone do not guarantee exactly-once billing under real concurrency or scale.

Calling ChangeMessageVisibility on the same thread as blocking OCR/HTTP I/O never fires when the job stalls. Even with a background heartbeat thread, SQS Standard guarantees at-least-once delivery—network partitions or Spot SIGKILL after charging the PSP (before DeleteMessage) will still redeliver the message.

Lifecycle & Failure Recovery

Why heartbeats alone do not guarantee exactly-once billing

poll batchsink successpoison / timeoutAppended to LogLeased to ConsumerOffset CommittedMoved to DLQ
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: T/2 Async Heartbeat + Idempotent Settlement Ledger.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Combine fast crash detection, bounded heartbeats, and strict consumer idempotency:

  • 45 s Initial Visibility + 20 s Async Heartbeat: Set VisibilityTimeout = 45 s (crashed Spot workers recover in <= 45 s). A separate background timer calls ChangeMessageVisibility(+45s) every 20 s (T/2) up to MAX_JOB_DURATION = 900 s, always cancelled in finally.
  • Idempotent Consumer Ledger + PSP Key: Before calling the payment gateway, acquire a conditional DB row INSERT INTO settled_invoices (invoice_id, status) ON CONFLICT DO NOTHING (or IN_PROGRESS lease) and pass invoice_id as the PSP Idempotency-Key.
Heartbeat & Idempotency Guard

Worker Lease Heartbeat & Settlement State Machine

PSP key + DB commitSpot SIGTERM / timeoutPROCESSINGHeartbeat +45s every 20sSETTLEDLedger PK + DeleteMessagCRASH / MAX 900sVT expires in <=45s

Background heartbeats extend healthy jobs up to 900s while DB + PSP idempotency keys eliminate duplicate charges.

05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where visibility leases and idempotent consumers apply.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Lease-extension + idempotency is the universal pattern for variable-duration async workers:

  • Document OCR, Video Transcoding & LLM Batch Jobs: Keeps crash recovery at 45s even for 15-minute jobs.
  • Billing & Payout Workers: Pairs queue leases with DB unique constraints and PSP idempotency keys.
  • Spot / Preemptible Compute Fleets: Handles SIGTERM gracefully by cancelling heartbeats and letting VT expire cleanly.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is an idempotent consumer ledger still required even when a background heartbeat calls `ChangeMessageVisibility` every 20 seconds?

Recommended Learning Flow