bedkillerspacex-boop/codex-skill-library/node-worker-threads-basics

Claude Code and agent skill by bedkillerspacex-boop/codex-skill-library

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Use Node.js worker_threads for CPU-bound work without blocking the event loop: Worker API, message passing, SharedArrayBuffer care, pooling, and memory leak avoidance. Use for owned Node services doing CPU-heavy tasks.

Install

npx vskill@latest install bedkillerspacex-boop/codex-skill-library/node-worker-threads-basics

SKILL.md

The same SKILL.md was published earlier as bedkillerspacex-boop/codex-skill-library/node-worker-threads-basics.

Node.js worker_threads Basics

Scope And Authorization

  • In scope: Node applications you own.
  • Out of scope: crypto-mining malware patterns; abusing shared hosts.
  • Workers are not free — pool size ≈ CPU cores for pure CPU tasks.
  • Pair with undici tuning for I/O; permission model for sandboxing.

When To Use

  • CPU-heavy work (image resize, parse, crypto, compression) blocking event loop.
  • Offloading from Express/Fastify request path.
  • Replacing naive child_process for in-process parallelism with structured messaging.
  • Debugging growing memory with unbounded Worker creation.

Do Not Use As Primary

NeedSkill instead
HTTP client poolingnode-undici-agent-tuning
Permission flagsnodejs-permission-model
diagnostics_channelnodejs-diagnostics-channel
Implementation quality baselinecode-quality-standards

Domain Focus

APIRole
`new Worker(filenameurl)`Start worker
parentPort.postMessageSend structured clone / transfer list
worker.on('message')Receive
worker.terminate()Stop
isMainThreadBranch entry
workerDataInit payload
TransferablesArrayBuffer move ownership
Piscina / poolReuse workers

Workflow

1. Identify CPU bottleneck
bash
# Event loop lag metrics; flamegraphs showing sync CPU in request handlers
  1. I/O-bound work should stay async on main thread — workers won’t help much.
  2. Success: p95 latency drops; main thread lag reduced; memory stable.
2. Minimal worker
js
// worker-task.js
const { parentPort, workerData } = require('node:worker_threads');
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
parentPort.postMessage({ result: fib(workerData.n) });
js
// main.js
const { Worker } = require('node:worker_threads');
function runFib(n) {
return new Promise((resolve, reject) => {
const worker = new Worker(require.resolve('./worker-task.js'), {
workerData: { n },
});
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0) reject(new Error(`exit ${code}`));
});
});
}
3. Prefer a pool
js
// Conceptual — use piscina or fixed pool
// maxThreads: os.cpus().length
// idleTimeout: recycle workers to mitigate leaks
  1. Never new Worker per request at high RPS without pool limits.
  2. Queue overflow → 503 to caller rather than unbounded memory.
4. Message design
  1. Prefer structured clone of plain data; transfer large ArrayBuffers.
  2. Avoid circular objects; handle clone errors.
  3. Protocol: { id, type, payload } for multiplexed tasks on one worker.
5. SharedArrayBuffer / Atomics
  1. Only when needed; mind crossOriginIsolated for browsers (N/A server).
  2. Race bugs are easy — prefer message passing first.
  3. Document memory ordering assumptions.
6. Errors and teardown
js
worker.on('error', (err) => log.error({ err }));
await worker.terminate();
  1. Unhandled worker exceptions kill worker — pool should respawn.
  2. On process shutdown: terminate pool gracefully.
7. Memory leak checklist
SmellFix
Workers per requestPool
Huge closures in workerDataPass minimal data
Listeners not removedOnce handlers / pool managed
Unbounded result buffersStream/chunk
Old Node worker bugsStay patched

Good / Bad

TopicGoodBad
CreationPooled workersnew Worker every request
Work typeCPU-boundWrapping simple fs.readFile
MessagesSmall JSON + transfer buffersClone multi-MB objects every ms
FailuresRespawn + fail requestHang promise forever
Size~CPU count1000 threads on 4 CPUs

Output Checklist

  • [ ] Bottleneck is CPU not I/O
  • [ ] Worker module isolated
  • [ ] Pool with max threads + queue
  • [ ] Message protocol defined
  • [ ] Error/exit handled
  • [ ] Shutdown terminates workers
  • [ ] Memory stable under load test
  • [ ] Main thread lag improved
  • [ ] code-quality-standards applied

Rules

  • Bound worker count and queue depth.
  • Do not block workers on async I/O meant for main thread patterns without reason.
  • Owned services only.
  • Measure before and after.

Security

  • Security scanPassed, 90 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/bedkillerspacex-boop/codex-skill-library/node-worker-threads-basics/badge)](https://verified-skill.com/skills/bedkillerspacex-boop/codex-skill-library/node-worker-threads-basics)

Something wrong with this skill or its page? Tell us.