Agent skill

Database Patterns

by majiayu000 in majiayu000/spellbook

A skill your agent uses when designing PostgreSQL + Redis data models, indexes, caching strategies, JSONB usage, tiered storage, or cache consistency contracts.

MITAuto-check passedDatabases

Install Database Patterns

skills CLI
$ npx skills add majiayu000/spellbook --skill database-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install majiayu000/spellbook database-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/majiayu000/spellbook.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/database-patterns .claude/skills/database-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
database-patterns
GitHub stars
286
Token cost
~2.8k tokens
SKILL.md length
175 words
Files
4
Skills in repo
96
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when designing PostgreSQL + Redis data models, indexes, caching strategies, JSONB usage, tiered storage, or cache consistency contracts.

  • Designing PostgreSQL + Redis data models
  • SKILL.md covers Core Principles, PostgreSQL, Redis and Caching Patterns, plus 4 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Caching strategies

What it does

Database Patterns is an agent skill from majiayu000/spellbook. Use when designing PostgreSQL + Redis data models, indexes, caching strategies, JSONB usage, tiered storage, or cache consistency contracts.

Its SKILL.md is about 2.8k tokens, which your agent loads only when the skill is triggered. The skill folder holds 4 other files (for example `reference/caching.md`, `reference/postgresql.md` and `reference/redis.md`).

It sits in Databases, covering Caching. It works with PostgreSQL and Redis. The repository describes itself as: Cross-runtime skills for Claude Code, Codex, and multi-agent workflows. The licence is MIT.

When your agent uses it

  • Designing PostgreSQL + Redis data models
  • Caching strategies
  • Cache consistency contracts

Example prompts

  • “/database-patterns”

What it can do on your machine

Read from SKILL.md and the folder at commit 414b597. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript, sql and markdown).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Database Patterns loads about 2.8k tokens when it runs. Until then it costs about 40 tokens; SKILL.md has 175 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~40
When it runs · the whole SKILL.md, loaded when a task matches
~2.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from majiayu000/spellbook at commit 414b597, republished under its MIT licence (© majiayu000). 175 words, ~2,781 tokens.

Download SKILL.mdSave it as .claude/skills/database-patterns/SKILL.md (or your agent's skills folder). This skill also uses 3 other files; get the full folder from GitHub.
name
database-patterns
description
Use when designing PostgreSQL + Redis data models, indexes, caching strategies, JSONB usage, tiered storage, or cache consistency contracts.

Database Patterns

Core Principles

  • PostgreSQL Primary — Relational data, transactions, complex queries
  • Redis Secondary — Caching, sessions, real-time data
  • Index-First Design — Design queries before indexes
  • JSONB Sparingly — Structured data prefers columns
  • Cache-Aside Default — Read-through, write-around
  • Tiered Storage — Hot/Warm/Cold data separation
  • No backwards compatibility — Migrate data, don't keep legacy schemas

PostgreSQL

Data Type Selection
Use CaseTypeAvoid
Primary KeyUUID / BIGSERIALINT (range limits)
TimestampsTIMESTAMPTZTIMESTAMP (no timezone)
MoneyNUMERIC(19,4)FLOAT (precision loss)
StatusTEXT + CHECKINT (unreadable)
Semi-structuredJSONBJSON (no indexing)
Full-textTSVECTORLIKE '%..%'
Schema Design
sql
-- Use UUID for distributed-friendly IDs
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  email TEXT UNIQUE NOT NULL,
  name TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'active'
    CHECK (status IN ('active', 'inactive', 'suspended')),
  metadata JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Updated timestamp trigger
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER users_updated_at
  BEFORE UPDATE ON users
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at();
Indexing Strategy
sql
-- B-Tree: Equality, range, sorting (default)
CREATE INDEX idx_users_email ON users(email);

-- Composite: Leftmost prefix rule
-- Supports: (user_id), (user_id, created_at)
-- Does NOT support: (created_at) alone
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);

