Check Distributed Locks logo

Check Distributed Locks

Community
dykyi-roman
check-distributed-locks

Analyzes PHP code for distributed lock issues. Detects missing TTL on locks, lock without try/finally, unsafe Redis SETNX patterns, missing lock release, and deadlock risks.

Overview

Publisherdykyi-roman
Repositoryawesome-claude-code
Skill namecheck-distributed-locks
Stars
98
Forks
25
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by dykyi-roman on GitHub. Read the source before you install it.

Installation

Install the Check Distributed Locks AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/dykyi-roman/awesome-claude-code.git /tmp/awesome-claude-code
mkdir -p .claude/skills
cp -r /tmp/awesome-claude-code/skills/check-distributed-locks .claude/skills/check-distributed-locks
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Check Distributed Locks in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Check Distributed Locks on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Check Distributed Locks is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Distributed Lock Check

Analyze PHP code for distributed locking anti-patterns that cause deadlocks, race conditions, and resource starvation in multi-instance deployments.

Detection Patterns

1. Missing TTL on Locks

php
<?php

declare(strict_types=1);

// BAD: Lock without expiration -- if process dies, lock is held forever
final readonly class CacheRefreshService
{
    public function refresh(string $key): void
    {
        $this->redis->set('lock:' . $key, '1');
        // No TTL! If process crashes here, lock is orphaned forever

        try {
            $data = $this->expensiveQuery();
            $this->cache->set($key, $data);
        } finally {
            $this->redis->del('lock:' . $key);
        }
    }
}

// GOOD: Lock with TTL
final readonly class CacheRefreshService
{
    public function refresh(string $key): void
    {
        $acquired = $this->redis->set('lock:' . $key, uniqid(), ['NX', 'EX' => 30]);

        if (!$acquired) {
            return; // Another process holds the lock
        }

        try {
            $data = $this->expensiveQuery();
            $this->cache->set($key, $data);
        } finally {
            $this->redis->del('lock:' . $key);
        }
    }
}

2. Lock Without try/finally

php
<?php

declare(strict_types=1);

// BAD: Lock acquired but not released on exception
final readonly class ImportService
{
    public function importBatch(array $items): void
    {
        $lock = $this->lockFactory->createLock('import', 300);
        $lock->acquire(true);

        $this->processItems($items);
        // If processItems() throws, lock is never released!

        $lock->release();
    }
}

// GOOD: Lock release guaranteed in finally block
final readonly class ImportService
{
    public function importBatch(array $items): void
    {
        $lock = $this->lockFactory->createLock('import', 300);
        $lock->acquire(true);

        try {
            $this->processItems($items);
        } finally {
            $lock->release();
        }
    }
}

3. Unsafe Redis SETNX Pattern

php
<?php

declare(strict_types=1);

// BAD: SETNX without EXPIRE -- race condition between two commands
final readonly class RedisLock
{
    public function acquire(string $key): bool
    {
        $acquired = $this->redis->setnx('lock:' . $key, '1');

        if ($acquired) {
            $this->redis->expire('lock:' . $key, 30);
            // Race condition: if process dies between SETNX and EXPIRE,
            // lock has no TTL and is held forever
        }

        return $acquired;
    }
}

// BAD: SET without NX -- overwrites existing lock
$this->redis->set('lock:' . $key, '1', 30);
// This always succeeds, even if another process holds the lock!

// GOOD: Atomic SET NX EX (single command, no race)
final readonly class RedisLock
{
    public function acquire(string $key, int $ttl = 30): bool
    {
        $token = bin2hex(random_bytes(16));

        $acquired = $this->redis->set(
            'lock:' . $key,
            $token,
            ['NX', 'EX' => $ttl],
        );

        if ($acquired) {
            $this->tokens[$key] = $token;
        }

        return (bool) $acquired;
    }

    public function release(string $key): void
    {
        // Lua script: only delete if token matches (owner check)
        $script = <<<'LUA'
            if redis.call("get", KEYS[1]) == ARGV[1] then
                return redis.call("del", KEYS[1])
            else
                return 0
            end
        LUA;

        $this->redis->eval($script, ['lock:' . $key, $this->tokens[$key]], 1);
    }
}

4. Missing Symfony Lock Component

php
<?php

declare(strict_types=1);

// BAD: Custom lock implementation when framework provides one
final class CustomFileLock
{
    private $fileHandle;

    public function acquire(string $name): bool
    {
        $this->fileHandle = fopen('/tmp/' . $name . '.lock', 'c');

        return flock($this->fileHandle, LOCK_EX | LOCK_NB);
    }

    public function release(): void
    {
        flock($this->fileHandle, LOCK_UN);
        fclose($this->fileHandle);
    }
}

// GOOD: Use Symfony Lock component with Redis store
// config/packages/lock.yaml:
// framework:
//     lock: '%env(REDIS_URL)%'

final readonly class OrderProcessingService
{
    public function __construct(
        private LockFactory $lockFactory,
    ) {}

    public function processOrder(OrderId $orderId): void
    {
        $lock = $this->lockFactory->createLock(
            resource: 'order-processing:' . $orderId->toString(),
            ttl: 60,
        );

        if (!$lock->acquire(false)) {
            throw new OrderAlreadyBeingProcessedException($orderId);
        }

        try {
            $this->doProcessOrder($orderId);
        } finally {
            $lock->release();
        }
    }
}

