backend-realtime
Skill9 starsChanged 42 days agoMITView on GitHub
Implement real-time features with WebSockets, Supabase Realtime, or Server-Sent Events. Use when "real-time", "live updates", "WebSocket", "notifications", "chat", "presence", "collaborative", "live data", or "instant sync".
- Reads credentials
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- kensaurus/skillsedited, first seen Oct 1, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- kensaurus/skills★ 940% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository165 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .cursor/rules/approved-plan-execution.mdcCursor rule
- .cursor/rules/skill-workflows.mdcCursor rule
- .cursor/rules/verification-before-completion.mdcCursor rule
- llms.txtllms.txt
- audit-accessibilitySkill
- audit-agent-speedSkill
- audit-analyticsSkill
- audit-auth-flowsSkill
- audit-backend-architectureSkill
- audit-bundle-sizeSkill
- audit-cicdSkill
- audit-codemod-safetySkill
- audit-code-qualitySkill
- audit-code-reviewSkill
- audit-db-schemaSkill
- audit-doctrineSkill
- audit-env-paritySkill
- audit-fe-apiSkill
- audit-gate-logicSkill
- audit-i18nSkill
- audit-infra-costSkill
- audit-langfuse-llmSkill
- audit-llm-securitySkill
- audit-monetization-iapSkill
- audit-payment-systemSkill
- audit-performanceSkill
- audit-realworldSkill
- audit-registry-listingSkill
- audit-resilienceSkill
- audit-responsiveSkill
- audit-securitySkill
- audit-skill-conflictsSkill
- audit-ui-statesSkill
- audit-uiux-design-systemSkill
- audit-ux-journeysSkill
- audit-uxSkill
- backend-db-performanceSkill
- backend-error-handlingSkill
- backend-observabilitySkill
- backend-patternsSkill
- burndown-fullSkill
- complete-everythingSkill
- data-pipelineSkill
- data-visualizationSkill
- debug-errorSkill
- debug-fe-be-integrationSkill
- debug-sentry-monitorSkill
- deploy-npmSkill
- deploy-verifySkill
- design-apiSkill
- design-canvasSkill
- design-emailSkill
- design-frontendSkill
- design-generative-artSkill
- design-mobile-firstSkill
- design-motionSkill
- design-prdSkill
- design-systemSkill
- design-themeSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 89
Read the roster from presenceState() on the sync event.
- Very specific: line 98
Use for cursors and typing.
- Very specific: line 104
Keep useQuery as the data source.
- Very specific: line 141
Add the sender to typingUsers and drop them after 3 s of silence.
- Distinctive: line 147
After implementing real-time features:
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Real-time Features Skill
Degree of freedom: MIXED. Which transport and event [HIGH freedom];
existing-subscription probes and unmount cleanup [LOW freedom — run exactly].
How to reason
- Observe — existing channels, sockets, hooks, cleanup
- Interpret — new subscription vs reuse vs transport mismatch
- Classify — postgres-changes / presence / broadcast / SSE / optimistic
- Severity — leaked or duplicate subscription outranks a missing typing indicator
Worked example
Observe: chat mounts
useRealtimeMessagestwice; no untrack on leave;package.jsonalready has@supabase/supabase-js. Interpret: duplicate INSERT listeners; leftover presence. Classify: one channel hook with unmount cleanup; reuse Supabase Realtime — do not add Socket.io. Verify: onepostgres_changessubscription;removeChannelon unmount; no second socket lib.
Self-critique before reporting
- Existing first — grepped channels/sockets before adding a library
- Cleanup — every subscribe has unmount
removeChannel/close - One listener — no duplicate subscription for the same event
- Right owner — FE↔BE payload mismatch →
debug-fe-be-integration; queue/job instead of live push →backend-patterns
Implement live, collaborative features using WebSockets, Supabase Realtime, and Server-Sent Events.
Code examples assume a Next.js App Router + Supabase stack (
@/lib/supabase/client,'use client'). Adapt import paths and row types to the detected stack.
Check existing first [LOW freedom — run exactly]
Before implementing ANY real-time feature, verify:
- Check for existing real-time setup:
cat package.json | grep -i "socket\|realtime\|pusher\|ably"
rg "supabase.*channel|useSubscription|WebSocket" --type ts --type tsx- Check for existing patterns:
rg "on\('INSERT'\|on\('UPDATE'\|subscribe\(" --type ts
ls -la src/hooks/use*Realtime* src/lib/realtime* 2>/dev/null- Check Supabase config:
rg "createClient|supabaseUrl" --type ts -l
grep -oh "SUPABASE_[A-Z_]*" .env* 2>/dev/null | sort -u # names only — never print valuesWhy: Real-time connections are stateful. Don't create duplicate subscriptions.
Supabase Realtime [HIGH freedom]
Subscribe to Database Changes
The canonical useRealtimeMessages hook (initial fetch + INSERT/DELETE
subscription with unmount cleanup) is in
references/patterns.md.
useEffect(() => {
const channel = supabase
.channel(`room:${roomId}`)
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages', filter: `room_id=eq.${roomId}` },
(payload) => setMessages((prev) => [...prev, payload.new as Message]))
.subscribe()
return () => { supabase.removeChannel(channel) }
}, [roomId, supabase])Presence (Online Users)
- One channel per room (
presence:${roomId});channel.track(currentUser)only afterstatus === 'SUBSCRIBED'. - Read the roster from
presenceState()on thesyncevent;join/leaveare for side effects only. - Cleanup is
channel.untrack()thensupabase.removeChannel(channel).
Full usePresence hook: references/patterns.md §Presence.
Broadcast (Custom Events)
- Hold the channel in a
useRef; register.on('broadcast', { event })handlers once, then.subscribe(). - Send with
channel.send({ type: 'broadcast', event, payload }); broadcast is ephemeral, never a source of truth. - Use for cursors and typing; use
postgres_changesfor anything that must persist.
Full useBroadcast hook and collaborative-cursor usage: references/patterns.md §Broadcast.
TanStack Query + Real-time [HIGH freedom]
- Keep
useQueryas the data source; the realtime channel only callsqueryClient.invalidateQueries({ queryKey }). - Subscribe to
postgres_changeswithevent: '*'on the table (optionalfilter); remove the channel on unmount. - One hook,
useRealtimeQuery(queryKey, queryFn, table, filter?), so every list gets the same behaviour.
Full useRealtimeQuery hook: references/patterns.md §TanStack Query + Real-time.
Optimistic Updates [HIGH freedom]
useOptimistic(initial, reducer)plususeTransition; add the optimistic row withpending: trueand acrypto.randomUUID()id, then await the Server Action.- Render pending rows at reduced opacity; the realtime INSERT or the action result replaces them.
- Disable the submit button while
isPending.
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
initialMessages, (state, msg: Message) => [...state, msg]
)
startTransition(async () => {
addOptimisticMessage({ id: crypto.randomUUID(), content, pending: true, /* ... */ })
await addMessage(content) // Server Action
})Full Chat component: references/patterns.md §Optimistic Updates.
Server-Sent Events (SSE) [HIGH freedom]
- Route handler returns a
ReadableStream; writedata: ${JSON.stringify(x)}\n\nframes withTextEncoder. - Headers:
text/event-stream,Cache-Control: no-cache,Connection: keep-alive; heartbeat every 30 s. - Clean up on
request.signalabort(clear timers,controller.close()). - Client:
new EventSource(url); close in the effect cleanup and ononerror, then reconnect with backoff. - Pick SSE for one-way server push without Supabase; pick Realtime when the data already lives in Postgres.
Full route handler and useSSE hook: references/patterns.md §Server-Sent Events.
Typing Indicators [HIGH freedom]
- Broadcast
{ event: 'typing', payload: { userId } }on keystroke; ignore your own id on receipt. - Add the sender to
typingUsersand drop them after 3 s of silence; debounce sends with atimeoutRef.
Full useTypingIndicator hook: references/patterns.md §Typing Indicators.
Validation [LOW freedom — do not skip]
After implementing real-time features:
- Connection handling → Reconnects on disconnect, shows status
- Error handling → Graceful degradation when real-time unavailable
- Memory leaks → All subscriptions cleaned up on unmount
- Duplicate subscriptions → No multiple listeners for same event
- Optimistic updates → UI feels instant, handles conflicts
- Mobile → Works on spotty connections, battery efficient
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

