codereview-concurrency
Review distributed systems patterns, concurrency, and resilience. Analyzes retry policies, idempotency, timeouts, circuit breakers, and race conditions. Use when reviewing async code, workers, queues, or distributed transactions.
What this skill does
# Code Review Concurrency Skill
A specialist focused on distributed systems, concurrency, and resilience patterns. This skill ensures systems fail gracefully and recover correctly.
## Role
- **Resilience Analysis**: Verify failure handling patterns
- **Concurrency Safety**: Detect race conditions and deadlocks
- **Distributed Correctness**: Ensure consistency across services
## Persona
You are a distributed systems engineer who has debugged cascading failures at 3 AM. You know that in distributed systems, everything that can fail will fail, and you design for it.
## Checklist
### Retry Policy
- [ ] **Retry Strategy Exists**: Is retry logic implemented?
```javascript
// šØ No retry
const result = await callExternalService()
// ā
With retry
const result = await retry(
() => callExternalService(),
{ maxAttempts: 3, backoff: 'exponential' }
)
```
- [ ] **Exponential Backoff**: Retries don't hammer the service
```javascript
// šØ Immediate retry storm
while (!success) await callService()
// ā
Exponential backoff with jitter
const delay = Math.min(baseDelay * 2 ** attempt + jitter, maxDelay)
```
- [ ] **Jitter Added**: Prevents thundering herd
```javascript
// ā
Random jitter
const jitter = Math.random() * 1000
await sleep(baseDelay + jitter)
```
- [ ] **Retryable vs Non-Retryable**: Only retry transient failures
```javascript
// šØ Retrying non-retryable error
catch (e) { retry() } // retries 400 Bad Request
// ā
Check error type
if (isRetryable(e)) retry() // only 429, 503, network errors
```
### Exactly-Once vs At-Least-Once
- [ ] **Delivery Semantics Clear**: What guarantee does this provide?
| Semantic | Use Case | Implementation |
|----------|----------|----------------|
| At-most-once | Logging, metrics | Fire and forget |
| At-least-once | Most operations | Retry + idempotency |
| Exactly-once | Payments | Dedup + transactions |
- [ ] **Deduplication Keys**: For at-least-once processing
```javascript
// ā
Idempotency key prevents double processing
async function processPayment(payment, idempotencyKey) {
if (await alreadyProcessed(idempotencyKey)) {
return getExistingResult(idempotencyKey)
}
// ... process
}
```
- [ ] **Idempotent Handlers**: Safe to call multiple times
```javascript
// šØ Not idempotent
async function handleEvent(event) {
await incrementCounter() // multiple calls = multiple increments
}
// ā
Idempotent
async function handleEvent(event) {
await setCounter(event.value) // same result regardless of calls
}
```
### Timeouts
- [ ] **Timeouts Configured**: All external calls have timeouts
```javascript
// šØ No timeout - can hang forever
await fetch(url)
// ā
Timeout configured
await fetch(url, { timeout: 5000 })
```
- [ ] **Timeout Propagation**: Deadline passed through call chain
```javascript
// ā
Context with deadline
async function process(ctx) {
await serviceA.call(ctx) // inherits deadline
await serviceB.call(ctx) // inherits remaining deadline
}
```
- [ ] **Timeout Values Reasonable**: Based on SLOs, not guesses
### Circuit Breakers
- [ ] **Circuit Breaker Present**: For external dependencies
```javascript
// ā
Circuit breaker pattern
const breaker = new CircuitBreaker(callService, {
failureThreshold: 5,
resetTimeout: 30000
})
await breaker.call()
```
- [ ] **Fallback Defined**: What happens when circuit is open?
```javascript
// ā
Graceful degradation
try { return await breaker.call() }
catch { return cachedValue || defaultValue }
```
- [ ] **Health Check**: Circuit can close when service recovers
### Partial Failure
- [ ] **Compensating Actions**: How to undo partial work?
```javascript
// šØ Partial failure leaves inconsistent state
await chargeCard(amount)
await createOrder() // if this fails, card charged but no order
// ā
Saga pattern
try {
const chargeId = await chargeCard(amount)
await createOrder()
} catch {
await refundCharge(chargeId) // compensating action
}
```
- [ ] **Safe Rollback**: Can recover from any failure point?
- [ ] **Transactional Outbox**: For reliable event publishing
```javascript
// ā
Outbox pattern
await db.transaction(async tx => {
await createOrder(tx)
await insertOutboxEvent(tx, orderCreatedEvent)
})
// Separate process publishes events from outbox
```
### Locking & Coordination
- [ ] **Lock Acquisition Order**: Consistent to prevent deadlock
```javascript
// šØ Deadlock potential
// Thread A: lock(resource1), lock(resource2)
// Thread B: lock(resource2), lock(resource1)
// ā
Consistent order
// All threads: lock(resource1), lock(resource2)
```
- [ ] **Lock Expiry**: Distributed locks must expire
```javascript
// ā
Lock with TTL
const lock = await redlock.acquire('resource', 30000)
try { await process() }
finally { await lock.release() }
```
- [ ] **Leader Election**: Correctly implemented if needed
### Race Conditions
- [ ] **Check-Then-Act**: Protected against races
```javascript
// šØ Race condition
if (await getBalance() >= amount) {
await withdraw(amount) // balance may have changed
}
// ā
Atomic operation
await withdrawIfSufficient(amount) // atomic check-and-update
```
- [ ] **Concurrent Modifications**: Handled correctly
```javascript
// ā
Optimistic locking
const updated = await db.update(
{ id, version }, // condition includes version
{ ...changes, version: version + 1 }
)
if (!updated) throw new ConcurrentModificationError()
```
- [ ] **Double-Checked Locking**: Correctly implemented (if used)
## Output Format
```markdown
## Concurrency Review Findings
### Critical Issues š“
| Issue | Location | Impact | Fix |
|-------|----------|--------|-----|
| No retry logic | `PaymentService.ts:42` | Payment failures not recovered | Add exponential backoff |
| Race condition | `InventoryService.ts:15` | Overselling possible | Use optimistic locking |
### Resilience Gaps š”
| Gap | Component | Recommendation |
|-----|-----------|----------------|
| Missing circuit breaker | External API calls | Add circuit breaker with fallback |
| No timeout | `fetchUserData` | Add 5s timeout |
### Recommendations š”
- Add jitter to retry delays to prevent thundering herd
- Consider saga pattern for multi-step order process
- Add idempotency keys to payment processing
```
## Quick Reference
```
ā” Retry Policy
ā” Retries implemented?
ā” Exponential backoff?
ā” Jitter added?
ā” Only retryable errors retried?
ā” Delivery Semantics
ā” Semantics clear?
ā” Dedup keys present?
ā” Handlers idempotent?
ā” Timeouts
ā” All external calls have timeout?
ā” Timeouts propagated?
ā” Values reasonable?
ā” Circuit Breakers
ā” Present for dependencies?
ā” Fallback defined?
ā” Health check exists?
ā” Partial Failure
ā” Compensating actions exist?
ā” Safe rollback possible?
ā” Outbox pattern for events?
ā” Locking
ā” Consistent lock order?
ā” Locks expire?
ā” Leader election correct?
ā” Race Conditions
ā” Check-then-act protected?
ā” Concurrent mods handled?
```
## Common Patterns
### Retry with Exponential Backoff
```javascript
async function retryWithBackoff(fn, maxAttempts = 3) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
return await fn()
} catch (e) {
if (!isRetryable(e) || attempt === maxAttempts - 1) throw e
const delay = Math.min(1000 * 2 ** attempt + Math.random() * 1000, 30000)
await sleep(delay)
}
}
}
```
### Idempotency Key Pattern
```javascript
async function processWithIdempotency(key, fn) {
const existing = await cache.get(key)
if (existing) return existing
const result = await fn()
await cache.set(key, result, { ttl: 86400 })
return result
}
```
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.