backend-distributed-locking
Use when the user asks about a distributed lock, two workers processing the same job, Redis lock (SET NX PX), Redlock, pg_advisory_lock, leases or fencing…
от j4flmao★ 47 звёзд на GitHub
Установить backend-distributed-locking в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Backend Distributed Locking
Purpose
Coordinate access to shared resources across multiple service instances using distributed locks with guaranteed safety properties.
Agent Protocol
Trigger
Exact user phrases: "distributed lock", "Redis lock", "Redlock", "ZooKeeper lock", "advisory lock", "PostgreSQL lock", "pg_advisory_lock", "lease", "distributed mutex", "fencing token", "lock timeout".
Input Context
- Resource being protected.
- Available infrastructure (Redis, PostgreSQL, ZooKeeper, etcd).
- Number of competing instances.
- Duration of the critical section.
Output Artifact
Lock configuration or implementation code. No file unless requested.
Response Format
Provider: {Redis|PostgreSQL|ZooKeeper|etcd}
Strategy: {Redlock|Advisory|Ephemeral|Lease}
TTL: {duration}
Safety: {fencing?}
Completion Criteria
- Lock acquisition and release implemented correctly.
- Lock timeout (TTL) configured.
- Fencing token mechanism in place for critical resources.
- Deadlock prevention: no nested locks.
- Graceful degradation: lock acquisition failure does not crash the service.
Max Response Length
4 lines per lock configuration. 20 lines for implementation.
Architecture Decision Tree
Which Lock Provider?
What infrastructure is already available?
├── Redis → High throughput, short locks, needs Redlock for failover
├── PostgreSQL → Same DB as data, simple setup, lock contention impacts DB
├── ZooKeeper/etcd → Strong consistency, leader election, operational complexity
└── In-memory → Single instance only, NOT distributed
Which Lock Strategy?
Is the critical section short (< 1 second)?
├── Yes → Redis simple lock or PostgreSQL advisory lock
└── No → Is the critical section a resource write?
├── Yes → Lease-based lock with fencing token
└── No → Redlock (Redis with multi-node failover)
Is strong consistency required?
├── Yes → ZooKeeper/etcd (sequential consistency, fencing built-in)
└── No → Is failover safety required?
├── Yes → Redlock (Redis, 3+ nodes)
└── No → Single Redis lock or PG advisory lock
Do I Need a Fencing Token?
Does the lock protect a write to shared storage?
├── Yes → Does shared storage have its own concurrency control (optimistic locking)?
│ ├── Yes → Fencing token optional but recommended
│ └── No → Fencing token REQUIRED — without it, stale lock holders can corrupt data
└── No → No fencing token needed
Workflow
Step 1: Choose Lock Provider
| Provider | Best For | Trade-off |
|---|---|---|
| Redis | High throughput, short locks | Needs failover (Redlock) |
| PostgreSQL | Same DB as data | Lock contention impacts DB |
| ZooKeeper/etcd | Strong consistency | Operational complexity |
| In-memory | Single instance only | Not distributed |
Step 2: Implement Lock (Redlock)
const { Lock } = require('redlock');
const redlock = new Redlock([redis1, redis2, redis3], { driftFactor: 0.01 });
async function processResource() {
const lock = await redlock.acquire(['resource:order-123'], 5000);
try {
await updateOrderStatus('order-123', 'processing');
} finally {
await lock.release();
}
}
from redlock import Redlock
import aioredis
redis = aioredis.from_url("redis://localhost")
lock = redis.lock("resource:order-123", timeout=5000)
async with lock:
await update_order_status("order-123", "processing")
// Go — Redis lock with go-redis
import "github.com/go-redsync/redsync/v4"
import "github.com/go-redsync/redsync/v4/redis/goredis/v9"
func processOrder(ctx context.Context, orderId string) error {
mutex := rs.NewMutex("resource:order-" + orderId, redsync.WithExpiry(5*time.Second))
if err := mutex.Lock(); err != nil {
return fmt.Errorf("failed to acquire lock: %w", err)
}
defer func() {
if ok, err := mutex.Unlock(); !ok || err != nil {
log.Printf("failed to release lock: %v", err)
}
}()
return updateOrderStatus(ctx, orderId, "processing")
}
Step 3: Implement Fencing Token
Fencing tokens ensure that even if a lock is held after its timeout, stale holders cannot write.
class FencedResource {
private currentFencingToken = 0;
async executeWithFencing(resourceId: string, operation: () => Promise<void>): Promise<void> {
const fencingToken = await this.lockService.acquire(resourceId);
try {
// Pass fencing token to the resource
await this.db.query(
'UPDATE resources SET data = $1, fencing_token = $2 WHERE id = $3 AND fencing_token < $2',
[newData, fencingToken, resourceId]
);
// If ROWS_AFFECTED = 0, someone else has the lock — abort
} finally {
await this.lockService.release(resourceId);
}
}
}
-- PostgreSQL advisory lock with fencing
SELECT pg_advisory_xact_lock(12345);
UPDATE
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/distributed-locking-advanced.md
- references/distributed-locking-fundamentals.md
- references/fencing-tokens-deep.md
- references/lock-contention-analysis.md
- references/lock-deep-dive.md
- references/lock-implementations.md
- references/lock-providers.md
- references/lock-strategies.md
- references/lock-testing.md
FAQ
Что делает скилл backend-distributed-locking?
Use when the user asks about a distributed lock, two workers processing the same job, Redis lock (SET NX PX), Redlock, pg_advisory_lock, leases or fencing tokens. Produces a lock design with TTLs, fencing and failure handling. Not for job deduplication via idempotency keys (use backend-idempotency).
Как установить скилл backend-distributed-locking?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл backend-distributed-locking запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
AnthropicGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
webapp-testing
AnthropicToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
brand-guidelines
AnthropicApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
web-artifacts-builder
AnthropicSuite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…