subscription-sync
Manages synchronization lifecycles and event buffering for real-time frontend applications.
Install
mkdir -p .claude/skills/subscription-sync && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/18225" && unzip -o skill.zip -d .claude/skills/subscription-sync && rm skill.zipInstalls to .claude/skills/subscription-sync
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Real-time data synchronization patterns for ChainGraph frontend. Use when working on WebSocket subscriptions, event buffers, tRPC subscriptions, flow synchronization, or execution event streaming. Covers subscription lifecycle, event buffering, race condition solutions. Triggers: subscription, sync, real-time, websocket, event buffer, tRPC subscription, flow events, onData, patronum interval.Key capabilities
- →Manage real-time data synchronization via WebSocket subscriptions
- →Utilize two separate tRPC clients for flow editing and execution events
- →Implement event buffering to prevent race conditions during flow initialization
- →Handle flow subscription lifecycle including connecting, subscribed, and disconnected states
- →Subscribe to execution events and ensure proper sequencing
How it works
The skill uses two tRPC clients for separate WebSocket connections to handle flow editing and execution events. It employs an event buffer to batch and flush flow events atomically, preventing race conditions.
Inputs & outputs
When to use subscription-sync
- →Debug real-time data sync
- →Implement WebSocket subscription
- →Manage event buffer state
About this skill
Subscription Sync Patterns
This skill covers the real-time data synchronization system between ChainGraph backend and frontend via WebSocket subscriptions.
Architecture Overview
┌──────────────────────────────────────────────────────────────┐
│ BACKEND (tRPC) │
│ │
│ Flow Subscription Execution Subscription │
│ ├─ FlowInitStart ├─ EXECUTION_CREATED │
│ ├─ NodesAdded ├─ FLOW_STARTED │
│ ├─ EdgesAdded ├─ NODE_STARTED │
│ ├─ FlowInitEnd ├─ NODE_COMPLETED │
│ ├─ NodeUpdated ├─ EDGE_TRANSFER │
│ ├─ PortUpdated └─ FLOW_COMPLETED │
│ └─ ... │
└──────────────────┬───────────────────────┬───────────────────┘
│ WebSocket │ WebSocket
▼ ▼
┌──────────────────────────────────────────────────────────────┐
│ FRONTEND │
│ │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ $trpcClient │ │ $trpcClientExecutor │ │
│ │ ws://localhost:3001 │ │ ws://localhost:4021 │ │
│ └──────────┬──────────┘ └──────────┬──────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ Flow Event Buffer │ │ Execution Events │ │
│ │ (50ms batching) │ │ (direct processing) │ │
│ └──────────┬──────────┘ └──────────┬──────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌────────────────────────────────────────────────┐ │
│ │ Effector Stores │ │
│ │ $nodes, $edges, $portValues, $execution │ │
│ └────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
Two tRPC Clients
ChainGraph frontend maintains TWO separate WebSocket connections:
Files:
- Main Server Client:
apps/chaingraph-frontend/src/store/trpc/store.ts - Executor Server Client:
apps/chaingraph-frontend/src/store/trpc/execution-client.ts
// Main Server - Flow editing operations (store.ts)
export const $trpcClient = trpcDomain.createStore<TRPCClient | null>(null)
// Connects to: ws://localhost:3001
// Executor Server - Execution events (execution-client.ts)
export const $trpcClientExecutor = trpcDomain.createStore<TRPCClient | null>(null)
// Connects to: ws://localhost:4021
Why Two Clients?
- Separation of Concerns: Flow editing and execution are independent
- Load Distribution: Heavy execution traffic doesn't block editing
- Independent Scaling: Executor can scale separately
- Failure Isolation: Execution server crash doesn't break editing
Flow Subscription Lifecycle
Files:
- Subscription:
apps/chaingraph-frontend/src/store/flow/subscription.ts - Event Buffer:
apps/chaingraph-frontend/src/store/flow/event-buffer.ts
Event Sequence
1. FlowInitStart
└─ Clear existing nodes/edges
└─ Set status: CONNECTING → SUBSCRIBED
2. NodesAdded (batch)
└─ Buffer accumulates events
3. EdgesAdded (batch)
└─ Buffer accumulates events
4. FlowInitEnd (COMMIT SIGNAL)
└─ Buffer flushes immediately
└─ All events processed atomically
└─ Nodes render BEFORE edges (race condition solved)
5. Live Updates (ongoing)
└─ Buffer with 50ms interval
└─ NodeUpdated, PortUpdated, EdgeAdded, etc.
Subscription Status
enum FlowSubscriptionStatus {
IDLE = 'idle',
CONNECTING = 'connecting',
SUBSCRIBED = 'subscribed',
ERROR = 'error',
DISCONNECTED = 'disconnected',
}
Event Buffer Pattern
Problem: Race condition where edges render before nodes during flow initialization.
Root Cause:
1. addNodes triggers xyflowStructureChanged with 50ms debounce
2. setEdges updates $xyflowEdges immediately
3. $xyflowEdges filters out edges because $xyflowNodes is empty
Solution: Buffer ALL FlowEvents and flush atomically on FlowInitEnd.
File: apps/chaingraph-frontend/src/store/flow/event-buffer.ts
import { interval } from 'patronum'
// Buffer accumulates events
export const $flowEventBuffer = flowDomain.createStore<FlowEvent[]>([])
.on(flowEventReceived, (buffer, event) => [...buffer, event])
// Ticker runs every 50ms (configurable via VITE_FLOW_EVENT_BUFFER_INTERVAL)
const ticker = interval({
timeout: 50, // BUFFER_INTERVAL_MS
start: tickerStart,
stop: tickerStop,
})
// Auto-start ticker when first event arrives
sample({
clock: flowEventReceived,
source: $flowEventBuffer,
filter: buffer => buffer.length === 1, // Buffer was empty
target: tickerStart,
})
// Auto-stop ticker when buffer is empty
sample({
clock: $flowEventBuffer,
filter: buffer => buffer.length === 0,
target: tickerStop,
})
// CRITICAL: Flush immediately on FlowInitEnd
sample({
clock: flowEventReceived,
filter: event => event.type === FlowEventType.FlowInitEnd,
target: flushBuffer,
})
Buffer Processing Flow
Subscription → flowEventReceived → $flowEventBuffer
│
┌────────────────────┴────────────────────┐
│ │
[FlowInitEnd] [50ms tick]
│ │
▼ ▼
flushBuffer (immediate) processBufferFx (batched)
│ │
└────────────────┬─────────────────────────┘
│
▼
newFlowEvents (batch of FlowEvent[])
│
▼
Event Handlers in stores.ts
Execution Subscription
File: apps/chaingraph-frontend/src/store/execution/subscription.ts
Execution events are processed directly (no buffering needed):
// Subscribe to execution events
// Note: No .execution namespace - procedures are at router root
const subscription = trpcClientExecutor.subscribeToExecutionEvents.subscribe(
{ executionId, fromIndex: 0 },
{
onData: (event) => {
executionEventReceived(event) // Direct dispatch
},
onError: (error) => {
executionError(error)
},
}
)
Execution Event Types
enum ExecutionEventEnum {
EXECUTION_CREATED = 'EXECUTION_CREATED', // index -1
FLOW_STARTED = 'FLOW_STARTED',
NODE_STARTED = 'NODE_STARTED',
NODE_COMPLETED = 'NODE_COMPLETED',
NODE_FAILED = 'NODE_FAILED',
EDGE_TRANSFER_COMPLETED = 'EDGE_TRANSFER_COMPLETED',
FLOW_COMPLETED = 'FLOW_COMPLETED',
FLOW_FAILED = 'FLOW_FAILED',
CHILD_EXECUTION_SPAWNED = 'CHILD_EXECUTION_SPAWNED',
}
Key Files
| File | Purpose |
|---|---|
src/store/trpc/store.ts | tRPC client stores |
src/store/flow/subscription.ts | Flow subscription management |
src/store/flow/event-buffer.ts | Event buffering with patronum |
src/store/execution/subscription.ts | Execution event subscription |
src/store/flow/stores.ts | Event handlers (newFlowEvents) |
Common Patterns
Subscribe to Flow
import { subscribeToFlowFx, unsubscribeFromFlowFx } from '@/store/flow/subscription'
// Subscribe
subscribeToFlowFx(flowId)
// Unsubscribe (cleanup)
unsubscribeFromFlowFx()
Handle Flow Events
// In stores.ts
sample({
clock: newFlowEvents,
filter: events => events.some(e => e.type === FlowEventType.NodeUpdated),
fn: events => events.filter(e => e.type === FlowEventType.NodeUpdated),
target: processNodeUpdates,
})
Subscribe to Execution
import { subscribeToExecutionFx } from '@/store/execution/subscription'
// Subscribe and wait for EXECUTION_CREATED
await subscribeToExecutionFx({ executionId })
// Start execution after subscription is ready
startExecution({ executionId })
Anti-Patterns
Anti-Pattern #1: Processing events without buffering
// ❌ BAD: Direct dispatch causes race conditions
onData: (event) => {
newFlowEvents([event]) // Edges may render before nodes!
}
// ✅ GOOD: Use buffer
onData: (event) => {
flowEventReceived(event) // Buffer handles ordering
}
Anti-Pattern #2: Not waiting for EXECUTION_CREATED
// ❌ BAD: Start before subscription is ready
startExecution({ executionId })
subscribeToExecutionFx({ executionId }) // Might miss events!
// ✅ GOOD: Subscribe first, then start
await subscribeToExecutionFx({ executionId })
startExecution({ executionId })
Anti-Pattern #3: Not cleaning up subscriptions
// ❌ BAD: Memory leak
useEffect(() => {
subscribeToFlowFx(flowId)
// No cleanup!
}, [flowId])
// ✅ GOOD: Cleanup on unmount/change
useEffect(() => {
subscribeToFlowFx(flowId)
return () => {
unsubscribeFromFlowFx()
}
}, [flowId])
Quick Reference
| Need | Pattern | File |
|---|---|---|
| Subscribe to flow | subscribeToFlowFx(flowId) | flow/subscription.ts |
| Buffer events | flowEventReceived(event) | flow/event-buffer.ts |
| Process buffered events | newFlowEvents event | flow/stores.ts |
| Subscribe to execution | `subs |
Content truncated.
When not to use it
- →When processing events without buffering, which causes race conditions
- →When starting execution before the subscription is ready
- →When not cleaning up subscriptions, which causes memory leaks
Limitations
- →Requires two separate WebSocket connections for flow editing and execution
- →Relies on specific event buffering patterns to prevent race conditions
- →Requires explicit cleanup of subscriptions to avoid memory leaks
How it compares
This skill provides specific patterns and architecture for managing real-time data synchronization with separate clients and event buffering, which is more structured than a generic WebSocket implementation.
Compared to similar skills
subscription-sync side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| subscription-sync (this skill) | 0 | 6mo | No flags | Advanced |
| telegram-mini-app | 62 | 6mo | Review | Advanced |
| create-mcp-app | 3 | 4mo | Review | Advanced |
| shopify-apps | 1 | 3mo | Review | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
You might also like
telegram-mini-app
davila7
Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize. Use when: telegram mini app, TWA, telegram web app, TON app, mini app.
create-mcp-app
modelcontextprotocol
This skill should be used when the user asks to "create an MCP App", "add a UI to an MCP tool", "build an interactive MCP View", "scaffold an MCP App", or needs guidance on MCP Apps SDK patterns, UI-resource registration, MCP App lifecycle, or host integration. Provides comprehensive guidance for building MCP Apps with interactive UIs.
shopify-apps
alinaqi
Shopify app development - Remix, Admin API, checkout extensions
ccxt-typescript
ccxt
CCXT cryptocurrency exchange library for TypeScript and JavaScript developers (Node.js and browser). Covers both REST API (standard) and WebSocket API (real-time). Helps install CCXT, connect to exchanges, fetch market data, place orders, stream live tickers/orderbooks, handle authentication, and manage errors. Use when working with crypto exchanges in TypeScript/JavaScript projects, trading bots, arbitrage systems, or portfolio management tools. Includes both REST and WebSocket examples.
add-nodebridge-handler
neovateai
Use this skill when adding a new NodeBridge handler to src/nodeBridge.ts, including updating types in src/nodeBridge.types.ts and optionally testing with scripts/test-nodebridge.ts
mcp-builder
anthropics
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).