Logotipo de Backend Concurrency Mechanics

Backend Concurrency Mechanics

Comunidad
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).

Descripción general

Editorj4flmao
Repositorioagent-skills
Nombre de la habilidadbackend-concurrency-mechanics
Estrellas
41
Forks
6
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por j4flmao en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Backend Concurrency Mechanics en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrency
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

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
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Backend Concurrency Mechanics en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Backend Concurrency Mechanics automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Backend Concurrency Mechanics no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

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.

Preguntas frecuentes

¿Qué hace la habilidad de IA 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...

¿Por qué usar Backend Concurrency Mechanics en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Backend Concurrency Mechanics está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Backend Concurrency Mechanics en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrency. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Backend Concurrency Mechanics?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Backend Concurrency Mechanics?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Backend Concurrency Mechanics con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Backend Concurrency Mechanics?

Sí. j4flmao la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