Backend Concurrency Mechanicsのロゴ

Backend Concurrency Mechanics

コミュニティ
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).

概要

公開者j4flmao
リポジトリagent-skills
スキル名backend-concurrency-mechanics
スター
41
フォーク
6
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    j4flmaoがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Backend Concurrency Mechanics」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrency
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

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
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでBackend Concurrency Mechanicsを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にBackend Concurrency Mechanicsを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Backend Concurrency Mechanicsは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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.

よくある質問

AIスキル「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...

TypingMindでBackend Concurrency Mechanicsを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Backend Concurrency Mechanicsはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにBackend Concurrency Mechanicsをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/j4flmao/agent-skills/tree/main/skills/backend/universal/concurrencyを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Backend Concurrency Mechanicsを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Backend Concurrency Mechanicsで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもBackend Concurrency Mechanicsを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Backend Concurrency Mechanics」は無料ですか?

はい。j4flmaoがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