-- Partial: Reduce index size
CREATE INDEX idx_active_users ON users(email)
  WHERE status = 'active';

-- GIN for JSONB: Containment queries
CREATE INDEX idx_metadata ON users USING GIN (metadata jsonb_path_ops);

-- Expression: Specific JSONB field
CREATE INDEX idx_user_role ON users ((metadata->>'role'));

-- Full-text search
CREATE INDEX idx_search ON products USING GIN (to_tsvector('english', name || ' ' || description));
JSONB Usage
sql
-- Good: Dynamic attributes, rarely queried fields
CREATE TABLE products (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  price NUMERIC(19,4) NOT NULL,
  category TEXT NOT NULL,           -- Extracted: frequently queried
  attributes JSONB DEFAULT '{}'     -- Dynamic: color, size, specs
);

-- Query with containment
SELECT * FROM products
WHERE category = 'electronics'              -- B-Tree index
  AND attributes @> '{"brand": "Apple"}';   -- GIN index

-- Query specific field
SELECT * FROM products
WHERE attributes->>'color' = 'black';       -- Expression index

-- Update JSONB field
UPDATE products
SET attributes = attributes || '{"featured": true}'
WHERE id = '...';
Query Optimization
sql
-- Always use EXPLAIN ANALYZE
EXPLAIN ANALYZE
SELECT u.*, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.status = 'active'
GROUP BY u.id
ORDER BY u.created_at DESC
LIMIT 20;

-- Watch for:
-- ❌ Seq Scan on large tables → Add index
-- ❌ Sort → Use index for ordering
-- ❌ Nested Loop with many rows → Consider JOIN order
-- ❌ Hash Join on huge tables → Add indexes
Connection Pooling
typescript
// PgBouncer or built-in pool
import { Pool } from 'pg';

const pool = new Pool({
  max: 20,                      // Max connections
  idleTimeoutMillis: 30000,     // Close idle connections
  connectionTimeoutMillis: 2000, // Fail fast
});

// Connection count formula:
// connections = (cores * 2) + effective_spindle_count
// Usually 10-30 is enough

Redis

Data Structure Selection
Use CaseStructureExample
Cache objectsStringuser:123 → JSON
CountersString + INCRviews:article:456
SessionsHashsession:abc → {userId, ...}
LeaderboardsSorted Setscores → {userId: score}
QueuesList/Streamtasks → LPUSH/RPOP
Unique setsSetonline_users
Real-timePub/Sub/StreamNotifications
Key Naming
# Format: <entity>:<id>:<attribute>
user:123:profile
user:123:settings
order:456:items
session:abc123

# Use colons for hierarchy
# Enables pattern matching with SCAN
SCAN 0 MATCH "user:*:profile" COUNT 100
TTL Strategy
typescript
const TTL = {
  SESSION: 24 * 60 * 60,      // 24 hours
  CACHE: 15 * 60,             // 15 minutes
  RATE_LIMIT: 60,             // 1 minute
  LOCK: 30,                   // 30 seconds
};

// Set with TTL
await redis.set(`cache:user:${id}`, JSON.stringify(user), 'EX', TTL.CACHE);

// Check TTL
const remaining = await redis.ttl(`cache:user:${id}`);

Caching Patterns

