Skip to content
Development
Skill

/concurrency-security

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

From plugin
vibecosystem
534200 skills138 agents7 hooks
Install
$ npx -y skills add vibeeval/vibecosystem --skill concurrency-security --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/concurrency-security

Context preview

The summary Claude sees to decide when to auto-load this skill.

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

SKILL.md

concurrency-security.SKILL.md
name: concurrency-security
description: 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
}

async function releaseLock(key: string, token: string): Promise<void> {
  // Lua script: only delete if we own the lock (atomic compare-and-delete)
  const script = `
    if redis.call("GET", KEYS[1]) == ARGV[1] then
      return redis.call("DEL", KEYS[1])
    else
      return 0
    end
  `
  await redis.eval(script, 1, `lock:${key}`, token)
}

// Usage
async function processPayment(paymentId: string) {
  const token = await acquireLock(paymentId, 30_000)  // 30s TTL
  if (!token) throw new Error('Payment already being processed')

  try {
    await doPaymentWork(paymentId)
  } finally {
    await releaseLock(paymentId, token)
  }
}

Redlock Algorithm (multi-node)

import Redlock from 'redlock'
import Redis from 'ioredis'

// Connect to 3+ independent Redis nodes for Redlock quorum
const clients = [
  new Redis('redis://redis1:6379'),
  new Redis('redis://redis2:6379'),
  new Redis('redis://redis3:6379'),
]

const redlock = new Redlock(clients, {
  retryCount: 3,
  retryDelay: 200,
  retryJitter: 100,
})

async function criticalSection(resourceId: string) {
  await redlock.using([`resource:${resourceId}`], 10_000, async (signal) => {
    if (signal.aborted) throw signal.error

    await performAtomicOperation(resourceId)

    if (signal.aborted) throw signal.error  // check after long operations
  })
}

PostgreSQL Advisory Locks

import { Pool } from 'pg'
const pool = new Pool()

// Session-level advisory lock (held until released or connection closes)
async function withAdvisoryLock<T>(lockId: number, fn: () => Promise<T>): Promise<T> {
  const client = await pool.connect()
  try {
    await client.query('SELECT pg_advisory_lock($1)', [lockId])
    return await fn()
  } finally {
    await client.query('SELECT pg_advisory_unlock($1)', [lockId])
    client.release()
  }
}

// Non-blocking try variant — returns false if lock is already held
async function tryAdvisoryLock(lockId: number): Promise<boolean> {
  const client = await pool.connect()
  try {
    const { rows } = await client.query('SELECT pg_try_advisory_lock($1) AS acquired', [lockId])
    return rows[0].acquired
  } finally {
    client.release()
  }
}

// Usage
const PAYMENT_PROCESSOR_LOCK = 12345  // stable integer per operation type
await withAdvisoryLock(PAYMENT_PROCESSOR_LOCK, async () => {
  await processQueue()
})

Idempotency Key Implementation

// Middleware: extract idempotency key from header and dedup in DB
import { Request, Response, NextFunction } from 'express'
import { db } from './db'

export async function idempotencyMiddleware(req: Request, res: Response, next: NextFunction) {
  const idempotencyKey = req.headers['idempotency-key'] as string | undefined

  if (!idempotencyKey || req.method === 'GET') return next()

  // Look up existing result
  const existing = await db.idempotencyKeys.findUnique({
    where: { key: idempotencyKey },
  })

  if (existing) {
    // Return cached response — same status and body
    return res.status(existing.statusCode).json(existing.responseBody)
  }

  // Capture response to store it
  const originalJson = res.json.bind(res)
  res.json = (body: unknown) => {
    // Store before sending
    db.idempotencyKeys.create({
      data: {
        key: idempotencyKey,
        statusCode: res.statusCode,
        responseBody: body,
        expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),  // 24h TTL
      },
    }).catch(console.error)

    return originalJson(body)
  }

  next()
}
-- DB schema for idempotency keys
CREATE TABLE idempotency_keys (
  key         TEXT PRIMARY KEY,
  status_code INT NOT NULL,
  response_body JSONB NOT NULL,
  created_at  TIMESTAMPTZ DEFAULT NOW(),
  expires_at  TIMESTAMPTZ NOT NULL
);

CREATE INDEX ON idempotency_keys (expires_at);
-- Clean up expired keys via pg_cron or a scheduled job

Atomic Database Operations

// SELECT FOR UPDATE: pessimistic lock on row
async function debitAccount(accountId: string, amount: number) {
  await db.$transaction(async (tx) => {
    const account = await tx.$queryR
Read more
Ships withvibecosystem

Your AI software team. Built on Claude Code. vibecosystem turns Claude Code into a full AI software team — 138 specialized agents that plan, build, review, test, and learn from every mistake. No configuration needed — just install and code.

Get the whole plugin

Other skills on vibecosystem.