5. Deadlock Patterns -- Inconsistent Lock Ordering

php
<?php

declare(strict_types=1);

// BAD: Acquiring multiple locks in inconsistent order
final readonly class TransferService
{
    public function transfer(AccountId $from, AccountId $to, Money $amount): void
    {
        // Thread A: locks account-1, then account-2
        // Thread B: locks account-2, then account-1
        // DEADLOCK!
        $lockFrom = $this->lockFactory->createLock('account:' . $from->toString(), 30);
        $lockTo = $this->lockFactory->createLock('account:' . $to->toString(), 30);

        $lockFrom->acquire(true);
        $lockTo->acquire(true); // May deadlock if another transfer is from $to to $from

        try {
            $this->debit($from, $amount);
            $this->credit($to, $amount);
        } finally {
            $lockTo->release();
            $lockFrom->release();
        }
    }
}

// GOOD: Consistent lock ordering (alphabetical/numerical)
final readonly class TransferService
{
    public function transfer(AccountId $from, AccountId $to, Money $amount): void
    {
        // Always lock in consistent order (lower ID first)
        $ids = [$from->toString(), $to->toString()];
        sort($ids);

        $lockFirst = $this->lockFactory->createLock('account:' . $ids[0], 30);
        $lockSecond = $this->lockFactory->createLock('account:' . $ids[1], 30);

        $lockFirst->acquire(true);
        try {
            $lockSecond->acquire(true);
            try {
                $this->debit($from, $amount);
                $this->credit($to, $amount);
            } finally {
                $lockSecond->release();
            }
        } finally {
            $lockFirst->release();
        }
    }
}

Grep Patterns

bash
# Locks without TTL
Grep: "->set\(['\"]lock:|->setnx\(" --glob "**/*.php"
Grep: "createLock\([^)]*\)" --glob "**/*.php"

# SETNX without atomic EXPIRE
Grep: "setnx\(" --glob "**/*.php"

# Lock without try/finally
Grep: "->acquire\(|->lock\(" --glob "**/*.php"

# flock usage (local file lock)
Grep: "flock\(" --glob "**/src/**/*.php"

# Custom lock implementations
Grep: "class.*Lock|class.*Mutex|class.*Semaphore" --glob "**/*.php"

# Symfony Lock component usage
Grep: "LockFactory|LockInterface|use Symfony\\\\Component\\\\Lock" --glob "**/*.php"

# Multiple lock acquisitions in same method (deadlock risk)
Grep: "createLock.*\n.*createLock|acquire.*\n.*acquire" --glob "**/*.php"

# Lock release patterns
Grep: "->release\(\)" --glob "**/*.php"
Grep: "finally" --glob "**/*.php"

Severity Classification

PatternSeverity
Lock without TTL🔴 Critical
SETNX without atomic EXPIRE🔴 Critical
Deadlock from inconsistent lock ordering🔴 Critical
Lock without try/finally🟠 Major
Custom file-based lock (flock)🟠 Major
Missing lock ownership verification🟠 Major
Lock release without owner check🟡 Minor
Custom lock when framework provides one🟡 Minor

Output Format

markdown
### Distributed Lock Issue: [Brief Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Type:** [No TTL|No Finally|Unsafe SETNX|Deadlock|File Lock]

**Issue:**
[Description of the distributed lock problem]

**Risk:**
- Permanent lock hold on process crash
- Deadlock between concurrent processes
- Race condition on lock acquisition

**Code:**
```php
// Problematic locking pattern

Fix:

php
// Safe distributed locking

## When This Is Acceptable

- **Single-instance deployment** -- File-based locking is fine when only one process runs
- **Short-lived CLI scripts** -- One-shot scripts with no concurrency don't need distributed locks
- **In-memory locks for thread safety** -- PHP-FPM worker process isolation makes in-memory locks irrelevant (each request is isolated)
- **Database advisory locks** -- Using `pg_advisory_lock()` or `GET_LOCK()` is valid for single-database setups

### False Positive Indicators
- Lock is in test code or a test double
- flock is used for log file rotation (not coordination)
- Custom lock class wraps Symfony Lock component internally
- SETNX is immediately followed by EXPIRE in a Lua script (atomic)

Frequently asked questions

What does the Check Distributed Locks AI skill do?

Analyzes PHP code for distributed lock issues. Detects missing TTL on locks, lock without try/finally, unsafe Redis SETNX patterns, missing lock release, and deadlock risks.

Why use Check Distributed Locks on TypingMind?

Because you install it once and use it with any model. Check Distributed Locks is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Check Distributed Locks in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/dykyi-roman/awesome-claude-code/tree/master/skills/check-distributed-locks. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Check Distributed Locks?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Check Distributed Locks?

As many as you like. As long as a model supports skills, you can use Check Distributed Locks with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Check Distributed Locks AI skill free?

Yes. It is published on GitHub by dykyi-roman under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