Logo: Backend Concurrency Mechanics

Backend Concurrency Mechanics

Communautéit
j4flmao
backend-concurrency-mechanics

Use this skill when the user says 'race condition', 'data race', 'goroutine vs thread', 'event loop blocking', 'memory barrier', 'memory model', 'mutex vs atomic', 'deadlock', 'thread pool sizing', 'virtual threads', 'async vs threads'. Explains how OS threads, M:N schedulers (Go goroutines, Java virtual threads), and event loops (Node.js, Python asyncio) actually execute work, and gives correct synchronization patterns for backend services. Do NOT use for: cross-process locks (backend-distributed-locking), job queues (backend-background-jobs), database isolation levels (backend-database-patterns).

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummbackend-concurrency-mechanics
Stären
41
Forks
6
Matgeliwwert Dateien
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    j4flmao huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Backend Concurrency Mechanics an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrency
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/universal/concurrency .claude/skills/backend-concurrency-mechanics
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Backend Concurrency Mechanics an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Backend Concurrency Mechanics automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Backend Concurrency Mechanics net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Concurrency Mechanics

Purpose

Pick the right concurrency model for a workload and write shared-state code that is correct under the language's memory model. Most production concurrency bugs come from unsynchronized shared state, blocking an event loop, or unbounded parallelism; this skill targets those.

Agent Protocol

Trigger

Exact user phrases: "race condition", "data race", "goroutine vs thread", "event loop blocking", "memory barrier", "memory model", "mutex vs atomic", "deadlock", "thread pool sizing", "virtual threads", "async vs threads".

Input Context

  • Language/runtime and version (Go, Java 21+, Node.js, Python, Rust, .NET).
  • Workload type: I/O-bound, CPU-bound, or mixed.
  • The shared state or code path that misbehaves; any race detector output.

Output Artifact

Explanation of the execution model plus corrected code. No files unless requested.

Response Format

Model: {OS threads | M:N (goroutines/virtual threads) | event loop}
Workload: {I/O-bound | CPU-bound}
Shared state: {what} -> {mutex | atomic | channel/actor | immutable copy}
Bound: {pool size / semaphore N}
Verify: {go test -race | jcstress | stress test}

Execution Models

ModelExamplesSchedulingCost per unitBlocking call behaviour
1:1 OS threadsJava platform threads, C++ std::thread, Python threadsKernel schedulerEach thread reserves a stack (commonly 1 MB on Windows, 8 MB virtual on Linux glibc, committed lazily) plus kernel structuresBlocks only that thread
M:N user-spaceGo goroutines, Java 21 virtual threads, Erlang processesRuntime multiplexes many tasks onto a few OS threadsSmall growable stacks (Go starts at 2 KB)Runtime parks the task; blocking syscalls may pin a carrier thread
Event loopNode.js (libuv), Python asyncio, Netty, Redis command executionSingle thread runs callbacks/coroutines when I/O is ready (epoll, kqueue, IOCP)Very cheap per connectionAny CPU-heavy or synchronous call stalls every request

Go scheduler (G-M-P)

  • G goroutine, M OS thread, P logical processor holding a local run queue; GOMAXPROCS sets the number of Ps (defaults to CPU count; since Go 1.25 it also respects cgroup CPU limits on Linux).
  • An idle P steals half of another P's local queue (work stealing) and also polls the global queue and network poller.
  • When a goroutine enters a blocking syscall, its M is detached from the P so another M can keep running goroutines.

Java virtual threads (Java 21+)

  • Mounted on a small ForkJoinPool of carrier threads; blocking I/O unmounts them.
  • Pinning: in Java 21-23, blocking inside synchronized pins the carrier; JDK 24 (JEP 491) removed that for synchronized. Native calls still pin.
  • Do not pool virtual threads; limit concurrency to downstream resources with a Semaphore.

Node.js event loop

  • JavaScript runs on one thread; network I/O is non-blocking via the OS; file system, DNS lookup, crypto and zlib use the libuv thread pool (default 4, UV_THREADPOOL_SIZE).
  • Microtasks (resolved promises, queueMicrotask) drain fully after each macrotask, so a promise loop can starve I/O.
  • CPU-bound work goes to worker_threads or another service.

Memory Models in Practice

Compilers and CPUs reorder memory operations. x86 (TSO) only allows a later load to pass an earlier store; ARM and POWER allow much more reordering. You do not write fences by hand in application code: the language memory model guarantees visibility when you use its synchronization primitives.

LanguageHappens-before established by
Gochannel send/receive, sync.Mutex, sync.WaitGroup, sync/atomic (sequentially consistent)
Javasynchronized, volatile, java.util.concurrent locks/atomics, Thread.start/join
C++/Ruststd::atomic with acquire/release or seq_cst ordering, mutexes
JSSingle-threaded; SharedArrayBuffer + Atomics between workers

