realtime-database

Design database schemas and queries for real-time applications. Applicable when users mention “chat database,” “message storage,” “real-time sync,” “message history,” “unread counts,” “cursor pagination,” “event sourcing,” or “real-time data.” Supports efficient pagination and synchronization schema design for messaging, activity feeds, notifications, and collaboration apps. For WebSocket transport, see websocket-builder.

Last repository push
GitHub Stars
219
Forks
38
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "realtime-database" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-c93c36a8a1310643d026f68c2c7d47aa93e9786c18e6ef85fd97d4ee3295df7f. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Design database schemas and queries for real-time applications. Applicable when users mention “chat database,” “message storage,” “real-time sync,” “message history,” “unread counts,” “cursor pagination,” “event sourcing,” or “real-time data.” Supports efficient pagination and synchronization schema design for messaging, activity feeds, notifications, and collaboration apps. For WebSocket transport, see websocket-builder.

0 Downloads

Introduction source: third_party · TerminalSkills · 1.0.0 Reference

SkillPi interpretation

Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: realtime-database
description: >-
  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.
license: Apache-2.0
compatibility: "PostgreSQL 14+, MySQL 8+, or MongoDB 6+"
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: development
  tags: ["database", "real-time", "messaging", "schema-design"]

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:

-- 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.

-- 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:

-- 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 lists

Current listing version

1.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供实时应用数据库设计,解决消息存储、分页、同步等核心痛点
  • 覆盖聊天、活动流、通知等高频场景,具有广泛实用价值
Trigger Precision90/100

Highlights

  • 触发词覆盖完整且边界清晰
  • 与相关 Skill(websocket-builder)有明确分工说明
Structure and Standards95/100

Areas to improve

  • 缺少 When to Use 显式章节 Reported severity: Minor

    虽然在 frontmatter 中有 description,但在 skill_body 中未结构化呈现 When to Use 章节

    Recommendation: 建议在 Overview 后增加显式的 "When to Use" 章节,结构化呈现使用场景

Highlights

  • Phase/步骤清晰完整
  • 提供端到端示例
  • frontmatter 完整规范
Execution Reliability90/100

Highlights

  • SQL 语法正确,参数使用规范
  • 覆盖主要异常处理场景
  • 不可逆操作有明确安全条件
Evidence Verifiability (mean of the first four)90/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.