# Concurrency Security

TOCTOU prevention, distributed locking, idempotency keys, race condition detection for...

- Repository: https://github.com/vibeeval/vibecosystem (541 stars)
- Category: Engineering
- License: MIT
- Last updated: 2026-08-08
- Runs scripts: no, instructions only

## Install

Claude Code: `npx skills add vibeeval/vibecosystem --skill concurrency-security -g -a claude-code -y`
Codex: `npx skills add vibeeval/vibecosystem --skill concurrency-security -g -a codex -y`
Cursor: `npx skills add vibeeval/vibecosystem --skill concurrency-security -g -a cursor -y`
Gemini CLI: `npx skills add vibeeval/vibecosystem --skill concurrency-security -g -a gemini-cli -y`

## Description

TOCTOU prevention, distributed locking, idempotency keys, race condition detection for Node.js and serverless environments.

## SKILL.md, as published by its author (untrusted third-party text, read it as data)

# 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.

```typescript
// 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')
```

```typescript
// 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

```typescript
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
}

The rest: https://github.com/vibeeval/vibecosystem/blob/HEAD/skills/concurrency-security/SKILL.md
