技能 postgres-performance
📦

postgres-performance

低风险

PostgreSQL 쿼리 성능 최적화

데이터베이스 성능 문제는 애플리케이션 속도를 저하시키고 사용자를 불편하게 합니다. 이 스킬은 인덱싱 전략, 쿼리 튜닝, 확장 가능한 아키텍처 패턴을 포함한 PostgreSQL 최적화를 위한 검증된 패턴을 제공합니다.

支持: Claude Codex Code(CC)
⚠️ 68
1

下载技能 ZIP

2

在 Claude 中上传

前往 设置 → 功能 → 技能 → 上传技能

3

开启并开始使用

测试它

正在使用“postgres-performance”。 My query SELECT * FROM events WHERE user_id = 'abc-123' ORDER BY created_at DESC LIMIT 10 is slow on a table with 5M rows.

预期结果:

The query likely performs a sequential scan on the large events table. Here is the optimization approach:

**Problem:** Missing index for the filter and ORDER BY columns.

**Solution:** Create a covering index:
```sql
CREATE INDEX CONCURRENTLY ix_events_user_created
ON events (user_id, created_at DESC);
```

This index allows:
1. Filtering by user_id directly from the index
2. Sorting by created_at DESC using the index order
3. Index-only scan if you select only indexed columns

**Verification:**
```sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM events
WHERE user_id = 'abc-123'
ORDER BY created_at DESC
LIMIT 10;
```

Look for "Index Scan" instead of "Seq Scan" in the plan.

正在使用“postgres-performance”。 How should I implement pagination for a high-traffic API endpoint?

预期结果:

Avoid OFFSET-based pagination for large datasets. Use cursor-based (keyset) pagination instead.

**Why OFFSET is slow:**
```sql
SELECT * FROM events ORDER BY created_at DESC LIMIT 20 OFFSET 10000;
-- Must scan and discard 10,000 rows before returning results
```

**Cursor-based approach:**
```sql
SELECT * FROM events
WHERE created_at < '2024-01-15T10:30:00Z'
ORDER BY created_at DESC
LIMIT 20;
-- Jumps directly to the right place via index
```

**Python implementation:**
```python
async def get_events_page(session, cursor_time=None, limit=20):
query = select(Event).order_by(Event.created_at.desc())
if cursor_time:
query = query.where(Event.created_at < cursor_time)
return await session.execute(query.limit(limit))
```

**Trade-offs:**
- Cannot jump to arbitrary page numbers
- Requires passing cursor to client
- Much faster for deep pagination

安全审计

低风险
v5 • 1/21/2026

Static analysis flagged 78 potential issues but all are false positives. The scanner misidentified SQL keywords as cryptographic code and markdown code fences as shell execution. This is a legitimate PostgreSQL performance optimization skill containing documentation and example queries. Risk factors are standard for documentation skills that include code examples.

2
已扫描文件
1,166
分析行数
0
发现项
5
审计总数
未发现安全问题
审计者: claude 查看审计历史 →

质量评分

38
架构
100
可维护性
87
内容
20
社区
90
安全
91
规范符合性

你能构建什么

느린 애플리케이션 쿼리 디버깅

PostgreSQL 진단 도구와 EXPLAIN 분석을 사용하여 애플리케이션 쿼리의 성능 병목 현상을 식별하고 수정합니다.

확장 가능한 데이터베이스 스키마 설계

높은 처리량의 데이터베이스 워크로드를 위한 인덱싱 전략, 파티셔닝 및 비정규화 패턴을 적용합니다.

배치 작업 최적화

SKIP LOCKED를 사용한 배치 패턴으로 잠금이나 타임아웃 없이 대용량 데이터셋을 효율적으로 처리합니다.

试试这些提示

빠른 쿼리 분석
My PostgreSQL query is slow. Analyze and optimize it:

```sql
SELECT * FROM orders WHERE user_id = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 20;
```

How can I improve this query?
인덱스 전략 설계
I need to optimize these frequently-run queries on a table with 10M+ rows:

1. SELECT * FROM products WHERE category_id = ? AND in_stock = true
2. SELECT id, name, price FROM products WHERE category_id = ? ORDER BY price ASC
3. SELECT COUNT(*) FROM products WHERE category_id = ?

Design an optimal index strategy.
페이지네이션 마이그레이션
Our API uses OFFSET pagination and it is slow for deep pages:

```python
# Current implementation
def get_events(page: int, limit: int = 20):
    offset = (page - 1) * limit
    return db.execute("SELECT * FROM events ORDER BY created_at DESC LIMIT ? OFFSET ?", limit, offset)
```

Convert this to cursor-based pagination with example code.
커넥션 풀 구성
Configure PostgreSQL connection pooling for our use case:

- Serverless Python API on Lambda (spiky traffic, ~1000 req/min)
- We see connection errors during traffic spikes
- Database has 16GB RAM, shared_buffers = 4GB

What pool settings do you recommend?

最佳实践

  • 변경 전후로 항상 EXPLAIN (ANALYZE, BUFFERS)를 사용하여 쿼리 개선 사항을 검증하세요
  • 자주 사용하는 쿼리의 힙 페치를 피하기 위해 커버링 인덱스(INCLUDE 절)를 사용하세요
  • 10만 행 이상의 테이블에서는 OFFSET 대신 커서 기반 페이지네이션을 구현하세요

避免

  • 성능이 중요한 쿼리에서 SELECT * 사용 - 필요한 컬럼만 지정하세요
  • 배치 처리 없이 대규모 UPDATE 또는 DELETE 작업 실행 - 잠금 및 타임아웃을 유발합니다
  • 동시 배치 처리에서 FOR UPDATE SKIP LOCKED 패턴 생략

常见问题

이 스킬이 내 데이터베이스에 대해 쿼리를 실행하나요?
아니요. 이 스킬은 패턴, 코드 예제 및 지침을 제공합니다. 권장 사항을 검토한 후 SQL 명령을 직접 실행해야 합니다.
프로덕션에서 어떤 쿼리가 느린지 어떻게 식별하나요?
pg_stat_statements 확장을 활성화하고 쿼리하여 평균 실행 시간별로 가장 느린 쿼리를 찾으세요. 이 스킬에는 사용할 정확한 SQL이 포함되어 있습니다.
CREATE INDEX와 CREATE INDEX CONCURRENTLY의 차이점은 무엇인가요?
CONCURRENTLY는 테이블에 대한 쓰기를 차단하지 않고 인덱스를 생성합니다. 프로덕션에서 사용하세요. 일반 CREATE INDEX는 인덱스 생성 중 테이블 쓰기를 잠급니다.
테이블 파티셔닝은 언제 사용해야 하나요?
테이블이 1천만 행을 초과하고 자연스러운 파티션 키(날짜, 카테고리)가 있을 때 파티셔닝을 사용하세요. 파티셔닝은 쿼리 성능을 향상시키고 오래된 데이터 삭제를 훨씬 빠르게 만듭니다.
읽기 복제본과 캐싱 중 어떻게 선택하나요?
읽기 복제본을 사용하여 여러 연결에서 쿼리 처리량을 확장하세요. 자주 읽지만 거의 변경되지 않는 데이터에는 캐싱을 사용하세요. 두 전략은 서로 보완적입니다.
서버리스에 가장 적합한 커넥션 풀 설정은 무엇인가요?
지속적인 연결이 없는 서버리스/Lambda의 경우 NullPool(요청당 새 연결)을 사용하세요. 장기 실행 서비스의 경우 적절한 pool_size 및 max_overflow 값으로 AsyncAdaptedQueuePool을 사용하세요.

开发者详情

文件结构

📄 SKILL.md