Cache-Aside (Lazy Loading)
typescript
async function getUser(id: string): Promise<User> {
  const cacheKey = `user:${id}`;

  // 1. Check cache
  const cached = await redis.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }

  // 2. Cache miss → Query database
  const user = await db.user.findUnique({ where: { id } });
  if (!user) {
    throw new NotFoundError('User not found');
  }

  // 3. Populate cache
  await redis.set(cacheKey, JSON.stringify(user), 'EX', 900);

  return user;
}
Write-Through
typescript
async function updateUser(id: string, data: UpdateInput): Promise<User> {
  // 1. Update database
  const user = await db.user.update({
    where: { id },
    data,
  });

  // 2. Update cache immediately
  await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 900);

  return user;
}
Cache Invalidation
typescript
async function deleteUser(id: string): Promise<void> {
  // 1. Delete from database
  await db.user.delete({ where: { id } });

  // 2. Invalidate cache
  await redis.del(`user:${id}`);

  // 3. Invalidate related caches
  const keys = await redis.keys(`user:${id}:*`);
  if (keys.length > 0) {
    await redis.del(...keys);
  }
}
Cache Stampede Prevention
typescript
async function getUserWithLock(id: string): Promise<User> {
  const cacheKey = `user:${id}`;
  const lockKey = `lock:user:${id}`;

  // Check cache
  const cached = await redis.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }

  // Try to acquire lock
  const acquired = await redis.set(lockKey, '1', 'EX', 10, 'NX');

  if (!acquired) {
    // Another process is loading, wait and retry
    await sleep(100);
    return getUserWithLock(id);
  }

  try {
    // Double-check cache (another process might have populated it)
    const rechecked = await redis.get(cacheKey);
    if (rechecked) {
      return JSON.parse(rechecked);
    }

    // Load from database
    const user = await db.user.findUnique({ where: { id } });
    await redis.set(cacheKey, JSON.stringify(user), 'EX', 900);
    return user;
  } finally {
    await redis.del(lockKey);
  }
}
Cache Penetration Prevention
typescript
async function getUserSafe(id: string): Promise<User | null> {
  const cacheKey = `user:${id}`;

  const cached = await redis.get(cacheKey);

  // Check for cached null
  if (cached === 'NULL') {
    return null;
  }

  if (cached) {
    return JSON.parse(cached);
  }

  const user = await db.user.findUnique({ where: { id } });

  if (!user) {
    // Cache null with short TTL
    await redis.set(cacheKey, 'NULL', 'EX', 60);
    return null;
  }

  await redis.set(cacheKey, JSON.stringify(user), 'EX', 900);
  return user;
}

Tiered Storage

┌─────────────────────────────────────────────────┐
│                   Application                    │
└─────────────────────────────────────────────────┘
                        │
        ┌───────────────┼───────────────┐
        ▼               ▼               ▼
   ┌─────────┐    ┌─────────┐    ┌─────────┐
   │  Redis  │    │ Postgres │    │ Archive │
   │  (Hot)  │    │  (Warm)  │    │  (Cold) │
   └─────────┘    └─────────┘    └─────────┘

   < 1ms          ~10ms           ~100ms+
   Active data    Recent data     Historical
   Memory         SSD             Object storage
Partitioning for Cold Data
sql
-- Partition by date range
CREATE TABLE orders (
  id UUID NOT NULL,
  user_id UUID NOT NULL,
  total NUMERIC(19,4) NOT NULL,
  created_at TIMESTAMPTZ NOT NULL
) PARTITION BY RANGE (created_at);

-- Create partitions
CREATE TABLE orders_2025_q1 PARTITION OF orders
  FOR VALUES FROM ('2025-01-01') TO ('2025-04-01');

CREATE TABLE orders_2025_q2 PARTITION OF orders
  FOR VALUES FROM ('2025-04-01') TO ('2025-07-01');

-- Archive old data
CREATE TABLE orders_archive (LIKE orders INCLUDING ALL);

-- Move old data to archive
WITH moved AS (
  DELETE FROM orders
  WHERE created_at < NOW() - INTERVAL '1 year'
  RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;

Transactions

ACID Compliance
typescript
// Use transactions for multi-table operations
async function transferFunds(fromId: string, toId: string, amount: number) {
  await db.$transaction(async (tx) => {
    // Deduct from source
    const from = await tx.account.update({
      where: { id: fromId },
      data: { balance: { decrement: amount } },
    });

    if (from.balance < 0) {
      throw new Error('Insufficient funds');
    }

    // Add to destination
    await tx.account.update({
      where: { id: toId },
      data: { balance: { increment: amount } },
    });
  });
}
Optimistic Locking
sql
-- Add version column
ALTER TABLE products ADD COLUMN version INT DEFAULT 1;

-- Update with version check
UPDATE products
SET
  stock = stock - 1,
  version = version + 1
WHERE id = $1 AND version = $2
RETURNING *;

-- If no rows returned, concurrent modification occurred

Checklist

markdown
## Schema
- [ ] UUID or BIGSERIAL for primary keys
- [ ] TIMESTAMPTZ for all timestamps
- [ ] NUMERIC for money, not FLOAT
- [ ] CHECK constraints for enums
- [ ] Foreign keys with ON DELETE

## Indexing
- [ ] Index for each WHERE clause pattern
- [ ] Composite indexes match query order
- [ ] GIN index for JSONB containment
- [ ] EXPLAIN ANALYZE for slow queries

## Caching
- [ ] Cache-aside as default pattern
- [ ] TTL on all cached data
- [ ] Cache invalidation on writes
- [ ] Stampede/penetration protection

## Operations
- [ ] Connection pooling configured
- [ ] Slow query logging enabled
- [ ] Backup and recovery tested
- [ ] Partition strategy for growth

See Also

© majiayu000, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 3 other files in skills/database-patterns of majiayu000/spellbook.

  • SKILL.md
  • reference/caching.md
  • reference/postgresql.md
  • reference/redis.md

Open the folder on GitHubat commit 414b597

Compare with similar skills

Database Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Database Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Database Patterns this skillmajiayu000/spellbook286—~2.8kAutomated safety check: PassMIT
Database Domain Specialistmodu-ai/moai-adk1.2k—~2.8kAutomated safety check: PassApache-2.0
Stripe Projectsfossasia/eventyay1.7k5 repos~2kAutomated safety check: NotesApache-2.0
Redis Coreredis/agent-skills1652 repos~759Automated safety check: PassMIT
Rhctlsaidake/rhctl106—~4kAutomated safety check: NotesApache-2.0
Veloxdb Scalable Performanceveloxbase/veloxdb646—~1.7kAutomated safety check: PassMIT

Similar skills

  • Database guidance for PostgreSQL, MongoDB, Redis and Oracle plus Neon, Supabase and Firestore: schema design, indexing, query tuning and cloud database choice.

    1.2k GitHub stars~2.8k tokensUpdated today
    DatabasesAuto-check passed
  • Stripe Projects

    fossasia/eventyay

    A skill your agent uses when the user wants to provision infrastructure or third-party services using Stripe Projects.

    1.7k GitHub starsUsed in 5 repos~2k tokens
    Backend & APIsAuto-check: notes
  • Redis Core

    redis/agent-skills

    Official

    Core Redis modeling guidance — choose the right data structure (String, Hash, List, Set, Sorted Set, JSON, Stream, Vector Set) and use consistent colon-separated key names.

    165 GitHub starsUsed in 2 repos~759 tokens
    DatabasesAuto-check passed
  • Rhctl

    saidake/rhctl

    Run and author rhctl CLI workflows and remote environment scripts under scripts/ (PostgreSQL, JetStream, Docker, Redis, MongoDB, AWS LocalStack, execute/upload/patch).

    106 GitHub stars~4k tokensUpdated yesterday
    DatabasesAuto-check: notes
  • Guides scalability and performance work for VeloxDB's Tauri + Rust PostgreSQL backend and React + TanStack frontend.

    646 GitHub stars~1.7k tokensUpdated 7 days ago
    DatabasesAuto-check passed
  • Configure REST Cache

    strapi-community/plugin-rest-cache

    Choose and write a Strapi REST Cache configuration for a specific use case.

    155 GitHub stars~1.1k tokensUpdated 9 days ago
    DatabasesAuto-check passed

More from majiayu000/spellbook

All 96 skills in this repo
  • Skill Ecosystem Doctor

    majiayu000/spellbook

    Audits and repairs how coding-agent Skills are owned, copied and exposed across runtimes, from canonical sources to quarantine and retirement.

    286 GitHub stars~3k tokensUpdated yesterday
    Auto-check passed
  • AGENTS.md Scaffold

    majiayu000/spellbook

    Scans a repository for real evidence and proposes, or on request writes, a small stack of root and scoped AGENTS.md files with validation commands and generated-file boundaries.

    286 GitHub stars~1.5k tokensUpdated yesterday
    Auto-check passed
  • Product Demo Builder

    majiayu000/spellbook

    Plans, produces or diagnoses evidence-backed product demo videos: script, capture plan, pacing checks and verified final media built on real product behavior.

    286 GitHub stars~3.3k tokensUpdated yesterday
    Auto-check passed
  • Flowguard Task Guard

    majiayu000/spellbook

    Single entry point that routes long or ambiguous agent tasks, checks live state, bounds autonomous loops and leaves a resumable handoff.

    286 GitHub stars~2.1k tokensUpdated yesterday
    Auto-check passed
  • npm Supply Chain Check

    majiayu000/spellbook

    Scans a repository, its lockfiles and node_modules for known malicious npm package versions and install-time indicators, using a read-only Python scanner.

    286 GitHub stars~1.5k tokensUpdated yesterday
    Auto-check passed
  • Product Manager Toolkit

    majiayu000/spellbook

    Product management helpers: a RICE scoring script, an interview transcript analyzer and PRD templates for prioritizing features, synthesizing research and writing requirements.

    286 GitHub stars~2.2k tokensUpdated yesterday
    Auto-check passed

Works with

Categories

Questions about Database Patterns

What does Database Patterns do?

A skill your agent uses when designing PostgreSQL + Redis data models, indexes, caching strategies, JSONB usage, tiered storage, or cache consistency contracts. Database Patterns is an agent skill from majiayu000/spellbook. Use when designing PostgreSQL + Redis data models, indexes, caching strategies, JSONB usage, tiered storage, or cache consistency contracts.

When should I use Database Patterns?

Database Patterns fits situations like: designing PostgreSQL + Redis data models; caching strategies; cache consistency contracts.

How do I install Database Patterns in Claude Code?

Run `npx skills add majiayu000/spellbook --skill database-patterns -a claude-code`. Or copy the skill folder (skills/database-patterns in majiayu000/spellbook) into .claude/skills/database-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Database Patterns in Codex?

Run `npx skills add majiayu000/spellbook --skill database-patterns -a codex`. Or copy the skill folder (skills/database-patterns in majiayu000/spellbook) into .agents/skills/database-patterns in your project. Codex loads it when a task matches its description.

Can I use Database Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add majiayu000/spellbook --skill database-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/database-patterns, .gemini/skills/database-patterns, .github/skills/database-patterns and .opencode/skills/database-patterns in your project.

What does Database Patterns need to run?

SKILL.md names no scripts, command-line tools or credentials: Database Patterns is instructions for the agent only.

Does Database Patterns access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Database Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Database Patterns use?

Database Patterns is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Database Patterns use?

About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Database Patterns?

Skills that share tags, products or a category with Database Patterns: Database Domain Specialist (modu-ai/moai-adk, 1.2k stars), Stripe Projects (fossasia/eventyay, 1.7k stars), Redis Core (redis/agent-skills, 165 stars) and Rhctl (saidake/rhctl, 106 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Database Patterns?

majiayu000 (a GitHub user) maintains it in majiayu000/spellbook, which has 286 GitHub stars. The repository holds 96 skills in this directory. The repository was last updated on October 6, 2026.

Source: majiayu000/spellbook on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.