[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74GHNYTKBXRBKXGR9PZ0ZR5":3,"skill-same:01M74GHNYTKBXRBKXGR9PZ0ZR5":44},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M74GHNYTKBXRBKXGR9PZ0ZR5","async-workload-design",null,"Design async and background processing — queue vs stream, worker sizing, idempotency, retries and DLQ, backpressure, priority lanes.","MohammadBafkar\u002Fpolymath","MohammadBafkar","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F34940462?v=4","01M74G540TQFZWK6KVAPKFVGNR","Mohammad Bafkar","01M74G541HG19QP9V5DQCJVKYE",0,"MIT","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-scalability\u002Fskills\u002Fasync-workload-design\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: async-workload-design\ndescription: Design async and background processing — queue vs stream, worker sizing, idempotency, retries and DLQ, backpressure, priority lanes.\n---\n\n# async-workload-design\n\n> Anything the user doesn't wait for should leave the request path — but a queue only moves the failure. Design bounded depth, idempotent workers, and what happens when work arrives faster than it drains.\n\n**Mode:** analytical — judgment inside a fixed frame. Keep the output shape; every verdict cites its evidence; unknowns are marked `[TBD]` or `[VERIFY]`, never filled in.\n\n## When to use\n\n- Offloading slow or bursty work (emails, exports, media processing, webhooks, ML jobs, third-party calls) from the request path.\n- Workers fall behind, queues grow without bound, jobs run twice, or one noisy tenant starves others.\n- Choosing between a task queue, a message broker, and an event stream for a workload.\n\nNot this when: you are designing the broker topology of a high-volume event stream — `polymath-streaming:streaming-design`; or the *business* saga\u002Fchoreography — `polymath-architecture:event-driven-design`.\n\n## Inputs\n\n- The work: what it does, duration distribution (p50\u002Fp99), CPU\u002FIO\u002Fmemory profile, side effects, and whether the caller needs a result.\n- Arrival pattern: steady rate, burst size and duration, and the latency target to completion (seconds? hours?).\n- Failure characteristics: transient vs permanent errors, downstream rate limits, idempotency of the work, ordering needs.\n- Platform: available queue\u002Fbroker (SQS, RabbitMQ, Service Bus, Kafka\u002FEvent Hubs, Celery\u002FSidekiq\u002FTemporal), runtime, deployment\u002Fautoscaling.\n\n## Procedure\n\n1. **Decide whether to go async at all.** Async is right when the result isn't needed in the response, the work is slow\u002Fbursty\u002Funreliable, or it must survive a restart. If the user needs the answer, keep it synchronous or return `202` + a status resource\u002Fcallback and say how the client learns the outcome.\n2. **Pick the primitive:**\n   - **Task queue \u002F work queue** (SQS, RabbitMQ, Service Bus queue): each message processed by one worker; no replay; per-message ack and retry. For independent jobs.\n   - **Event stream \u002F log** (Kafka, Event Hubs, Kinesis): many consumers, replay, ordering per key, retention. For facts consumed by multiple parties or needing reprocessing.\n   - **Workflow engine** (Temporal, Step Functions, Durable Functions): long-running, multi-step, compensations, timers — don't hand-roll state machines in queue handlers.\n   - **Scheduler \u002F cron**: time-based; guard against overlap and missed runs (leader lock or idempotent job keyed by schedule slot).\n3. **Make the message and the worker safe to repeat.** Delivery is at-least-once. Define an idempotency key per unit of work and dedupe at the side-effecting boundary (unique constraint, conditional write, provider idempotency key). Enqueue from the database transaction via an outbox so work isn't lost or enqueued for a rolled-back change. Keep messages small (ids, not payloads) so workers read fresh state.\n4. **Retries, backoff, and the DLQ.** Classify errors: transient (retry with exponential backoff + jitter, capped attempts), permanent (don't retry — dead-letter immediately), poison (crashes the worker — dead-letter after N). Set visibility timeout\u002Flease longer than p99 job time (plus heartbeat for long jobs) or work gets processed twice concurrently. A DLQ needs an alert, an owner, inspect\u002Fredrive tooling, and a retention longer than the alert-to-fix time.\n5. **Size workers with Little's law.** In-flight work L = arrival rate λ × time in system W. Workers needed ≈ λ × service time ÷ target utilization (use `polymath-performance:high-load-io-design`'s calculator). Size for the burst you must absorb within the completion target, otherwise accept a queue and compute the drain time (backlog ÷ (capacity − λ)). If capacity ≤ arrival rate, the queue grows forever — no tuning fixes that.\n6. **Bound everything (backpressure).** Cap queue depth or age; decide the overflow policy explicitly: block\u002Fslow the producer, reject with `429`\u002F`503` + `Retry-After`, drop lowest priority, or spill to durable storage. Cap per-worker concurrency to what the downstream tolerates; use a token bucket for third-party rate limits (`polymath-scalability:rate-limiting-design`). Unbounded queues turn an overload into a delayed, bigger one.\n7. **Isolate and prioritize.** Separate queues (and worker pools) per priority and per workload class so bulk jobs can't starve interactive ones; per-tenant fairness (weighted fair queuing, per-tenant concurrency caps, or sharded queues) so one customer's import doesn't block everyone. Don't implement priority by sorting inside one queue unless the broker supports it.\n8. **Ordering.** Needed only per entity: partition\u002Fgroup by entity id (FIFO message groups, Kafka key) and accept lower parallelism per key. Global ordering doesn't scale; redesign to make operations commutative or versioned (last-write-wins by version, not arrival order).\n9. **Autoscale on the right signal.** Queue depth or age (or lag per worker), not CPU — an IO-bound worker is idle at CPU 5% while the queue explodes. Scale-in must drain gracefully (stop pulling, finish in-flight, extend lease); set a floor for burst readiness and a ceiling matching downstream capacity.\n10. **Observe and operate.** Metrics: queue depth, oldest-message age (the SLO metric), processing time, success\u002Fretry\u002FDLQ rates, in-flight, redelivery count. Trace context carried in the message. Runbooks for DLQ redrive, pausing a queue, and replay; test the redrive path.\n11. **Design the result path** for work with outcomes: status resource, webhook with signature + retries, or events; define expiry of results.\n\n## Output\n\n```text\nAsync design: report export\n\nDecision: async — exports take p50 40 s \u002F p99 6 min; user gets 202 + GET \u002Fexports\u002F{id}; email + webhook on completion.\nPrimitive: task queue (SQS) + worker pool; long steps → Temporal workflow not needed (single stage) [VERIFY: if multi-stage PDF merge is added].\nEnqueue: outbox in the orders DB → relay → SQS (message = {export_id}); worker loads state.\nIdempotency: exports.id unique; worker conditional update status=queued→running; file key = export_id (overwrite-safe).\nRetries: visibility timeout 15 min (p99 6 min + margin) + heartbeat; transient errors retry 5× backoff 30 s × 2ⁿ jittered; permanent (bad filter) → DLQ now; DLQ alarm on depth > 0; redrive tool in runbook.\nSizing: λ = 2\u002Fs peak, service 40 s mean → L = 80 in flight; target util 0.7 → 115 workers at burst; steady 15 min drain budget → [TBD: cost vs fewer workers + longer drain].\nBackpressure: depth cap 5,000 → API returns 429 + Retry-After 60; per-tenant limit 3 concurrent exports.\nIsolation: queues exports-interactive \u002F exports-bulk (scheduled), separate pools; fair share via per-tenant cap.\nOrdering: none required (exports independent).\nAutoscaling: scale on ApproximateAgeOfOldestMessage > 120 s (not CPU); scale-in drains in-flight; max 150 (DB replica read limit).\nSLO: 95% of exports complete \u003C 5 min; alert on oldest-message age > 10 min.\nResult: GET status; webhook signed (HMAC) with retries; result URL expires 7 d.\n```\n\n## Quality bar\n\n- At-least-once delivery is handled: each worker's side effects are idempotent with a named key.\n- Queue depth\u002Fage is bounded, with an explicit overflow policy and a backpressure signal to producers.\n- Worker count follows from arrival rate × service time and a utilization target (or says the queue never drains).\n- Priority and tenant isolation exist where mixed workloads share workers; DLQ has an owner, alert, and redrive path.\n- Autoscaling uses queue age\u002Fdepth; scale-in is graceful.\n\n## Anti-patterns to avoid\n\n- Unbounded queues \"to absorb spikes\" with no drain plan or age alert.\n- Enqueue after DB commit without an outbox (lost jobs) or before commit (ghost jobs).\n- One shared queue for interactive and bulk work; one tenant starving the rest.\n- Visibility timeout shorter than the job — duplicates running concurrently.\n- Retrying permanent errors forever; retry without jitter; no DLQ alert.\n- Autoscaling IO-bound workers on CPU.\n","# async-workload-design\n\n> Anything the user doesn't wait for should leave the request path — but a queue only moves the failure. Design bounded depth, idempotent workers, and what happens when work arrives faster than it drains.\n\n**Mode:** analytical — judgment inside a fixed frame. Keep the output shape; every verdict cites its evidence; unknowns are marked `[TBD]` or `[VERIFY]`, never filled in.\n\n## When to use\n\n- Offloading slow or bursty work (emails, exports, media processing, webhooks, ML jobs, third-party calls) from the request path.\n- Workers fall behind, queues grow without bound, jobs run twice, or one noisy tenant starves others.\n- Choosing between a task queue, a message broker, and an event stream for a workload.\n\nNot this when: you are designing the broker topology of a high-volume event stream — `polymath-streaming:streaming-design`; or the *business* saga\u002Fchoreography — `polymath-architecture:event-driven-design`.\n\n## Inputs\n\n- The work: what it does, duration distribution (p50\u002Fp99), CPU\u002FIO\u002Fmemory profile, side effects, and whether the caller needs a result.\n- Arrival pattern: steady rate, burst size and duration, and the latency target to completion (seconds? hours?).\n- Failure characteristics: transient vs permanent errors, downstream rate limits, idempotency of the work, ordering needs.\n- Platform: available queue\u002Fbroker (SQS, RabbitMQ, Service Bus, Kafka\u002FEvent Hubs, Celery\u002FSidekiq\u002FTemporal), runtime, deployment\u002Fautoscaling.\n\n## Procedure\n\n1. **Decide whether to go async at all.** Async is right when the result isn't needed in the response, the work is slow\u002Fbursty\u002Funreliable, or it must survive a restart. If the user needs the answer, keep it synchronous or return `202` + a status resource\u002Fcallback and say how the client learns the outcome.\n2. **Pick the primitive:**\n   - **Task queue \u002F work queue** (SQS, RabbitMQ, Service Bus queue): each message processed by one worker; no replay; per-message ack and retry. For independent jobs.\n   - **Event stream \u002F log** (Kafka, Event Hubs, Kinesis): many consumers, replay, ordering per key, retention. For facts consumed by multiple parties or needing reprocessing.\n   - **Workflow engine** (Temporal, Step Functions, Durable Functions): long-running, multi-step, compensations, timers — don't hand-roll state machines in queue handlers.\n   - **Scheduler \u002F cron**: time-based; guard against overlap and missed runs (leader lock or idempotent job keyed by schedule slot).\n3. **Make the message and the worker safe to repeat.** Delivery is at-least-once. Define an idempotency key per unit of work and dedupe at the side-effecting boundary (unique constraint, conditional write, provider idempotency key). Enqueue from the database transaction via an outbox so work isn't lost or enqueued for a rolled-back change. Keep messages small (ids, not payloads) so workers read fresh state.\n4. **Retries, backoff, and the DLQ.** Classify errors: transient (retry with exponential backoff + jitter, capped attempts), permanent (don't retry — dead-letter immediately), poison (crashes the worker — dead-letter after N). Set visibility timeout\u002Flease longer than p99 job time (plus heartbeat for long jobs) or work gets processed twice concurrently. A DLQ needs an alert, an owner, inspect\u002Fredrive tooling, and a retention longer than the alert-to-fix time.\n5. **Size workers with Little's law.** In-flight work L = arrival rate λ × time in system W. Workers needed ≈ λ × service time ÷ target utilization (use `polymath-performance:high-load-io-design`'s calculator). Size for the burst you must absorb within the completion target, otherwise accept a queue and compute the drain time (backlog ÷ (capacity − λ)). If capacity ≤ arrival rate, the queue grows forever — no tuning fixes that.\n6. **Bound everything (backpressure).** Cap queue depth or age; decide the overflow policy explicitly: block\u002Fslow the producer, reject with `429`\u002F`503` + `Retry-After`, drop lowest priority, or spill to durable storage. Cap per-worker concurrency to what the downstream tolerates; use a token bucket for third-party rate limits (`polymath-scalability:rate-limiting-design`). Unbounded queues turn an overload into a delayed, bigger one.\n7. **Isolate and prioritize.** Separate queues (and worker pools) per priority and per workload class so bulk jobs can't starve interactive ones; per-tenant fairness (weighted fair queuing, per-tenant concurrency caps, or sharded queues) so one customer's import doesn't block everyone. Don't implement priority by sorting inside one queue unless the broker supports it.\n8. **Ordering.** Needed only per entity: partition\u002Fgroup by entity id (FIFO message groups, Kafka key) and accept lower parallelism per key. Global ordering doesn't scale; redesign to make operations commutative or versioned (last-write-wins by version, not arrival order).\n9. **Autoscale on the right signal.** Queue depth or age (or lag per worker), not CPU — an IO-bound worker is idle at CPU 5% while the queue explodes. Scale-in must drain gracefully (stop pulling, finish in-flight, extend lease); set a floor for burst readiness and a ceiling matching downstream capacity.\n10. **Observe and operate.** Metrics: queue depth, oldest-message age (the SLO metric), processing time, success\u002Fretry\u002FDLQ rates, in-flight, redelivery count. Trace context carried in the message. Runbooks for DLQ redrive, pausing a queue, and replay; test the redrive path.\n11. **Design the result path** for work with outcomes: status resource, webhook with signature + retries, or events; define expiry of results.\n\n## Output\n\n```text\nAsync design: report export\n\nDecision: async — exports take p50 40 s \u002F p99 6 min; user gets 202 + GET \u002Fexports\u002F{id}; email + webhook on completion.\nPrimitive: task queue (SQS) + worker pool; long steps → Temporal workflow not needed (single stage) [VERIFY: if multi-stage PDF merge is added].\nEnqueue: outbox in the orders DB → relay → SQS (message = {export_id}); worker loads state.\nIdempotency: exports.id unique; worker conditional update status=queued→running; file key = export_id (overwrite-safe).\nRetries: visibility timeout 15 min (p99 6 min + margin) + heartbeat; transient errors retry 5× backoff 30 s × 2ⁿ jittered; permanent (bad filter) → DLQ now; DLQ alarm on depth > 0; redrive tool in runbook.\nSizing: λ = 2\u002Fs peak, service 40 s mean → L = 80 in flight; target util 0.7 → 115 workers at burst; steady 15 min drain budget → [TBD: cost vs fewer workers + longer drain].\nBackpressure: depth cap 5,000 → API returns 429 + Retry-After 60; per-tenant limit 3 concurrent exports.\nIsolation: queues exports-interactive \u002F exports-bulk (scheduled), separate pools; fair share via per-tenant cap.\nOrdering: none required (exports independent).\nAutoscaling: scale on ApproximateAgeOfOldestMessage > 120 s (not CPU); scale-in drains in-flight; max 150 (DB replica read limit).\nSLO: 95% of exports complete \u003C 5 min; alert on oldest-message age > 10 min.\nResult: GET status; webhook signed (HMAC) with retries; result URL expires 7 d.\n```\n\n## Quality bar\n\n- At-least-once delivery is handled: each worker's side effects are idempotent with a named key.\n- Queue depth\u002Fage is bounded, with an explicit overflow policy and a backpressure signal to producers.\n- Worker count follows from arrival rate × service time and a utilization target (or says the queue never drains).\n- Priority and tenant isolation exist where mixed workloads share workers; DLQ has an owner, alert, and redrive path.\n- Autoscaling uses queue age\u002Fdepth; scale-in is graceful.\n\n## Anti-patterns to avoid\n\n- Unbounded queues \"to absorb spikes\" with no drain plan or age alert.\n- Enqueue after DB commit without an outbox (lost jobs) or before commit (ghost jobs).\n- One shared queue for interactive and bulk work; one tenant starving the rest.\n- Visibility timeout shorter than the job — duplicates running concurrently.\n- Retrying permanent errors forever; retry without jitter; no DLQ alert.\n- Autoscaling IO-bound workers on CPU.\n",{"name":5,"description":7},"main","23f6e21841a39580c9da2b5ec941f39dda17cd86","plugins\u002Fpolymath-scalability\u002Fskills\u002Fasync-workload-design","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath","https:\u002F\u002Fgithub.com\u002FMohammadBafkar","2026-10-29 18:34:59",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add MohammadBafkar\u002Fpolymath --skill async-workload-design",{"tool":36,"command":37},"bunx","bunx skills add MohammadBafkar\u002Fpolymath --skill async-workload-design",{"tool":39,"command":40},"pnpm","pnpm dlx skills add MohammadBafkar\u002Fpolymath --skill async-workload-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-scalability\u002Fskills\u002Fasync-workload-design\u002FSKILL.md",true,[],[45,52,59,66,73,80],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M74GN87EBRHM9N87M7AP1HDD","runbook","Write or refresh an operational runbook for an alert\u002Fsymptom; structured as TL;DR + Pre-checks + Steps + Verification + Rollback + Escalation.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Frunbook\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M74GN5GPKEC1JEKP2DFQNEQJ","rfc","Draft a lightweight design RFC to docs\u002Frfcs\u002F\u003Cslug>.md; Summary, Motivation, Detailed design, Drawbacks, Alternatives, Unresolved questions. A proposal to debate, not a recorded decision (adr).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Frfc\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M74GN2F4CWPMV4X09TG4E304","editorial-pass","Review and tighten prose in a Markdown artifact for a target tone (terse, formal, friendly) without dropping information; preserve quotations and load-bearing constraints.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Feditorial-pass\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M74GMZWGYMZ37C4DYGT6P23G","architecture-review-facilitation","Run an architecture review as a process — entry criteria, reviewer checklist, decision log, and follow-up actions — pairing the design artifact with a red-team pass.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Farchitecture-review-facilitation\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M74GMXVX0YX3ETDXS527XDGM","architecture-doc","Write a C4-style architecture document; System Context + Containers (+ Components when interesting) with mermaid diagrams. Describes structure, not a decision (adr) or proposal (rfc).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Farchitecture-doc\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M74GMVG1WSMCK066S3KE6V5K","adr","Write an Architecture Decision Record (Michael Nygard format) to docs\u002Fadrs\u002FNNNN-\u003Cslug>.md; frontmatter validated by the ADR artifact schema. Records a made decision, not a proposal to debate (rfc).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Fadr\u002FSKILL.md",[],[]]