realtime-database
When the user needs to design database schemas and queries optimized for real-time applications. Use when the user mentions "chat database," "message storage," "real-time sync," "message history," "unread count," "cursor pagination," "event sourcing," or "live data." Handles schema design for messaging, activity feeds, notifications, and collaborative apps with efficient pagination and sync. For WebSocket transport, see websocket-builder.
Best use case
realtime-database is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
When the user needs to design database schemas and queries optimized for real-time applications. Use when the user mentions "chat database," "message storage," "real-time sync," "message history," "unread count," "cursor pagination," "event sourcing," or "live data." Handles schema design for messaging, activity feeds, notifications, and collaborative apps with efficient pagination and sync. For WebSocket transport, see websocket-builder.
Teams using realtime-database should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/realtime-database/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How realtime-database Compares
| Feature / Agent | realtime-database | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
When the user needs to design database schemas and queries optimized for real-time applications. Use when the user mentions "chat database," "message storage," "real-time sync," "message history," "unread count," "cursor pagination," "event sourcing," or "live data." Handles schema design for messaging, activity feeds, notifications, and collaborative apps with efficient pagination and sync. For WebSocket transport, see websocket-builder.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Real-Time Database
## Overview
Designs database schemas and query patterns optimized for real-time applications — chat, activity feeds, notifications, collaborative editing. Focuses on efficient message storage, cursor-based pagination, unread tracking, and sync protocols that minimize data transfer on reconnection.
## Instructions
### 1. Schema Design for Messaging
Core tables for a chat system:
```sql
-- Channels (direct messages + groups)
CREATE TABLE channels (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
type VARCHAR(10) NOT NULL CHECK (type IN ('direct', 'group')),
name VARCHAR(100),
created_at TIMESTAMPTZ DEFAULT now()
);
-- Channel membership with read tracking
CREATE TABLE channel_members (
channel_id UUID REFERENCES channels(id),
user_id UUID NOT NULL,
role VARCHAR(20) DEFAULT 'member',
last_read_message_id BIGINT,
joined_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (channel_id, user_id)
);
-- Messages with sequential IDs for ordering
CREATE TABLE messages (
id BIGSERIAL PRIMARY KEY,
channel_id UUID REFERENCES channels(id),
sender_id UUID NOT NULL,
content TEXT NOT NULL,
reply_to_id BIGINT REFERENCES messages(id),
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ,
deleted_at TIMESTAMPTZ
);
CREATE INDEX idx_messages_channel_cursor
ON messages(channel_id, id DESC) WHERE deleted_at IS NULL;
```
Use BIGSERIAL for message IDs — sequential, sortable, perfect for cursor pagination.
### 2. Cursor-Based Pagination
Never use OFFSET for message history — it's O(n) and results shift as new messages arrive.
```sql
-- Load 50 messages before a cursor (scrolling up)
SELECT id, sender_id, content, created_at
FROM messages
WHERE channel_id = $1 AND id < $2 AND deleted_at IS NULL
ORDER BY id DESC
LIMIT 50;
-- Load messages after a cursor (sync on reconnect)
SELECT id, sender_id, content, created_at
FROM messages
WHERE channel_id = $1 AND id > $2 AND deleted_at IS NULL
ORDER BY id ASC;
```
Return cursor metadata: `{ messages: [...], nextCursor: 12345, hasMore: true }`
### 3. Unread Count Tracking
Use the `last_read_message_id` approach — one integer per user per channel:
```sql
-- Get unread count for a user across all channels
SELECT cm.channel_id, COUNT(m.id) AS unread_count
FROM channel_members cm
JOIN messages m ON m.channel_id = cm.channel_id
AND m.id > COALESCE(cm.last_read_message_id, 0)
AND m.deleted_at IS NULL
AND m.sender_id != $1
WHERE cm.user_id = $1
GROUP BY cm.channel_id
HAVING COUNT(m.id) > 0;
-- Mark channel as read
UPDATE channel_members
SET last_read_message_id = $2
WHERE channel_id = $1 AND user_id = $3;
```
### 4. Reconnection Sync
When a client reconnects, minimize data transfer:
```
1. Client sends: { lastMessageIds: { "ch_1": 500, "ch_2": 300 } }
2. Server queries: new messages per channel since those IDs
3. If gap > 200 messages: send summary + latest 50 (client should full-reload)
4. Return: { channels: { "ch_1": { messages: [...], hasMore: false } } }
```
### 5. Soft Deletes and Edits
Messages should use soft deletes to maintain thread integrity:
- `deleted_at` timestamp — filter in queries, show "message deleted" in UI
- `updated_at` timestamp — mark edited messages
- Keep `reply_to_id` references valid even after parent is soft-deleted
## Examples
### Example 1: Chat Schema for SaaS App
**Prompt**: "Design the database for chat in my project management tool. Direct messages and project channels."
**Output**: Complete migration with channels, members, messages tables; cursor pagination queries; unread count query; and index strategy. Estimated performance: sub-10ms for message history with 10M+ messages.
### Example 2: Activity Feed Schema
**Prompt**: "I need an activity feed — user actions like 'Alex commented on Task-42'. Need fan-out for team feeds."
**Output**: Events table with actor/verb/object pattern, fan-out-on-write to per-user feed tables, cursor pagination, and a cleanup job for feeds older than 90 days.
## Guidelines
- **Use sequential IDs** (BIGSERIAL) for cursor pagination — UUIDs can't be sorted by creation order
- **Never use OFFSET** — cursor pagination is O(1), OFFSET is O(n)
- **Track reads per-channel, not per-message** — one integer vs. millions of rows
- **Index for your access patterns** — (channel_id, id DESC) covers 90% of chat queries
- **Soft delete messages** — hard deletes break reply chains and confuse users
- **Partition large tables** by channel_id or time range if exceeding 100M rows
- **Cache hot channels** in Redis — recent messages and member listsRelated Skills
realtime-analytics
Build real-time analytics pipelines from scratch. Use when someone asks to "set up analytics", "build a dashboard", "track events in real time", "ClickHouse analytics", "event ingestion pipeline", or "live metrics". Covers event schema design, ingestion services with batching, ClickHouse table optimization, aggregation queries, and dashboard wiring.
openai-realtime
Build voice-enabled AI applications with the OpenAI Realtime API. Use when a user asks to implement real-time voice conversations, stream audio with WebSockets, build voice assistants, or integrate OpenAI audio capabilities.
database-schema-designer
Designs database schemas with proper normalization, indexing, constraints, and tenant isolation patterns. Use when someone needs to create a new database schema, add multi-tenant support, design row-level security policies, or optimize table structures. Trigger words: database schema, table design, RLS, row-level security, foreign keys, indexes, migrations, ERD, data model, normalization.
d1-database
Build serverless applications with Cloudflare D1 — SQLite at the edge. Use when someone asks to "serverless database", "Cloudflare D1", "SQLite at the edge", "database for Workers", "edge database", or "serverless SQL". Covers schema setup, queries, migrations, Workers integration, and Drizzle ORM.
zustand
You are an expert in Zustand, the small, fast, and scalable state management library for React. You help developers manage global state without boilerplate using Zustand's hook-based stores, selectors for performance, middleware (persist, devtools, immer), computed values, and async actions — replacing Redux complexity with a simple, un-opinionated API in under 1KB.
zoho
Integrate and automate Zoho products. Use when a user asks to work with Zoho CRM, Zoho Books, Zoho Desk, Zoho Projects, Zoho Mail, or Zoho Creator, build custom integrations via Zoho APIs, automate workflows with Deluge scripting, sync data between Zoho apps and external systems, manage leads and deals, automate invoicing, build custom Zoho Creator apps, set up webhooks, or manage Zoho organization settings. Covers Zoho CRM, Books, Desk, Projects, Creator, and cross-product integrations.
zod
You are an expert in Zod, the TypeScript-first schema declaration and validation library. You help developers define schemas that validate data at runtime AND infer TypeScript types at compile time — eliminating the need to write types and validators separately. Used for API input validation, form validation, environment variables, config files, and any data boundary.
zipkin
Deploy and configure Zipkin for distributed tracing and request flow visualization. Use when a user needs to set up trace collection, instrument Java/Spring or other services with Zipkin, analyze service dependencies, or configure storage backends for trace data.
zig
Expert guidance for Zig, the systems programming language focused on performance, safety, and readability. Helps developers write high-performance code with compile-time evaluation, seamless C interop, no hidden control flow, and no garbage collector. Zig is used for game engines, operating systems, networking, and as a C/C++ replacement.
zed
Expert guidance for Zed, the high-performance code editor built in Rust with native collaboration, AI integration, and GPU-accelerated rendering. Helps developers configure Zed, create custom extensions, set up collaborative editing sessions, and integrate AI assistants for productive coding.
zeabur
Expert guidance for Zeabur, the cloud deployment platform that auto-detects frameworks, builds and deploys applications with zero configuration, and provides managed services like databases and message queues. Helps developers deploy full-stack applications with automatic scaling and one-click marketplace services.
zapier
Automate workflows between apps with Zapier. Use when a user asks to connect apps without code, automate repetitive tasks, sync data between services, or build no-code integrations between SaaS tools.