
Concurrency Security
TOCTOU prevention, distributed locking, idempotency keys, race condition detection for...
Install
npx skills add vibeeval/vibecosystem --skill concurrency-security -g -a claude-code -y- Repository
- vibeeval/vibecosystem541
- Category
- Engineering
- Updated
- 3mo ago
- License
- MIT
- Context cost
- Mediumabout 2,584 tokens
- Runs scripts
- No, instructions only
What it does
TOCTOU prevention, distributed locking, idempotency keys, race condition detection for Node.js and serverless environments.
Concurrency Security
Patterns for preventing race conditions, double-execution, and state corruption in concurrent systems.
TOCTOU Prevention
Time-of-Check to Time-of-Use: the gap between reading state and acting on it.
// WRONG: check then act - another process can change state between lines
const balance = await db.accounts.findUnique({ where: { id } })
if (balance.amount >= amount) {
await db.accounts.update({ where: { id }, data: { amount: balance.amount - amount } })
}
// CORRECT: atomic check-and-update in a single statement
const updated = await db.$executeRaw`
UPDATE accounts
SET amount = amount - ${amount}
WHERE id = ${id} AND amount >= ${amount}
RETURNING *
`
if (updated.count === 0) throw new Error('Insufficient funds or concurrent update')
// File system TOCTOU (Node.js)
// WRONG
if (fs.existsSync(filePath)) {
fs.writeFileSync(filePath, data) // another process may have deleted it
}
// CORRECT: use O_EXCL flag for exclusive creation
import { open } from 'fs/promises'
try {
const fh = await open(filePath, 'wx') // fail if file exists
await fh.writeFile(data)
await fh.close()
} catch (err: any) {
if (err.code === 'EEXIST') { /* already exists, handle */ }
throw err
}
Distributed Locking with Redis
import Redis from 'ioredis'
const redis = new Redis(process.env.REDIS_URL!)
// Simple SETNX + TTL lock
async function acquireLock(key: string, ttlMs: number): Promise<string | null> {
const token = crypto.randomUUID()
// SET key token NX PX ttlMs, atomic, returns OK or null
const result = await redis.set(`lock:${key}`, token, 'NX', 'PX', ttlMs)
return result === 'OK' ? token : null
}
