This prompt is designed for platform engineers, tech leads, and code reviewers who need to systematically identify known concurrency anti-patterns in submitted code before they reach production. The job-to-be-done is not a general code review but a targeted, pattern-based scan for specific, well-documented concurrency defects such as incorrect double-checked locking, unbounded thread-per-request creation, busy-wait loops, and unsynchronized lazy initialization. The ideal user is someone who understands the concurrency primitives of the target language but wants a consistent, automated second pair of eyes that won't overlook subtle, repeatable mistakes buried in a large diff.
Prompt
Concurrency Anti-Pattern Detection Prompt

When to Use This Prompt
Define the job, the ideal user, required inputs, and the boundaries where this prompt should not be applied.
To use this prompt effectively, you must provide the full source code of the change or module under review as [INPUT], along with the programming language in [LANGUAGE] so the model can apply language-specific pattern recognition. The prompt works best when the code is self-contained and the anti-patterns are structural—meaning they can be identified from the code's shape and synchronization usage without requiring a running trace. Do not use this prompt for performance tuning, lock contention profiling, or for finding novel, zero-day concurrency bugs that require deep domain knowledge of a proprietary system. It is a pattern detector, not a formal verifier or a substitute for dynamic race detectors like ThreadSanitizer. If the code change is a complex, multi-service workflow where concurrency risk is distributed across network boundaries, this prompt will miss those cross-system interactions.
The output is a structured report of findings, each mapped to a specific anti-pattern name, code location, a human-readable explanation of the flaw, and concrete refactoring guidance. This makes the prompt directly embeddable into a CI/CD pipeline as a quality gate, where findings can be posted as automated review comments. However, you must pair this prompt with a validation step: false positives are possible, especially when the model misinterprets intentional, low-level synchronization for an anti-pattern. Always require a human reviewer to confirm or dismiss each finding before blocking a merge. For high-risk code paths handling financial transactions or safety-critical state, escalate findings to a mandatory senior engineer review rather than relying solely on the prompt's severity classification.
Use Case Fit
Where this prompt works and where it does not. Concurrency anti-pattern detection requires specific code context and language awareness to produce reliable results.
Good Fit: Known Anti-Pattern Catalog
Use when: you have a defined catalog of concurrency anti-patterns to check against, such as double-checked locking bugs, busy-wait loops, or thread-per-request without bounds. The prompt performs best when matching code against known patterns with clear signatures. Guardrail: maintain a living anti-pattern registry with language-specific examples and false-positive notes.
Bad Fit: Novel Concurrency Bugs
Avoid when: the code contains novel or highly domain-specific concurrency bugs that don't match known anti-pattern templates. The prompt relies on pattern matching and may miss subtle interleaving bugs, memory model edge cases, or framework-specific synchronization issues. Guardrail: pair with dynamic analysis tools, stress testing, and human expert review for novel bug detection.
Required Input: Language and Framework Context
What to watch: the prompt needs explicit language version, concurrency model, and framework context to produce accurate anti-pattern detection. Without this, it may flag correct patterns as bugs or miss language-specific pitfalls. Guardrail: always include language, runtime version, and concurrency primitives in use as part of the input context.
Required Input: Complete Code Context
What to watch: anti-pattern detection requires surrounding code context, not just isolated snippets. Lock ordering violations, shared state access, and goroutine lifecycle bugs span multiple functions or files. Guardrail: provide full function bodies, relevant struct definitions, and call site context. Flag when context is incomplete and results may be unreliable.
Operational Risk: False Positive Fatigue
What to watch: the prompt may flag correct synchronization patterns as anti-patterns, especially in performance-optimized code, lock-free structures, or framework-internal code. High false positive rates erode reviewer trust. Guardrail: require human verification for all findings, track false positive rates per anti-pattern, and tune detection thresholds based on team feedback.
Operational Risk: Language Model Drift
What to watch: model behavior may shift across versions, causing previously caught anti-patterns to be missed or new false positives to appear. Concurrency detection is sensitive to subtle instruction interpretation changes. Guardrail: maintain a regression test suite of known concurrency bugs and false-positive examples, run before prompt version changes, and monitor detection rates in production.
Copy-Ready Prompt Template
A reusable prompt template for detecting known concurrency anti-patterns in code submissions, with placeholders for input, context, and output constraints.
This prompt template is designed to be dropped into a code review pipeline or used manually by a platform engineer. It instructs the model to act as a concurrency reviewer, scanning the provided code for a specific set of high-risk anti-patterns. The template uses square-bracket placeholders for the code under review, the programming language, any additional constraints, and the desired output schema. This separation ensures the prompt can be reused across different repositories and languages without modification.
textYou are a senior systems engineer specializing in concurrent and parallel programming. Your task is to review the provided [LANGUAGE] code for known concurrency anti-patterns. Review the following code: ```[LANGUAGE] [CODE_DIFF_OR_SNIPPET]
Specifically, you must detect and report on these anti-patterns:
- Double-Checked Locking Bugs: Incorrect implementations of the double-checked locking pattern, including missing volatile keywords, incorrect null checks, or partially constructed objects.
- Busy-Wait Loops: Loops that repeatedly check a condition without yielding, sleeping, or using proper signaling mechanisms, leading to CPU starvation.
- Unbounded Thread/Goroutine Creation: Patterns like "thread-per-request" or "goroutine-per-task" without bounds, connection pooling, or worker pools, which risk resource exhaustion.
- Incorrect Double-Checked Locking: Any variant where the synchronization logic is flawed, even if it doesn't match the classic pattern exactly.
For each detected anti-pattern, provide a structured finding with the following fields:
anti_pattern_name: The name of the anti-pattern.location: The specific file path and line range (e.g.,src/handler.go:45-52).explanation: A clear, concise explanation of why this code matches the anti-pattern and the concurrency risk it introduces.severity: One ofCRITICAL,HIGH,MEDIUM, orLOW.refactoring_guidance: A specific, actionable suggestion for fixing the issue, including a brief code sketch if helpful.
[CONSTRAINTS]
- Only report on the four anti-patterns listed above. Do not flag general code style issues or other concurrency concerns.
- If no anti-patterns are found, return an empty list.
- Base your analysis strictly on the provided code. Do not speculate about external systems.
Return your findings as a JSON object matching this exact schema: { "findings": [ { "anti_pattern_name": "string", "location": "string", "explanation": "string", "severity": "CRITICAL|HIGH|MEDIUM|LOW", "refactoring_guidance": "string" } ] }
To adapt this template, replace the placeholders with your specific context. [LANGUAGE] should be set to the programming language of the code under review (e.g., Java, Go, Python). [CODE_DIFF_OR_SNIPPET] is the actual code, which could be a unified diff from a pull request or a standalone code block. The [CONSTRAINTS] section is a powerful extension point: you can add rules like "ignore test files," "focus only on files changed in the last commit," or "do not report issues already present in the main branch." For high-risk production systems, always route findings with CRITICAL or HIGH severity for mandatory human review before merging.
Prompt Variables
Required inputs for the Concurrency Anti-Pattern Detection Prompt. Each variable must be populated before the prompt is sent to the model. Missing or malformed inputs are the most common cause of false negatives and unparseable output.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CODE_DIFF] | The unified diff or code snippet to analyze for concurrency anti-patterns | diff --git a/pkg/lock/lock.go b/pkg/lock/lock.go @@ -10,6 +10,8 @@ func GetInstance() *Singleton {
| Must be non-empty and contain at least one function or method block. Parse check: diff must contain @@ hunk headers or be a valid code block with recognizable concurrency primitives (mutex, channel, goroutine, async/await, synchronized). |
[LANGUAGE] | The programming language of the submitted code | go | Must match a supported language enum: go, java, python, javascript, typescript, rust, csharp, cpp. Unknown values cause the model to fall back to generic analysis and increase false positive rate. |
[ANTI_PATTERN_CATALOG] | The specific anti-patterns to scan for, drawn from a known catalog | double-checked-locking, busy-wait-loop, thread-per-request-unbounded, non-atomic-compound-operation | Must be a comma-separated list of anti-pattern identifiers from the supported catalog. Empty list triggers all-catalog scan but increases latency and false positive rate. Validate against allowed enum values before sending. |
[SEVERITY_THRESHOLD] | Minimum severity level to include in output | medium | Must be one of: low, medium, high, critical. Findings below this threshold are omitted from output. Use 'low' for exhaustive review, 'high' for CI gate enforcement. |
[CONTEXT] | Surrounding code or architectural notes that clarify intended concurrency design | This singleton uses lazy initialization with a sync.Once alternative expected. The system runs under high contention during startup. | Optional. Null allowed. When provided, must be plain text under 2000 tokens. Overlong context causes the model to miss anti-patterns in the diff. Truncate with a token counter before sending. |
[OUTPUT_SCHEMA] | The exact JSON schema the model must conform to in its response | {"findings": [{"anti_pattern": "string", "severity": "string", "file_path": "string", "line_start": int, "line_end": int, "explanation": "string", "refactoring_guidance": "string"}]} | Must be a valid JSON Schema object or a concise example structure. Schema check: parse the schema string as JSON before sending. Invalid schema causes unparseable output and retry loops. |
[MAX_FINDINGS] | Upper bound on the number of findings returned | 5 | Must be an integer between 1 and 20. Values above 20 risk output truncation. Use lower values for CI comments, higher values for deep review sessions. |
Implementation Harness Notes
How to wire the concurrency anti-pattern detection prompt into a CI/CD pipeline or code review workflow with validation, retries, and human approval gates.
This prompt is designed to be called programmatically as part of a pre-merge or post-commit review pipeline. The primary integration point is a CI/CD system (GitHub Actions, GitLab CI, Jenkins) that triggers on pull request creation or new commits. The application layer is responsible for extracting the code diff, assembling the prompt with the correct [CODE_DIFF], [LANGUAGE], and [ANTI_PATTERN_CATALOG] placeholders, and handling the model response. Because concurrency anti-patterns can indicate data corruption risks, the implementation must treat model output as a suggestion that requires deterministic validation before blocking a merge.
The implementation harness should follow a strict sequence: Input Assembly → Model Call → Schema Validation → Deduplication → Severity Routing → Human Review Gate. For input assembly, extract the unified diff from the PR and truncate it to fit the model's context window, prioritizing files in concurrent execution paths (e.g., files importing threading, asyncio, java.util.concurrent, or sync packages). The [ANTI_PATTERN_CATALOG] should be a curated JSON array of known patterns with names, descriptions, and regex or AST signatures where available. After the model returns JSON, validate it against a strict schema that requires anti_pattern_name, file_path, line_range, explanation, and severity fields. Reject any finding where the file_path does not exist in the diff or the line_range falls outside the changed lines—this catches hallucinated locations. Deduplicate findings that reference the same code location and anti-pattern, keeping the highest severity instance. For each validated finding, route based on severity: critical and high findings should create blocking review comments on the PR; medium findings should create non-blocking suggestions; low findings should be logged to a review dashboard without blocking the merge. All findings must include the raw model output and validation result in structured logs for auditability.
Model choice and retries: Use a model with strong code reasoning capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent) and set temperature=0 for deterministic output. Implement a retry loop with up to 2 retries if the response fails schema validation or returns empty results for a diff that contains concurrency primitives. On the second retry, append the validation error message to the prompt as additional context. If retries are exhausted, log the failure and surface a manual review request in the PR rather than silently passing. Tool use and RAG: For teams with a known anti-pattern database, pre-filter the [ANTI_PATTERN_CATALOG] to only include patterns relevant to the detected language before sending the prompt—this reduces token usage and improves precision. Do not use RAG for the code diff itself; the diff must be provided inline to avoid retrieval latency and staleness. Human review: Critical findings must require a human reviewer to acknowledge or dismiss before the PR can merge. Implement this as a required status check that only passes when a reviewer with code ownership permissions resolves the finding in the review tool.
What to avoid: Do not use this prompt as the sole gate for merge decisions without deterministic post-processing. The model may misidentify safe patterns (e.g., a correctly implemented double-checked locking pattern flagged as broken) or miss anti-patterns that require deeper inter-procedural analysis. Never send entire repository codebases in the prompt—limit input to the diff plus minimal surrounding context (e.g., 50 lines of unchanged code around each changed block). Avoid running this prompt on every commit to a feature branch; instead, trigger it on PR creation and on pushes to PRs that modify concurrency-sensitive files. Finally, do not log the raw code diff to observability systems that lack access controls—code is sensitive intellectual property and must be treated accordingly in prompt logs.
Common Failure Modes
Concurrency anti-pattern detection is brittle when the model guesses intent from static code alone. These failures show up in production as false positives that erode trust, missed bugs that slip through review, and output that reviewers ignore because it isn't actionable.
False Positives on Intentional Patterns
What to watch: The model flags correct double-checked locking, benign busy-waits with bounded retries, or thread-per-request patterns that are acceptable under known load limits. Guardrail: Require the prompt to request a confidence score and a 'likely intentional' category. Pair with a static analysis tool for ground truth on actual data races.
Missing Cross-File Synchronization
What to watch: The prompt only sees the submitted diff, missing that a lock ordering violation spans three files or that shared state is mutated in a caller the model cannot see. Guardrail: Always include relevant caller and callee context in the [CONTEXT] block. Add a 'limited visibility' caveat to the output schema when full call graphs are unavailable.
Language-Specific Primitive Confusion
What to watch: The model applies Java concurrency rules to Go goroutines, or misjudges Python GIL behavior as full thread safety. Guardrail: Explicitly set the language and concurrency model in the system prompt. Include a [LANGUAGE] variable that toggles the rule set and example anti-patterns.
Non-Actionable Output Format
What to watch: The model produces a wall of text describing a deadlock scenario without a file path, line number, or concrete fix. Reviewers dismiss the finding. Guardrail: Enforce a strict [OUTPUT_SCHEMA] requiring file_path, line_range, anti_pattern_id, and a suggested_fix code block. Validate the schema before posting the review comment.
Ignoring Framework Guarantees
What to watch: The model flags unsynchronized access in a dependency injection framework that guarantees single-threaded instantiation, or criticizes a thread pool managed by a battle-tested library. Guardrail: Provide a [FRAMEWORK_CONTEXT] block listing known guarantees. Instruct the model to suppress findings for patterns covered by documented framework contracts.
Hallucinated Fix Introduces New Bugs
What to watch: The model suggests adding a mutex that creates a lock ordering violation with an existing lock, or recommends a channel close that panics on double-close. Guardrail: Run the suggested fix through the same detection prompt recursively. Flag any fix that introduces a new anti-pattern. Require human approval for any fix that touches synchronization primitives.
Evaluation Rubric
Use this rubric to test the quality of the Concurrency Anti-Pattern Detection Prompt output before integrating it into a CI pipeline or code review harness. Each criterion maps to a specific failure mode common in concurrency analysis.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Anti-Pattern Identification | Output names a specific, recognized concurrency anti-pattern (e.g., Double-Checked Locking, Busy-Wait Loop) for each finding. | Output uses vague terms like 'concurrency issue' or 'thread problem' without naming a standard anti-pattern. | Manual review against a known anti-pattern taxonomy; automated check for presence of anti-pattern name from a predefined list. |
Location Grounding | Every finding includes a file path and line range or function name that maps directly to the submitted [CODE_DIFF]. | Findings reference code locations not present in the input diff, or omit location entirely. | Parse output for file path and line number fields; validate paths exist in the input diff using a script. |
Explanation Completeness | Each finding explains why the code matches the anti-pattern, the specific concurrent execution scenario that triggers the bug, and the potential consequence (e.g., data corruption, deadlock). | Explanation is a generic definition of the anti-pattern without connecting it to the specific code context. | LLM-as-judge evaluation: prompt a second model to check if the explanation references specific variables, control flow, or timing windows from the input code. |
Refactoring Guidance | Output provides a concrete, actionable refactoring suggestion specific to the code and language, not a generic textbook solution. | Suggestion is a one-liner like 'use a mutex' or 'fix the race condition' without adapting to the code structure. | Check that the suggestion contains language-specific primitives (e.g., |
False Positive Rate | Zero false positives on a curated dataset of 20 known-safe concurrent patterns (e.g., correctly implemented double-checked locking, proper thread pool shutdown). | Output flags a correctly synchronized code block as an anti-pattern. | Run the prompt against a golden dataset of safe concurrency patterns and assert that no findings are generated. |
Output Schema Adherence | Output is valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed. | Output is missing required fields, contains extra untyped commentary, or is not parseable JSON. | Automated JSON schema validation in the test harness; retry with repair prompt on first failure. |
Severity Classification | Each finding includes a severity level (e.g., High, Medium, Low) that correlates with the actual risk of data corruption or deadlock. | A trivial busy-wait loop is marked High severity, or a data-corrupting race condition is marked Low. | Spot-check severity against a pre-labeled severity benchmark; automated check that severity is one of the allowed enum values. |
Token Efficiency | Output contains no redundant repetition of the input code or anti-pattern definition boilerplate beyond what is needed for explanation. | Output copies large blocks of the input code verbatim or repeats the same generic anti-pattern description for every finding. | Token count comparison against expected range; manual review for excessive verbatim code reproduction. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add a strict output schema, severity scoring, and validation wrapper. Include language-specific anti-pattern catalogs and require exact file paths and line ranges. Wire the prompt into a CI pipeline with retry logic and eval gates.
codeYou are a concurrency reviewer for [LANGUAGE] code. Analyze the following diff for known concurrency anti-patterns. Anti-pattern catalog: [ANTI_PATTERN_LIST] Output JSON matching [OUTPUT_SCHEMA]. Include: - anti_pattern_name - file_path - line_range - severity (CRITICAL|HIGH|MEDIUM|LOW) - explanation - refactoring_guidance - confidence_score (0.0-1.0) If no anti-patterns found, return {"findings": []}. [CODE_DIFF]
Watch for
- Silent format drift when model returns extra fields or wrong enum values
- False positives on framework-internal patterns that look like anti-patterns
- Missing human review gate for CRITICAL severity findings before auto-blocking merge

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us