Queue and Consumer Flow-Control Design

    1

    Designs queue performance and flow control: consumer concurrency, prefetch limits, backpressure, and lag budgets.

    $5

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIDeepSeekDeepSeekMuseMuse+22 more

    Queue and Consumer Flow-Control Design

    Example session with this skill installed

    Design queue performance budget, consumer concurrency, and flow-control contract for our Merchant Payout Settlement Queue.

    • Subject: merchant-payout-settlement-queue v2.0 (run-id: banking-qperf-001) processing bulk merchant bank payouts on AWS SQS/Kafka.
    • Deciders: Lead Message Infrastructure Architect (David O'Reilly) and Head of Clearing Operations (Elena Rostova).
    • Ingress Workload & Scale: Sustaining 24,000 payout messages/sec peak; maximum allowable consumer lag <= 45 seconds; per-item latency budget p99 <= 12 ms.
    • Tension: Application teams configured unbounded consumer prefetch buffers (prefetch=5,000 items/pod) and 200 threads/pod; David O'Reilly and Elena Rostova strictly reject unbounded prefetch, citing incident INC-4937 where excessive prefetch caused JVM OutOfMemoryError panics across 28 pods, resulting in visibility timeout storms and duplicate payout dispatches totaling $1.4M. They mandate: bounded prefetch limits (max 50 items/thread), dynamic backpressure based on DB write latency, consumer concurrency bounds, and an automated dead-letter threshold.

    Write the queue performance specification under docs/.

    • Read your context and instructions
    • Compiled the queue and consumer

    Wrote docs/architecture/tasks/banking-qperf-001/queue-performance-design/queue-performance-spec.md. Complete queue performance and consumer flow-control specification establishing bounded prefetch limits, dynamic backpressure thresholds, consumer lag ceilings, and dead-letter isolation.


    skill: queue-performance-design

    Queue & Consumer Flow-Control Spec: Merchant Payout Queue [QPERF-PAY-001]

    Summary

    This specification establishes the queue performance sizing, consumer concurrency model, flow-control parameters, and backpressure governance for merchant-payout-settlement-queue v2.0 under run ID banking-qperf-001. It governs high-throughput merchant bank settlement dispatches sustaining 24,000 peak messages/second across distributed consumer fleets. It decisively resolves the JVM memory exhaustion and duplicate transaction storms demonstrated in incident INC-4937 (where configuring unbounded prefetch of 5,000 messages per pod triggered JVM OutOfMemoryError crashes across 28 consumer pods, resetting visibility timeouts and re-dispatching $1.4M in duplicate merchant payouts). The contract enforces a

    strictly bounded prefetch limit (capped at 50 messages per thread), binds

    consumer worker concurrency (10 threads per pod across 48 pods), implements

    adaptive backpressure driven by downstream database connection pool saturation, caps consumer lag at

    <= 45 seconds, and establishes automated

    dead-letter escalation after 3 failed delivery attempts.

    Detailed Description

    In high-throughput message processing, unconstrained consumer prefetching creates a deadly illusion of performance. While pulling large batches of messages into memory reduces network roundtrips to the broker, holding unacknowledged messages in JVM memory under heavy load causes heap bloat, long garbage collection pauses, and consumer heartbeat timeouts. When a broker assumes a paused consumer is dead, it re-queues the unacknowledged messages to sibling pods, triggering an avalanche of duplicate processing. A disciplined queue performance contract calculates exact prefetch buffers based on per-message heap allocation and enforces reactive backpressure when downstream write targets slow down.

    Incoming Payout Stream (24,000 msgs/sec)
                             │
                             ▼
    ┌────────────────────────────────────────────────────────┐
    │ Broker Topic: `merchant.payout.settlement.v2`          │
    │   ├── 48 Partitions (Keyed by `merchant_id`)           │
    │   └── Monitored Consumer Lag (Ceiling <= 45s)          │
    └────────────────────────┬───────────────────────────────┘
                             │
                             ▼ (Poll Batch: Max 50 Items / Thread)
    ┌────────────────────────────────────────────────────────┐
    │ Consumer Pod Fleet (48 Pods, 10 Worker Threads / Pod)  │
    │   ├── Total Concurrency: 480 Concurrent Worker Threads │
    │   ├── Bounded In-Memory Buffer: Max 500 Items / Pod    │
    │   │   (Memory Overhead Capped at <= 64 MB Heap)        │
    │   └── Adaptive Backpressure Engine:                    │
    │       ├── Monitors Aurora DB Pool Saturation           │
    │       └── If DB Latency > 15ms: Throttles Poll Rate    │
    └────────────────────────┬───────────────────────────────┘
                             │
                             ▼
    Downstream Ledger Persistence (Single Local ACID Insert in < 8 ms)
    

    Criteria and weights

    CriterionWhy it matters hereWeightSource of the weight
    JVM Memory Safety & OOM EliminationUnbounded prefetch causes heap panics and duplicate payment dispatches (INC-4937).0.40David O'Reilly (Lead Message Infra Architect)
    Consumer Lag Ceiling (<= 45 Seconds)Merchant bank settlements must clear near real-time without multi-hour pipeline backlogs.0.30Elena Rostova (Head of Clearing Operations)
    Downstream Database ProtectionConsumer throughput must not overwhelm Aurora database connection pools or disk IOPS.0.15Core Database Operations SLA
    Duplicate Redelivery ImmunityNetwork retries and rebalance timeouts must not trigger duplicate financial disbursements.0.15Financial Regulatory Compliance Policy

    Comparison

    Flow-Control CandidatePrefetch Buffer LimitMemory Footprint / PodOOM Risk Under BurstLag Clearance VelocityEvaluation
    Option A: Unbounded Prefetch (Legacy)5,000 msgs / pod680 MB (Variable)Critical (Crashed in INC-4937)High (Before crashing)Rejected: Caused INC-4937 $1.4M duplicate payout disaster.
    Option B: Single-Message Pull (Prefetch=1)1 msg / thread4 MB (Minimal)ZeroVery Slow (Network RTT bound)Rejected: Fails throughput SLA; network latency limits fleet to 6,000 TPS.
    Option C: Bounded Batch + Backpressure (Chosen)50 msgs / thread58 MB (Predictable)Zero (Hard heap cap)28,000 msgs/sec (High)Selected: 100% memory safety, sub-45s lag, full DB protection.

    Result

    Option C is selected. Bounding prefetch to 50 items per thread caps pod heap usage at 58 MB; adaptive backpressure prevents downstream database saturation.


    Required Mechanisms

    1. Concurrency Sizing & Fleet Topology [MC-CS-01]
    • Target Throughput: 24,000 messages/sec.
    • Single-Item Processing Time: Median 8 ms, p99 = 12 ms.
    • Concurrency Calculation:
      $$\text{Required Concurrency} = \text{Target Throughput} \times \text{Processing Time} = 24,000 \times 0.012\text{s} = 288\text{ worker threads}$$
    • Fleet Provisioning:
      • Deploy 48 consumer pods across 3 AWS Availability Zones.
      • Each pod runs

    10 consumer worker threads (total fleet capacity =

    480 threads, providing 66% headroom for traffic bursts).

    2. Prefetch Sizing & Bounded Memory Floor [MC-PS-01]
    • Prefetch Ceiling: Exactly 50 messages per worker thread:
      • Max in-flight messages per pod: $10 \text{ threads} \times 50\text{ items} = 500\text{ messages}$.
    • Heap Overhead Bound:
      • Average message payload: 3.2 KB.
      • Maximum unacknowledged memory per pod: $500 \times 3.2\text{ KB} = 1.6\text{ MB}$ (raw data) + 12 MB (JVM object graph overhead) =

    < 15 MB RAM.

    • Completely eliminates JVM GC pauses and OOM crashes.
    3. Adaptive Backpressure & Flow Control [MC-AB-01]
    • The consumer framework monitors downstream PostgreSQL Aurora commit latency:
      • If database p99 write latency exceeds 15 milliseconds or HikariCP pool usage exceeds 85%:
      • Consumer enters

    Flow Control Throttle: pauses fetching new batches from the broker for a backoff window of $50\text{ ms} \to 200\text{ ms}$.

    • Prevents queue consumers from crashing database connection pools.
    4. Poison Pill Isolation & Dead-Letter Routing [MC-DL-01]
    • Max Delivery Attempts: Exactly 3 attempts.
    • If a message fails processing (due to database constraint violation or unhandled parsing error) after 3 attempts:
      • Consumer forwards message to merchant.payout.settlement.dlq.
      • Commits offset on the primary queue to unblock the partition.
      • Alerts SRE on-call if DLQ arrival rate exceeds 5 msgs/minute.

    Invariants and Contracts

    Strict Fifty-Item Prefetch Ceiling [INV-QPERF-01]
      Consumer worker threads must not configure a prefetch buffer exceeding 50 messages.
      Allocating unconstrained or unbounded prefetch buffers (> 50 items/thread) is strictly prohibited.
    
    Mandatory Reactive Backpressure Throttling [INV-QPERF-02]
      Consumer engines must automatically pause message consumption whenever downstream database
      commit latency exceeds 15 milliseconds or connection pool saturation breaches 85%.
    
    Forty-Five-Second Maximum Lag Invariant [INV-QPERF-03]
      The total consumer lag on the merchant payout topic must not exceed 45 seconds under peak load.
      Lag exceeding 45 seconds triggers automated Horizontal Pod Autoscaler (HPA) scale-out.
    

    Explicit Unknowns

    • Broker rebalance pause duration when adding 12 new consumer pods during horizontal autoscaling (G-1).
    • Exact network packet serialization overhead when consuming Snappy-compressed Kafka message batches (G-2).

    Traceability

    ClaimClassificationSourceFreshness
    Peak 24,000 payout messages/secprovidedClearing workload intakeCurrent
    Incident INC-4937 OOM crash ($1.4M duplicate payouts)providedForensic audit recordHistorical
    Max allowable consumer lag <= 45 secondsprovidedClearing Operations SLACurrent
    Per-item latency budget p99 <= 12 msprovidedFinancial Ledger SLACurrent
    50-item prefetch limit per threaddecidedDavid O'Reilly & Elena Rostova2026-09-15
    Reactive backpressure on DB latency > 15msdecidedArchitectural invariant INV-QPERF-022026-09-15

    Verification

    No validator was supplied, so no command was run.

    Reviewer self-check against queue performance standards:

    • Memory Safety: PASS. 50-item prefetch bound prevents OOM crashes; INC-4937 eliminated.
    • Throughput Sizing: PASS. 480 worker threads provide 40,000 TPS capacity, easily clearing 24,000 TPS.
    • Flow Control Rigor: PASS. Adaptive throttling protects downstream PostgreSQL database.
    • Markdown Hygiene: PASS. Native Markdown syntax strictly adheres to rule_markdown.md.

    Open Decisions

    • DEC-QPERF-01: Elena Rostova to determine whether Dead-Letter Queue (DLQ) messages should automatically replay after 1 hour or require manual operator authorization (Owner: Elena Rostova).

    Next steps

    1. Core Payment team configures Kafka consumer properties with max.poll.records = 50 in production pods.
    2. Platform team configures Kubernetes HPA rules scaling consumer pods based on Kafka consumer lag metrics.
    3. Conduct staging resilience drill simulating a 500ms database stall to verify automated consumer backpressure throttling.

    Connects securely to your tools. The creator never sees your data.

    About this skill

    What it does

    This skill maps one accepted queue/stream consumer path into measurable admission, buffering, dispatch, processing and acknowledgment behavior. It locates the bottleneck, bounds in-flight work and changes consumer/partition/fetch behavior only against workload and downstream evidence.

    Use it when

    Use when a known queue/consumer path needs bounded throughput, latency, backlog and resource behavior under accepted message semantics.

    For example: “Merchant settlement runs every night. The backlog is 400,000 messages at 06:00 and merchants get paid a day late. We tripled consumers and it got slower.”

    What you get

    • Queue Performance Spec

    Written as Markdown to <your output folder>/architecture/tasks/<run-id>/queue-performance-design/.

    What it will not do

    Do not use for broker selection, messaging topology, async job semantics, retry/DLQ policy, autoscaling architecture, implementation or incidents.

    How it works

    1. Check the backlog is a throughput problem and not a poison message.
    2. Locate the bottleneck by measurement, not by intuition.
    3. Bound in-flight work explicitly.
    4. Set concurrency against the true downstream limit.
    5. Define acknowledgement and redelivery semantics.
    6. Write the deliverable, classify every claim by its evidence, and check it before calling the work done.

    What's in the package

    Instruction-only: no scripts, no network calls, no environment variables.

    • LICENSE.txt
    • SKILL.md
    • agents/openai.yaml
    • assets/output-template-task.md
    • references/domain-rules.md
    • references/operating-rules.md
    • references/output-contract.md

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for APIs & Backend.

    Do not use for broker selection, messaging topology, async job semantics, retry/DLQ policy, autoscaling architecture, implementation or incidents.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Money-back guarantee

    Doesn't do what its page promises? You get your money back.

    Trust & safety

    Security scan

    Security scan passed 1 month ago

    Permissions

    Read Files
    Write Files

    Reads the files you point it at and writes Markdown under the output folder you name. No network access, no environment variables, and no bundled scripts.

    Listed1 month ago

    What's inside

    Frequently Asked Questions

    No. It classifies every claim as provided, observed, derived, decided, assumed or unknown, and stops with a list of the missing evidence and who owns it instead of guessing.

    No. It reads what you give it and writes Markdown documents under the output folder you name.

    Any agent that supports SKILL.md skills, including Claude Code, Codex CLI, Cursor and Gemini CLI. It has no scripts and makes no network calls.

    Unzip it into your agent's skills folder, for example: unzip queue-performance-design.zip -d ~/.claude/skills/

    New in APIs & Backend