This prompt is designed for backend and systems engineers who need to review multi-threaded code for concurrency defects before they reach production. It analyzes a code diff and produces a severity-ranked list of findings covering race conditions, deadlock risks, thread-safety violations, and improper synchronization patterns. Use this prompt in CI/CD pipelines, pre-merge review gates, or as part of a structured code review checklist. The prompt works best when the diff contains the full context of shared state access, lock acquisition, and thread coordination logic. It is not a replacement for dynamic analysis tools, stress testing, or formal verification.
Prompt
Concurrency Anti-Pattern Detection Prompt

When to Use This Prompt
Understand the ideal context, required inputs, and limitations of the Concurrency Anti-Pattern Detection Prompt before integrating it into your review pipeline.
The ideal input is a focused code diff where concurrency concerns are present—think changes to thread pools, shared caches, lock management, or async coordination. The prompt requires the full diff context, not just isolated lines, because concurrency bugs often span multiple files or involve implicit contracts between components. You should also provide any relevant [CONSTRAINTS], such as the language runtime's memory model guarantees or team-specific synchronization conventions. The output is a structured finding list with severity ratings, file and line references, and fix suggestions, making it directly actionable for developers.
Do not use this prompt for single-threaded code, purely algorithmic changes with no shared state, or diffs where the concurrency model is entirely external (e.g., database-managed transactions with no application-level threading). It will produce false positives on intentional lock-free patterns, well-documented benign data races in performance-critical code, and framework-managed synchronization that the prompt cannot see. Always pair this prompt with a human review step for findings marked as high severity, and consider running it alongside dynamic race detectors like ThreadSanitizer for confirmation. The prompt is a static analysis aid, not a runtime safety guarantee.
Use Case Fit
Where the Concurrency Anti-Pattern Detection Prompt delivers value and where it introduces risk.
Good Fit: Multi-threaded Diff Review
Use when: reviewing pull requests that touch shared state, locks, channels, or transaction boundaries in languages like Java, Go, Rust, or C++. Guardrail: The prompt works best on focused diffs; large, unrelated changes dilute its effectiveness.
Bad Fit: High-Level Architecture Review
Avoid when: evaluating system-wide concurrency models, distributed consensus protocols, or eventual consistency designs. Guardrail: This prompt targets code-level anti-patterns, not architectural trade-offs. Use the Architectural Anti-Pattern Detection Prompt for design-level concerns.
Required Inputs
What you need: A well-formed code diff with file paths and line numbers, plus the language/framework context. Guardrail: Without line-level diff granularity, the model cannot produce actionable, severity-ranked findings that a developer can map back to their editor.
Operational Risk: False Negatives on Novel Patterns
What to watch: The model may miss concurrency bugs that don't match well-known anti-pattern templates, especially in domain-specific or framework-specific synchronization primitives. Guardrail: Never use this as the sole gate for concurrency safety. Pair with deterministic race detectors and stress tests.
Operational Risk: Over-Flagging Intentional Patterns
What to watch: Performance-critical code often uses intentional lock-free structures or double-checked locking that the model may flag as anti-patterns. Guardrail: Require human review for all findings before blocking a merge. The prompt should explain the risk, not dictate the fix.
Variant: Transaction Boundary Focus
What to watch: Database transaction boundaries and isolation levels are a subset of concurrency risk that the general prompt may under-prioritize. Guardrail: For data-intensive diffs, combine this prompt with the Database Access Anti-Pattern Detection Prompt to catch N+1 and transaction scope issues together.
Copy-Ready Prompt Template
A reusable prompt template for detecting concurrency anti-patterns in code diffs, with placeholders for input, context, and output constraints.
This prompt template is designed to be pasted directly into your AI system, whether that's an LLM API call, a CI/CD pipeline integration, or a code review assistant. It expects a code diff as input and produces a structured, severity-ranked list of concurrency anti-pattern findings. Replace each square-bracket placeholder with the actual values for your review context before execution. The template includes placeholders for the code diff, language-specific concurrency primitives, project-specific risk tolerances, and the desired output schema.
textYou are a senior systems engineer specializing in concurrent and parallel programming. Your task is to analyze the provided code diff for concurrency anti-patterns, race conditions, deadlock risks, thread-safety violations, and improper synchronization. ## INPUT [CODE_DIFF] ## CONTEXT - Language and runtime: [LANGUAGE_AND_RUNTIME] - Concurrency model in use: [CONCURRENCY_MODEL, e.g., async/await, threads with locks, actors, channels, STM] - Shared state boundaries: [SHARED_STATE_DESCRIPTION, e.g., in-memory cache, database connection pool, file system] - Project risk tolerance: [RISK_LEVEL, e.g., low (data integrity critical), medium, high (best-effort)] ## CONSTRAINTS - Only report findings that are present in the diff. Do not speculate about code outside the diff unless a diff change creates a new interaction risk with existing code. - For each finding, cite the specific file path and line range from the diff. - If no concurrency issues are found, return an empty findings list with a brief justification. - Do not suggest full rewrites. Suggest minimal, safe fixes. - Flag any finding that could lead to data corruption or silent failure as CRITICAL severity. ## OUTPUT_SCHEMA Return a single JSON object with the following structure: { "summary": "string (one-sentence assessment of the diff's concurrency safety)", "findings": [ { "id": "string (unique finding identifier, e.g., CONC-001)", "severity": "CRITICAL | HIGH | MEDIUM | LOW", "category": "RACE_CONDITION | DEADLOCK | THREAD_SAFETY | IMPROPER_SYNCHRONIZATION | ATOMICITY_VIOLATION | ORDERING_VIOLATION | RESOURCE_LEAK | OTHER", "file": "string (file path from diff)", "line_range": "string (e.g., L45-L52)", "description": "string (clear explanation of the anti-pattern and why it is a problem in this context)", "reproduction_risk": "string (likelihood of hitting this bug in production: HIGH, MEDIUM, LOW)", "suggested_fix": "string (concrete, minimal code change suggestion)", "requires_human_review": true } ], "no_findings_justification": "string (only present if findings list is empty)" } ## EXAMPLES ### Example Finding (CRITICAL) { "id": "CONC-001", "severity": "CRITICAL", "category": "RACE_CONDITION", "file": "src/cache/user_session_cache.go", "line_range": "L42-L48", "description": "The diff introduces a check-then-act pattern on the session map without holding a lock. Between the existence check on L42 and the write on L48, another goroutine could insert a session, leading to a silent overwrite and session corruption.", "reproduction_risk": "MEDIUM", "suggested_fix": "Acquire the cache mutex before the existence check and release it after the write. Use `cache.mu.Lock()` at L41 and `cache.mu.Unlock()` at L49.", "requires_human_review": true } ### Example Finding (MEDIUM) { "id": "CONC-002", "severity": "MEDIUM", "category": "IMPROPER_SYNCHRONIZATION", "file": "src/worker/task_processor.py", "line_range": "L88-L95", "description": "The diff adds a shared `self.results` list that is appended to from multiple `asyncio.create_task` calls without any lock or queue. While CPython's GIL protects individual list operations, the order of results is non-deterministic and the size check on L95 may race with pending appends.", "reproduction_risk": "HIGH", "suggested_fix": "Replace the list with an `asyncio.Queue` and have workers `put` results. The collector should `get` with a timeout or use `task_done` tracking.", "requires_human_review": false }
To adapt this template, start by replacing [CODE_DIFF] with the actual unified diff output from your version control system. The [LANGUAGE_AND_RUNTIME] and [CONCURRENCY_MODEL] fields are critical for accurate detection—a race condition in Go's goroutine model looks different from one in Python's asyncio or Java's thread pools. If your project has a known set of shared state boundaries (e.g., a specific cache instance, a database connection pool), describe them in [SHARED_STATE_DESCRIPTION] to help the model reason about interaction risks. Set [RISK_LEVEL] based on your domain: financial systems and databases should use "low" tolerance to catch more potential issues, while best-effort batch processors can use "high" to reduce noise. After generating findings, always run your eval suite against known concurrency bug patterns to measure false negative rates before trusting this prompt in a merge gate.
Prompt Variables
Required inputs for the Concurrency Anti-Pattern Detection Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Missing or malformed inputs are the most common cause of false negatives in production.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CODE_DIFF] | The unified diff or code snippet to analyze for concurrency anti-patterns | diff --git a/src/worker.go b/src/worker.go @@ -12,7 +12,8 @@
| Must be non-empty. Validate that the diff contains at least one function body or method definition. Reject if only import changes or comment edits are present. |
[LANGUAGE] | The programming language of the code under review, used to select language-specific concurrency primitives and patterns | go | Must match a supported language identifier: go, java, kotlin, rust, python, csharp, cpp, javascript, typescript. Reject unsupported languages and return an explicit unsupported-language error before calling the model. |
[CONCURRENCY_MODEL] | The concurrency model used in the codebase to narrow detection rules | goroutines with channels | Must be one of: goroutines-with-channels, async-await, threads-and-locks, actor-model, reactive-streams, null. Use null when the model should infer from code patterns. Validate against [LANGUAGE] compatibility. |
[SEVERITY_THRESHOLD] | Minimum severity level to include in the output; findings below this threshold are dropped | medium | Must be one of: low, medium, high, critical. Default to medium if not specified. Validate enum membership before prompt assembly. Findings at or above this threshold are included. |
[MAX_FINDINGS] | Maximum number of findings to return, preventing output bloat on large diffs | 10 | Must be an integer between 1 and 25. Default to 10 if not specified. Validate range before prompt assembly. If the diff contains more findings than [MAX_FINDINGS], the model should return the top-N by severity. |
[KNOWN_SAFE_PATTERNS] | A list of patterns the team has already reviewed and accepted, to suppress false positives | ["sync.WaitGroup used with defer wg.Done()", "@GuardedBy annotation present"] | Must be a JSON array of strings, or null. Each entry should describe a specific code pattern. Validate JSON parse before prompt assembly. The model should not flag code matching these patterns. |
[OUTPUT_SCHEMA] | The exact JSON schema the model must conform to in its response | {"type": "object", "properties": {"findings": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "severity": {"type": "string", "enum": ["low", "medium", "high", "critical"]}, "file": {"type": "string"}, "line_range": {"type": "string"}, "anti_pattern": {"type": "string"}, "description": {"type": "string"}, "remediation": {"type": "string"}}, "required": ["id", "severity", "file", "line_range", "anti_pattern", "description", "remediation"]}}}, "required": ["findings"]} | Must be a valid JSON Schema object. Validate JSON parse and schema structure before prompt assembly. The model output must pass JSON Schema validation against this schema. If validation fails, trigger the output repair retry loop. |
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 escalation.
Integrating this prompt into an application requires treating it as a deterministic analysis step within a broader review pipeline, not a standalone chatbot. The prompt expects a structured code diff as its primary input and returns a severity-ranked list of findings. The harness must therefore handle pre-processing (diff extraction, file filtering, context window packing), post-processing (output validation, schema enforcement, deduplication), and routing (automated merge gates for low-severity findings, human review queues for critical or high-risk detections). Because concurrency bugs are notoriously difficult to reproduce and can cause data corruption, the implementation must bias toward false positives over false negatives—it is safer to flag a benign pattern for human review than to miss a deadlock risk.
Start by constructing the model request inside a function that accepts a git diff string and a risk threshold configuration. Use a model with strong code reasoning capabilities and a context window large enough to hold the full diff plus the system prompt. Set temperature=0 to maximize output determinism. The prompt returns JSON, so configure the model's response format for strict JSON mode if the provider supports it. After receiving the response, validate the output against a JSON schema that enforces the expected structure: a top-level array of finding objects, each with required fields for severity (enum: CRITICAL, HIGH, MEDIUM, LOW), file_path, line_range, anti_pattern, description, and remediation. Reject malformed responses and retry up to two times with an explicit error message appended to the prompt, such as "Your previous response failed JSON schema validation. Ensure all required fields are present and severity is one of the allowed values." If retries are exhausted, log the failure and escalate the entire diff for human review.
For production CI/CD integration, wrap the detection call in a pipeline stage that runs after linting and before merge eligibility checks. Cache the model response keyed on the diff hash to avoid re-analyzing unchanged code. Route findings by severity: CRITICAL and HIGH findings should block the merge and create a review task with the full finding context; MEDIUM findings should generate a non-blocking comment on the pull request; LOW findings can be logged for trend analysis without interrupting the developer workflow. Implement an eval harness that runs the prompt against a golden dataset of known concurrency bugs—including race conditions, deadlocks, improper synchronization, and thread-safety violations—and measures recall (did it catch the known bug?) and precision (did it flag benign code?). Track false negative rates on critical patterns as a key health metric. Finally, provide a feedback mechanism so reviewers can mark findings as false positives or confirm them, feeding that signal back into prompt refinement and eval dataset expansion.
Expected Output Contract
Defines the exact fields, types, and validation rules for the structured finding list returned by the Concurrency Anti-Pattern Detection Prompt. Use this contract to build a parser, validator, and retry handler before integrating the prompt into a CI pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
findings | Array of objects | Must be a non-null array. If no issues are found, return an empty array. Reject if the root is not an array. | |
findings[].id | String (kebab-case) | Must match pattern ^[a-z]+(-[a-z]+)*$. Must be unique within the findings array. Reject duplicates. | |
findings[].severity | Enum: CRITICAL, HIGH, MEDIUM, LOW | Must be one of the four defined enum values. Reject any other string or null. | |
findings[].file_path | String (relative path) | Must be a non-empty string. Should match the relative path format from the provided [DIFF]. Reject empty strings. | |
findings[].line_range | Object with 'start' and 'end' integers | Both 'start' and 'end' must be positive integers with 'start' <= 'end'. Reject if 'start' > 'end' or if values are negative. | |
findings[].anti_pattern | String | Must be a concise, non-empty string identifying the specific concurrency bug type (e.g., 'Race Condition', 'Deadlock Risk'). Reject empty strings. | |
findings[].description | String | Must be a non-empty string explaining the finding in the context of the provided [DIFF]. Reject if it is a generic definition without code context. | |
findings[].fix_suggestion | String | Must be a non-empty string providing a concrete, actionable fix. Reject if it is a vague statement like 'Fix the race condition' without a specific mechanism. |
Common Failure Modes
Concurrency bugs are notoriously difficult to reproduce and can survive code review. These failure modes target the most common ways a concurrency anti-pattern detection prompt produces false confidence, misses critical issues, or generates unactionable noise.
False Negatives on Known Bug Patterns
Risk: The model misses a well-known concurrency bug (e.g., double-checked locking, check-then-act race) because the diff lacks explicit synchronization keywords. Guardrail: Maintain a golden dataset of 10-15 canonical concurrency bugs in your language and run it as a regression suite before deploying any prompt update.
Over-Flagging Framework-Managed Concurrency
Risk: The prompt flags every shared variable access in an async framework (e.g., Node.js event loop, Python asyncio) as a race condition, generating noise that causes developers to ignore real findings. Guardrail: Include explicit framework context in the prompt and use a post-processing deduplication step that suppresses findings for single-threaded event-loop patterns.
Severity Inflation Without Execution Context
Risk: The model assigns 'Critical' severity to a theoretical race in a low-throughput background logger, while missing a 'High' severity deadlock in a payment processing path. Guardrail: Require the prompt to cross-reference the code path's operational criticality (e.g., request path vs. startup hook) before assigning severity, and add a human review step for any 'Critical' finding.
Hallucinated Synchronization Primitives
Risk: The model invents a non-existent lock class or API method when suggesting a fix, leading a junior developer to implement a broken solution. Guardrail: Constrain the prompt to only suggest synchronization primitives from the language's standard library or explicitly provided project dependencies, and validate all suggested API names against a known list.
Ignoring Transaction Boundaries in Database Code
Risk: The prompt focuses on in-memory locks and misses isolation-level violations or missing transaction boundaries that cause write skew or lost updates. Guardrail: Include a dedicated instruction block for database access patterns that checks for transaction scope, isolation levels, and SELECT FOR UPDATE usage before generating the final finding list.
Context Window Truncation on Large Diffs
Risk: A large diff with multiple files causes the model to lose context on the calling code, missing a deadlock because it only sees the lock acquisition in one file. Guardrail: Chunk the diff by logical unit (e.g., per class or per transaction boundary) and run the prompt on each chunk independently, then merge findings with a deduplication pass.
Evaluation Rubric
Use this rubric to test the Concurrency Anti-Pattern Detection Prompt against known concurrency bug patterns before shipping. Each criterion targets a specific failure mode observed in production code review workflows.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Race Condition Detection | Prompt identifies unsynchronized access to shared mutable state across threads, citing specific lines and the shared variable | Prompt misses a known race condition in the test fixture or flags thread-safe code as racy | Run against a golden diff containing a classic check-then-act race on a non-volatile field; verify finding includes the variable name and line range |
Deadlock Risk Identification | Prompt detects circular lock acquisition order across two or more locks and explains the deadlock scenario | Prompt fails to flag nested synchronized blocks with different lock orders or flags sequential lock acquisition as deadlock risk | Run against a golden diff with lock ordering inversion (lock A then B in one method, B then A in another); verify finding describes the cycle |
Thread-Safety Violation Classification | Prompt correctly classifies findings as thread-unsafe, conditionally safe, or safe with documented assumptions | Prompt labels a thread-safe concurrent collection usage as unsafe or misses a non-thread-safe collection shared across threads | Run against a mixed diff containing ConcurrentHashMap (safe), unsynchronized ArrayList (unsafe), and a volatile field (conditionally safe); verify all three classifications are correct |
Synchronization Gap Detection | Prompt identifies missing synchronization on compound actions (e.g., get-then-put) even when individual operations are atomic | Prompt treats individually atomic operations as sufficient for compound correctness | Run against a golden diff with a ConcurrentHashMap.get() followed by .put() without external synchronization; verify finding notes the compound action gap |
False Positive Rate on Intentional Patterns | Prompt produces zero findings on a diff containing correctly implemented double-checked locking, copy-on-write, or thread-confined objects | Prompt flags a correctly implemented double-checked locking pattern with volatile as a race condition | Run against a clean diff with standard concurrency patterns from java.util.concurrent documentation; verify zero findings or findings marked as informational only |
Severity Ranking Consistency | Prompt assigns Critical to deadlock and data corruption risks, High to race conditions, Medium to style issues, Low to informational notes | Prompt assigns Medium to a deadlock risk or Critical to a missing @ThreadSafe annotation | Run against a diff with one deadlock, one race condition, and one style issue; verify severity ordering matches Critical > High > Medium > Low |
Explanation Groundedness | Prompt's explanation for each finding references specific code constructs (lock objects, shared variables, thread boundaries) from the diff | Prompt produces generic explanations like 'this code may have concurrency issues' without citing specific lines or variables | Run against a known race condition diff; verify explanation contains at least one variable name and one line reference from the diff |
Output Schema Compliance | Prompt output is valid JSON matching the expected schema with all required fields present and correctly typed | Output is missing required fields, contains extra untyped fields, or is not parseable JSON | Validate output against the [OUTPUT_SCHEMA] using a JSON schema validator; verify all required fields present and no additional properties |
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 JSON output schema with required fields: finding_id, severity, pattern_type, file_path, line_range, description, remediation, and confidence. Include a [CONSTRAINTS] block requiring evidence from the diff for each finding. Add retry logic on schema validation failure.
code[OUTPUT_SCHEMA] { "findings": [ { "finding_id": "string", "severity": "critical|high|medium|low", "pattern_type": "string", "file_path": "string", "line_range": "string", "description": "string", "remediation": "string", "confidence": 0.0-1.0 } ] } [CONSTRAINTS] - Every finding must cite a specific line range from the diff. - Do not flag patterns protected by documented framework guarantees. - If no concurrency anti-patterns are found, return an empty findings array.
Watch for
- Silent format drift when the model omits optional fields
- Missing human review gate for critical-severity findings
- Confidence scores that don't correlate with actual bug presence

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