async-concurrency-correctness
Skill9 starsChanged 5 months agoApache-2.0View on GitHub
Writes and fixes correct async/concurrent code across Python (asyncio), TypeScript (Promises), Rust (tokio), and Go (goroutines/channels), targeting deadlocks, races, cancellation, and backpressure.
In this repository147 other files it gives its agents.
- second-brain/AGENTS.mdAGENTS.md
- second-brain/CLAUDE.mdCLAUDE.md
- agent-tool-mcp-builderSkill
- api-design-reviewSkill
- audit-accessibility-wcagSkill
- audit-license-complianceSkill
- audit-technical-seoSkill
- auth-jwt-sessionSkill
- author-codemodSkill
- brainstorm-designSkill
- build-audit-loggingSkill
- build-cdc-streaming-pipelineSkill
- build-cli-toolSkill
- build-data-tableSkill
- build-etl-pipelineSkill
- build-form-validationSkill
- build-native-mobile-uiSkill
- build-office-docsSkill
- build-offline-first-syncSkill
- build-react-componentSkill
- build-realtime-channelSkill
- build-spreadsheetSkill
- build-vector-searchSkill
- caching-strategySkill
- cicd-pipeline-authorSkill
- cloud-cost-optimizeSkill
- code-commentsSkill
- code-reviewSkill
- compose-local-dev-stackSkill
- configure-bundler-buildSkill
- configure-dns-tlsSkill
- configure-reverse-proxy-lbSkill
- configure-security-headers-cspSkill
- contract-testingSkill
- datetime-timezone-correctnessSkill
- db-migration-safetySkill
- debug-ci-pipeline-failureSkill
- debug-flaky-testsSkill
- debug-frontend-browserSkill
- debug-root-causeSkill
- defend-llm-prompt-injectionSkill
- deliver-webhooksSkill
- dependency-upgradeSkill
- deploy-releaseSkill
- design-api-paginationSkill
- design-authorization-modelSkill
- design-backup-dr-recoverySkill
- design-event-sourcing-cqrsSkill
- design-multi-tenancySkill
- design-protobuf-grpc-serviceSkill
- design-relational-schemaSkill
- design-search-index-infraSkill
- design-state-machineSkill
- design-token-systemSkill
- diff-table-paritySkill
- distributed-locks-leasesSkill
- dockerfile-optimizeSkill
- encrypt-sensitive-dataSkill
- error-messageSkill
- estimate-workSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 15
Do NOT use for single-threaded refactors, naming, or non-timing-dependent logic bugs — that's refactor-cleanup.
- Distinctive: line 58
Eliminate shared mutable state or make access correct: Prefer message-passing/ownership over shared memory.
- Very specific: line 60
Use atomics for counters (std::sync::atomic, Go atomic, not bare i++).
- Distinctive: line 77
Loop variable captured by goroutine pre-Go 1.22: all goroutines see the last value.
- Very specific: line 87
Stress test: run the hot path with N concurrent callers (e.g.
- Very specific: line 88
Deadlock check: add a hard timeout to the test itself (go test -timeout 30s, asyncio.timeout, jest testTimeout) so a hang fails loudly …
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
When to Use
Reach for this skill when the code touches more than one thing happening at once and correctness depends on ordering, timing, or shared state:
- Writing/reviewing
async/await, event loops,goroutine+channel,tokio::spawn, thread pools, locks, queues. - A symptom points at concurrency: hang/deadlock, intermittent test failure, data race, "works once then stalls", leaked/zombie tasks, OOM under load, event loop "blocked" warnings, requests timing out under concurrency but fine serially.
- Adding parallelism to existing serial code (fan-out, worker pool, pipeline).
Do NOT use for single-threaded refactors, naming, or non-timing-dependent logic bugs — that's refactor-cleanup. If a "race" reproduces 100% deterministically serially, it's a logic bug, not a concurrency bug — stop and treat it as one.
First move: identify the runtime model before writing a line. The right fix differs per runtime.
| Runtime | Model | Key constraint |
| Python asyncio | single-thread cooperative loop | one blocking call freezes everything; CPU work needs a process, not a thread (GIL) |
| TypeScript/Node | single-thread microtask queue | sync CPU blocks the loop; await in a for serializes; unhandled rejection can crash |
| Rust tokio | M:N work-stealing (multi-thread) or current-thread | blocking a worker starves the pool; !Send futures can't cross threads |
| Go | M:N goroutine scheduler, preemptive | true parallelism → real data races; nil/closed channel semantics bite |
Steps
- Pin the runtime + executor flavor. asyncio (
asyncio.run?) · tokio (#[tokio::main]multi-thread vsflavor = "current_thread"?) · Go (GOMAXPROCS?) · Node (worker_threads in play?). Decisions below depend on this. - Get blocking work off the async path. Anything that doesn't yield blocks the whole loop/worker:
- asyncio: wrap sync/CPU/file-I/O in
await asyncio.to_thread(fn, ...); for CPU-bound useloop.run_in_executor(ProcessPoolExecutor(), ...)(threads won't help under the GIL). - tokio:
tokio::task::spawn_blocking(move || ...).awaitfor blocking syscalls/CPU; never callstd::thread::sleep, blockingMutexheld across.await, or sync file I/O on a worker. - Node: move CPU work to a
worker_thread; never a synchronous loop,fs.readFileSync, orJSON.parseof a huge string on the main thread. - Go: blocking is fine (scheduler handles it), but cap goroutines spawned around it (step 5).
- asyncio: wrap sync/CPU/file-I/O in
- Never hold a sync lock across an await/yield point. This is the #1 async deadlock.
- asyncio: use
asyncio.Lock(anasync with), notthreading.Lock, aroundawait. If you must touch athreading.Lock, acquire→mutate→release with zero awaits inside. - tokio: use
tokio::sync::Mutexonly when the guard must survive.await. Otherwise preferstd::sync::Mutexand drop the guard before.await(scope it in a block, orlet v = *guard; drop(guard);). Holdingstd::sync::Mutexacross.awaitis a hang waiting to happen. - Go:
sync.Mutexis fine but neverLock()then<-ch/anotherLock()while holding it — order all locks consistently to kill lock-ordering deadlocks.
- asyncio: use
- Make cancellation and shutdown explicit. Tasks must be reliably stoppable and joined.
- asyncio: prefer
asyncio.TaskGroup(3.11+) so a child failure cancels siblings and youawaitthem all; useasyncio.timeout(s)for deadlines. Every barecreate_taskmust be stored and awaited/cancelled — fire-and-forget tasks get GC'd and silently dropped. On shutdown: cancel, thenawait asyncio.gather(*tasks, return_exceptions=True). Catchasyncio.CancelledError, run cleanup, then re-raise it — swallowing it breaks cancellation. - tokio: pass a
tokio_util::sync::CancellationToken(orselect!on a shutdown channel) into long tasks; wrap deadlines intokio::time::timeout. Note a droppedJoinHandledoes not cancel the task — call.abort()or use aJoinSet. Cancellation drops at the next.await, so keep state consistent at every await point. - Node: thread an
AbortSignalinto fetch/timers/streams; race work againstAbortSignal.timeout(ms). - Go: every goroutine takes
ctx context.Contextand returns on<-ctx.Done(); paircontext.WithTimeout/WithCancelwith adefer cancel(). Use async.WaitGroupto join before exit so you don't leak.
- asyncio: prefer
- Bound concurrency — never unbounded fan-out. Spawning one task per input will exhaust memory/sockets/fds.
- asyncio: gate with
asyncio.Semaphore(N)around each unit, or process in chunks;gatherover a fixed worker pool, not over N inputs. - tokio:
Semaphore::new(N)+acquire_owned, orbuffer_unordered(N)on afutures::stream. - Node: pool with
p-limit/a concurrency cap; an unawaitedarray.map(async ...)fires all at once — wrap inpLimitor batch. - Go: fixed-size worker pool reading from a jobs channel (
for w := 0; w < N; w++ { go worker() }), or a buffered semaphore channelsem := make(chan struct{}, N).
- asyncio: gate with
- Channels/queues must have backpressure. Bounded by default; unbounded queues just move the OOM downstream and hide the real throughput limit.
- Go:
make(chan T, N)(buffered) so producers block when consumers lag; close the channel exactly once, from the sender side only; never send on a closed channel. Drain orselect{ case <-ctx.Done(): }to avoid send-blocked leaks. - asyncio:
asyncio.Queue(maxsize=N);await queue.putblocks the producer under load (that's the point). Use sentinel values ortask_done()/join()to signal completion. - Rust:
tokio::sync::mpsc::channel(N)(bounded), notunbounded_channel.send().awaitapplies backpressure.
- Go:
- Eliminate shared mutable state or make access correct. Prefer message-passing/ownership over shared memory. If shared:
- Make handlers idempotent (retries + at-least-once delivery will re-run them).
- Use atomics for counters (
std::sync::atomic, Goatomic, not barei++); use proper guarded structures for the rest. - Go: protect every shared field — a single unguarded write under
-raceis a real bug, not a warning to ignore.
- Verify under contention, not just once (see Verify).
Common Errors
std::sync::Mutexguard held across.await(Rust): task parks holding the lock → deadlock. Drop the guard before awaiting, or switch totokio::sync::Mutex.threading.Lockinstead ofasyncio.Lock(Python): blocks the whole loop or deadlocks. Use the async lock around awaits.- Fire-and-forget
asyncio.create_task(...)without keeping a reference: the task can be garbage-collected mid-flight and exceptions vanish. Store it; await or cancel it; or useTaskGroup. - Swallowing
CancelledError:except Exceptioncatches it (it'sBaseExceptionin 3.8+ but still easy to over-catch) — clean up and re-raise, or cancellation silently no-ops. awaitinside aforloop when you meant parallel (JS/Python): serializes everything. UsePromise.all/asyncio.gather— but then add a concurrency cap (step 5) so it's not unbounded.Promise.allfor fan-out with no limit: opens thousands of connections at once. Cap it.- Unhandled promise rejection (Node): crashes or silently drops the result. Always
.catch/tryaround detached promises; addprocess.on('unhandledRejection')as a backstop, not a fix. JoinHandledropped expecting cancellation (tokio): dropping does NOT abort the task — it keeps running detached. Use.abort()or aJoinSet.- Closing a Go channel from the receiver, or twice: panics. Close once, from the sole sender. Sending on a closed/nil channel panics/blocks forever.
selectwith nodefaultand no ready case (Go): blocks forever — a silent deadlock. Add actx.Done()case.- Loop variable captured by goroutine pre-Go 1.22: all goroutines see the last value. Pass it as an arg or shadow it.
- Treating
-race/ lint warnings as noise: a reported race is a real bug. Fix the root cause; never suppress it to make CI green. - CPU-bound work in
to_thread/spawn_blockingexpecting parallelism (Python): GIL serializes it. Use processes for CPU. - Blocking call sneaking onto a tokio worker (
reqwest::blocking, syncstd::fs,std::thread::sleep): starves the runtime. Use async equivalents orspawn_blocking.
Verify
A concurrency fix isn't done until it survives contention. Don't trust a single green run.
- Run under the race detector / sanitizer: Go
go test -race ./...andgo run -race; RustRUSTFLAGS="-Zsanitizer=thread"(nightly) or at minimumcargo testwithtokio--features fulland Loom for lock-free code; Python/Node — add a stress test (below). - Stress test: run the hot path with N concurrent callers (e.g. 100–1000), repeated 100+ iterations. Flaky pass = unfixed race. In Go run with
-count=100 -race; in async langs spawn the opgather/Promise.all/JoinSetwith a high count and assert invariants every run. - Deadlock check: add a hard timeout to the test itself (
go test -timeout 30s,asyncio.timeout, jesttestTimeout) so a hang fails loudly instead of hanging CI. - Leak check: assert no growth in task/goroutine count after the workload settles — Go
runtime.NumGoroutine()before/after; asynciolen(asyncio.all_tasks()); tokio task count via aJoinSet/metrics. Steady-state count must return to baseline. - Backpressure check: drive producers faster than consumers and confirm bounded memory (queue depth stays ≤ N, RSS flat) instead of unbounded growth.
- Cancellation check: trigger shutdown/timeout mid-flight and assert all tasks stopped, resources released (no leaked connections/fds/locks), and no
CancelledError/panic escaped.
Show the actual command + output as evidence. "Looks fine" is not verification for concurrency.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

