anotherben/claude-harness/sync-worker
Claude Code and agent skill by anotherben/claude-harness
- community
Checking that the SKILL.md file is still in the repository.
Queue and sync worker pattern guide for background job processing. Use this skill before writing or modifying any queue worker, sync job, retry logic, batch processor, checkpoint system, or background task. Covers atomic queue claims (FOR UPDATE SKIP LOCKED), exponential backoff strategies, binary-split batch retry, stale lock recovery, checkpoint persistence, dead letter escalation, adaptive rate limiting, quota tracking, echo detection, and dedup patterns. Invoke this for any code that touches rex_sync_queue, email_queue, background sync jobs, or scheduled tasks — even "simple queue operations" have concurrency traps.
Install
npx vskill@latest install anotherben/claude-harness/sync-workerSKILL.md
The same SKILL.md was published earlier as anotherben/claude-harness/sync-worker.
Sync Worker Patterns
This codebase has a multi-layer queue architecture spanning REX sync, Shopify inventory push, email drafts, and scheduled jobs. Every queue worker shares common patterns for claims, retries, and failure handling. Getting these wrong causes duplicate processing, lost updates, stale locks, and retry storms.
TOP GOTCHAS (read these FIRST)
- Checkpoint staleness guard — If a background sync crashes and restarts, the stale checkpoint fetches entire history → exhausts API quota → checkpoint never advances → death spiral. MUST cap lookback to 4 hours max (
MAX_STALENESS_MS). SeerexBackgroundSync.js. - "Overpaid" means success — REX returns error messages like "overpaid", "Balance: 0", "NullReferenceException GetOutletId" when an operation already succeeded. Retrying these causes retry storms. Always check `isAlreadyPaidError()` in
rexSyncQueueWorker.js. - Echo detection on inventory push — Cortex pushes to Shopify → Shopify fires
inventory_levels/updatewebhook back → infinite loop. MUST log pushes to `shopify_inventory_push_log` and check 90-second window on webhook receipt. Circuit breaker: 5 reverts in 10 min stops pushing. - syncInProgress MUST use try/finally — Missing
finallyblock means a crash leavessyncInProgress = truepermanently, blocking all future syncs. - Quota isolation — Use
REX_API_KEY_SYNCfor sync,REX_API_KEY_WEBHOOKfor webhooks. Same key = webhook traffic eats sync quota.
Before Writing Queue/Sync Code
- Explore the existing worker for the queue type you're modifying — patterns are established:
get_file_outline([worker-file])to see all functions without reading 375-911 line filesget_symbol([worker-file], [function-name])to pull the specific pattern you need- Use
search_symbols(query="[pattern]", kind="function")to find where a pattern lives - Only use Read for full-file context or before editing
- Check which queue table your operation uses (see Queue Table Map below)
- Verify the claim pattern uses
FOR UPDATE SKIP LOCKED— any other approach has race conditions
Queue Table Map
| Table | Worker File | Poll Interval | Batch Size | Use For | |
|---|---|---|---|---|---|
rex_sync_queue | rexSyncQueueWorker.js (551 lines) | 60s | 10 | Payment, refund, cancel, order_create, fulfillment, inventory push, reconciliation | |
rex_sync_retry_queue | rexSyncRetry.js (375 lines) | 60s | varies | PO receipt sync (legacy) | |
email_queue | emailDraftWorker.js (165 lines) | Bull queue | 1 | AI email draft generation | |
email_sync_checkpoints | Email sync service | N/A | N/A | Crash-safe email processing tracking | |
rex_sync_state | rexBackgroundSync.js (911 lines) | 15 min | full | Incremental sync checkpoint persistence |
Atomic Queue Claim Pattern
The ONLY safe way to claim queue items for processing:
Why this matters:
FOR UPDATElocks the selected rows so no other worker can claim themSKIP LOCKEDmeans if another worker already locked a row, skip it instead of waiting (prevents deadlocks)- Without both: two workers process the same item → duplicate payments, double fulfillments
Never use: SELECT then separate UPDATE — the gap between them is a race condition window.
Exponential Backoff Strategy
The canonical backoff intervals for REX sync:
After max_attempts (default 5) failures → dead letter. Send rexSyncFailureAlert email.
When adding new queue types, reuse this same backoff array. Don't invent new intervals.
Queue Deduplication
Prevent duplicate queue entries with UPSERT:
This ensures rapid updates to the same entity are debounced — only the latest payload is retained.
Payment dedup uses a separate 3-layer approach:
- Check
rex_sync_queuefor pendingorder_createbefore enqueuingpayment_pending_order - Payment ledger (
order_payments) tracks financial state per transaction with atomic claims isAlreadyPaidError()catch as safety net in queue worker
Binary-Split Batch Retry
For batch upserts where one bad record can fail the entire batch:
This recursively splits failing batches until the single bad record is isolated. O(log n) retries instead of retrying each record individually.
N+1 Elimination via Pre-fetch Maps
For sync jobs that process lists of entities needing related data:
Established in syncOrders.js for customer UUIDs. Apply this pattern whenever a sync loop needs related data.
Stale Lock Detection & Recovery
In-Progress Guard (all workers)
Critical: The finally block is mandatory. Early versions missed it → crashed sync left syncInProgress = true permanently.
Database-Level Stale Detection
For crash-safe checkpoints (email sync pattern):
Checkpoint Staleness Guard
REX background sync caps lookback to prevent "quota death spiral":
Without this: a crashed sync restarts from a week-old checkpoint → fetches thousands of records → exhausts API quota → checkpoint never advances → death spiral.
Echo Detection (Inventory Feedback Loops)
When Cortex pushes inventory to Shopify, Shopify fires an inventory_levels/update webhook back. Without echo detection, this creates an infinite loop.
Pattern: 90-second window via shopify_inventory_push_log:
Circuit breaker: 5 override reverts in 10 minutes → stop pushing.
Dead Letter Escalation
When a queue item exhausts all retries:
For email drafts, dead letters create a sticky note for manual handling.
Manual intervention paths:
manualRetry(queueId)→ reset to pendingdismissQueueItem(queueId, reason)→ mark dismissed with audit trail
Adaptive Rate Limiting (REX API)
Plus daily (10K) and hourly (1K) quota tracking in rex_quota_usage table. At 95% daily quota → warning. At 100% → pause sync, set status quota_exhausted.
Separate API keys (REX_API_KEY_SYNC vs REX_API_KEY_WEBHOOK) isolate webhook traffic from sync quota.
Feature Flags (Parsed at Call Time)
Integration feature flags are read at call time (not module load) so they can be toggled without restart:
| Flag | Default | Controls | |
|---|---|---|---|
SHOPIFY_INVENTORY_SYNC_ENABLED | false | Master switch for inventory push | |
SHOPIFY_INVENTORY_SYNC_DRY_RUN | false | Log-only mode | |
SHOPIFY_INVENTORY_SYNC_TEST_SKUS | empty | Comma-separated allowlist | |
SHOPIFY_INVENTORY_OVERRIDE_PROTECT | false | Revert manual Shopify overrides | |
SHOPIFY_INVENTORY_RECONCILIATION_ENABLED | false | Daily drift correction | |
REX_ORDER_SYNC_ENABLED | false | Order sync to REX | |
REX_PAYMENT_SYNC_ENABLED | false | Include payments in sync | |
REX_REFUND_SYNC_ENABLED | false | Refund sync |
Always read these with process.env.FLAG === 'true' at the point of use, never cache at module level.
Common Mistakes
| Mistake | Why It Happens | Prevention | |
|---|---|---|---|
| SELECT then UPDATE for queue claim | Looks simpler than CTE | Always use atomic UPDATE...WHERE id IN (SELECT...FOR UPDATE SKIP LOCKED) | |
Missing finally on syncInProgress | Early return or throw skips cleanup | Always use try/finally | |
| No staleness cap on checkpoint lookback | Assumes checkpoint is recent | Cap to 4 hours max | |
| N+1 queries in sync loop | Each entity fetches related data | Pre-fetch into Map before loop | |
| Retrying already-succeeded operations | Error message looks like failure | Check isAlreadyPaidError() patterns | |
| Caching feature flags at module load | Expects restart for changes | Read process.env at call time | |
| Same API key for sync and webhooks | Don't know about quota isolation | Use REX_API_KEY_WEBHOOK for webhook calls | |
| No echo detection on inventory push | Forget about webhook feedback loop | Log pushes, check 90s window on webhook |
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/sync-worker/SKILL.md
Popularity
- Repository stars
- 7
- 7-day trend score
- 10
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/anotherben/claude-harness/sync-worker)