A data race is two concurrent accesses to the same memory, at least one a write, without happens-before ordering. In Go and C++ the result is undefined behaviour territory (torn reads, stale values); do not reason about "benign" races.

Correct Patterns (Go)

go
package counter

import (
	"context"
	"sync"
	"sync/atomic"

	"golang.org/x/sync/errgroup"
)

// Single integer: atomic is enough.
type Hits struct{ n atomic.Int64 }

func (h *Hits) Inc()         { h.n.Add(1) }
func (h *Hits) Load() int64  { return h.n.Load() }

// Compound invariant (map + total) needs a mutex: atomics cannot make
// two updates appear as one.
type Stats struct {
	mu     sync.Mutex
	byPath map[string]int
	total  int
}

func NewStats() *Stats { return &Stats{byPath: make(map[string]int)} }

func (s *Stats) Record(path string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.byPath[path]++
	s.total++
}

// Bounded fan-out: never start one goroutine per item without a limit.
func FetchAll(ctx context.Context, urls []string, fetch func(context.Context, string) error) error {
	g, ctx := errgroup.WithContext(ctx)
	g.SetLimit(16) // bound concurrency to protect downstreams
	for _, u := range urls {
		g.Go(func() error { return fetch(ctx, u) }) // Go 1.22+: loop var is per-iteration
	}
	return g.Wait() // first error cancels ctx for the rest
}

Verify with go test -race ./... in CI; the race detector only finds races on executed paths, so run it with concurrent tests.

Choosing a Primitive

SituationUse
Single counter/flagAtomic
Several fields that must change togetherMutex (RWMutex only if reads dominate and critical sections are long enough to matter)
Ownership transfer / pipeline stagesChannels or queues
Read-mostly configImmutable snapshot swapped via atomic pointer (atomic.Pointer[T], AtomicReference)
Limit concurrent calls to a dependencySemaphore / bounded pool
Per-key serializationShard locks by hash of key, or an actor/queue per key

Pool Sizing

  • CPU-bound: about the number of cores; more threads only add context switches.
  • I/O-bound with threads: Little's law, concurrency = throughput x latency (e.g. 200 req/s x 0.05 s = 10 in flight), then cap at what the downstream (DB pool, API rate limit) accepts.
  • The DB connection pool is usually the real limit; size app concurrency to it, not the other way round.

Deadlocks and Liveness

  • Acquire multiple locks in one global order.
  • Never hold a lock while doing I/O or calling unknown callbacks.
  • Always pass deadlines (context.Context, CompletableFuture.orTimeout, AbortSignal.timeout).
  • Goroutine leaks: every goroutine needs an exit path (closed channel or cancelled context); monitor runtime.NumGoroutine().

Anti-Patterns

Anti-patternFix
sync.WaitGroup + shared slice append without lockPre-size slice and write by index, or collect via channel
JSON.parse of 50 MB or bcrypt sync calls in Node request pathStream/parse in worker thread; use async APIs
time.Sleep/polling for coordinationChannels, condition variables, or context
Check-then-act on shared map (if !exists { insert })Single critical section or LoadOrStore
Unbounded goroutines/threads per requesterrgroup limit, semaphore, worker pool

Checklist

  • Execution model and workload type identified.
  • Every shared mutable value has one documented synchronization mechanism.
  • Concurrency bounded per downstream dependency.
  • Event loop free of CPU-heavy or synchronous calls.
  • Race detector / stress tests in CI; goroutine or thread counts monitored.

References

  • Related skills: skills/backend/universal/distributed-locking/SKILL.md, skills/backend/universal/background-jobs/SKILL.md, skills/backend/universal/resilience-patterns/SKILL.md.

Heefeg gestallte Froen

Wat mécht de KI-Skill Backend Concurrency Mechanics?

Use this skill when the user says 'race condition', 'data race', 'goroutine vs thread', 'event loop blocking', 'memory barrier', 'memory model', 'mutex vs atomic', 'deadlock', 'thread pool sizing', 'virtual threads', 'async vs threads'. Explains how OS threads, M:N schedulers (Go goroutines, Java virtual threads), and event loops (Node.js, Python asyncio) actually execute work, and gives correct synchronization patterns for backend services. Do NOT use for: cross-process locks (backend-distributed-locking), job queues (backend-background-jobs), database isolation levels (backend-database-pa...

Firwat Backend Concurrency Mechanics op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Backend Concurrency Mechanics besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Backend Concurrency Mechanics an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrency an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Backend Concurrency Mechanics benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Backend Concurrency Mechanics benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Backend Concurrency Mechanics domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Backend Concurrency Mechanics gratis?

Jo. j4flmao huet de Skill ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