Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

database-advanced-optimization

БесплатноБез исполняемых скриптовНе проверен

Use SQL (PostgreSQL) when:

diegosouzapwот diegosouzapw★ 68 звёзд на GitHub

Об этом скилле

Database Advanced Optimization

Level 1: Quick Reference (5 minutes)

Database Selection Guide

Use SQL (PostgreSQL) when:

  • ACID compliance is critical
  • Complex joins and transactions required
  • Data has clear relational structure
  • Strong consistency needed
  • Rich query capabilities required

Use NoSQL (MongoDB) when:

  • Flexible schema needed
  • Horizontal scaling is priority
  • Document-oriented data model fits
  • High write throughput required
  • Eventual consistency acceptable

Use In-Memory (Redis) when:

  • Sub-millisecond latency required
  • Caching layer needed
  • Real-time features (pub/sub, streams)
  • Session management
  • Rate limiting or counters

Common Optimization Patterns

-- PostgreSQL: Create covering index
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at)
INCLUDE (status, total_amount);

-- PostgreSQL: Analyze query plan
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE user_id = 123;
// MongoDB: Create compound index
db.orders.createIndex({ userId: 1, createdAt: -1 }, { background: true });

// MongoDB: Use aggregation pipeline efficiently
db.orders.aggregate([
  { $match: { status: "pending" } },
  { $sort: { createdAt: -1 } },
  { $limit: 100 }
]);
# Redis: Implement cache-aside pattern
def get_user(user_id):
    cache_key = f"user:{user_id}"
    user = redis.get(cache_key)

    if user is None:
        user = db.query("SELECT * FROM users WHERE id = %s", user_id)
        redis.setex(cache_key, 3600, json.dumps(user))

    return json.loads(user)

Essential Optimization Checklist

PostgreSQL

  • Create appropriate indexes (B-tree, GIN, GiST)
  • Analyze query plans with EXPLAIN ANALYZE
  • Configure autovacuum appropriately
  • Set up connection pooling (PgBouncer)
  • Monitor with pg_stat_statements
  • Optimize shared_buffers and work_mem
  • Configure appropriate WAL settings

MongoDB

  • Design effective shard keys
  • Create compound indexes for common queries
  • Enable profiler for slow queries
  • Configure replica sets for read scaling
  • Optimize aggregation pipelines
  • Set appropriate write concerns
  • Monitor with MongoDB Compass/Atlas

Redis

  • Implement appropriate caching strategy
  • Configure maxmemory and eviction policies
  • Use pipelining for bulk operations
  • Set appropriate TTLs
  • Monitor memory usage and hit rates
  • Configure persistence (RDB/AOF) appropriately
  • Use Redis Cluster for scaling

Quick Wins

Immediate Impact:

  1. Add indexes for frequently queried columns
  2. Enable query result caching
  3. Implement connection pooling
  4. Add Redis cache layer for hot data
  5. Optimize N+1 queries with batch loading

Performance Monitoring:

# PostgreSQL query stats
SELECT query, calls, total_time, mean_time
FROM pg_stat_statements
ORDER BY mean_time DESC LIMIT 10;

# MongoDB profiler
db.setProfilingLevel(1, { slowms: 100 });
db.system.profile.find().sort({ ts: -1 }).limit(10);

# Redis stats
redis-cli INFO stats | grep -E 'keyspace_hits|keyspace_misses'

Level 2:

📚 Full Examples: See REFERENCE.md for complete code samples, detailed configurations, and production-ready implementations.

Implementation Guide (45 minutes)

PostgreSQL Advanced Optimization

Index Strategies

PostgreSQL supports multiple index types, each optimized for specific use cases:

B-tree Indexes (Default)

See REFERENCE.md for complete implementation.

GIN Indexes (Full-text and Array Search)

See REFERENCE.md for complete implementation.

GiST Indexes (Geometric and Range Data)

See REFERENCE.md for complete implementation.

Query Optimization with EXPLAIN ANALYZE

See REFERENCE.md for complete implementation.

Understanding EXPLAIN Output:

See REFERENCE.md for complete implementation.

Optimization Decisions:

  • Index Scan = Good (using indexes)
  • Buffers shared hit = Good (data in cache)
  • Nested Loop = Appropriate for small result sets
  • Hash Join = Better for large joins

VACUUM and Maintenance

See REFERENCE.md for complete implementation.

Connection Pooling with PgBouncer

See REFERENCE.md for complete implementation.

Connection Pooling Best Practices:

  • Use transaction mode for most applications
  • Set default_pool_size = (CPU cores × 2) + effective_spindle_count
  • Monitor pool usage: SHOW POOLS; in PgBouncer console
  • Application connection string: postgresql://user:pass@pgbouncer:6432/myapp

PostgreSQL Performance Tuning

See REFERENCE.md for complete implementation.

MongoDB Advanced Optimization

Sharding Strategies

Shard Key Selection:

Полный SKILL.md на GitHub

Установить database-advanced-optimization в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

metadata.json

FAQ

Что делает скилл database-advanced-optimization?

Use SQL (PostgreSQL) when:

Как установить скилл database-advanced-optimization?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл database-advanced-optimization запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить database-advanced-optimization с