databases-architecture-skill
Master database design (SQL, NoSQL), system architecture, API design (REST, GraphQL), and building scalable systems. Learn PostgreSQL, MongoDB, system design patterns, and enterprise architectures.
What this skill does
# Databases & Architecture Skill
Complete guide to designing databases, systems, and APIs that scale.
## Quick Start
### Learning Path
```
Data → Schema → APIs → Architecture
↓ ↓ ↓ ↓
SQL Normalize REST Microservices
NoSQL Indexes GraphQL Patterns
```
### Get Started in 5 Steps
1. **SQL Fundamentals** (2-3 weeks)
- SELECT, INSERT, UPDATE, DELETE
- Joins and aggregations
2. **Database Design** (3-4 weeks)
- Normalization
- Entity-relationship modeling
- Indexing
3. **NoSQL Databases** (2-3 weeks)
- Document stores (MongoDB)
- Key-value (Redis)
- When to use each
4. **API Design** (3-4 weeks)
- REST principles
- GraphQL basics
- Error handling
5. **System Architecture** (ongoing)
- Scalability patterns
- Caching strategies
- Distributed systems
---
## SQL Databases
### **SQL Fundamentals**
```sql
-- CREATE TABLE
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE,
age INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- INSERT
INSERT INTO users (name, email, age)
VALUES ('Alice', '[email protected]', 25);
-- SELECT (basic)
SELECT * FROM users;
SELECT name, email FROM users;
-- WHERE (filtering)
SELECT * FROM users WHERE age > 25;
SELECT * FROM users WHERE age >= 25 AND age <= 35;
-- LIKE (pattern matching)
SELECT * FROM users WHERE name LIKE 'A%'; -- Starts with A
-- ORDER BY (sorting)
SELECT * FROM users ORDER BY age DESC; -- Highest first
-- LIMIT (pagination)
SELECT * FROM users LIMIT 10 OFFSET 20; -- Skip 20, show 10
```
### **Advanced SQL**
```sql
-- JOINS
SELECT users.name, orders.amount
FROM users
INNER JOIN orders ON users.id = orders.user_id;
-- LEFT JOIN (include nulls)
SELECT users.name, COUNT(orders.id) as order_count
FROM users
LEFT JOIN orders ON users.id = orders.user_id
GROUP BY users.id, users.name;
-- GROUP BY & AGGREGATION
SELECT age, COUNT(*) as count, AVG(salary) as avg_salary
FROM users
GROUP BY age
HAVING COUNT(*) > 5; -- Filter groups
-- Window functions
SELECT name, salary,
AVG(salary) OVER (PARTITION BY department) as dept_avg,
RANK() OVER (ORDER BY salary DESC) as salary_rank
FROM employees;
-- CTEs (Common Table Expressions)
WITH high_earners AS (
SELECT * FROM employees WHERE salary > 100000
)
SELECT department, COUNT(*) as count
FROM high_earners
GROUP BY department;
-- UPDATE
UPDATE users SET age = 26 WHERE name = 'Alice';
-- DELETE
DELETE FROM users WHERE age < 18;
```
### **Database Design**
**Normalization (Reduce data redundancy):**
```
1NF: Each column has atomic value
2NF: Remove partial dependencies
3NF: Remove transitive dependencies
BCNF: Every determinant is a candidate key
```
**Example - Poor vs Good Design:**
```sql
-- POOR (denormalized)
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(255),
course1 VARCHAR(255),
course2 VARCHAR(255),
course3 VARCHAR(255),
teacher1 VARCHAR(255),
teacher2 VARCHAR(255)
);
-- GOOD (normalized)
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE courses (
id INT PRIMARY KEY,
name VARCHAR(255),
teacher_id INT FOREIGN KEY
);
CREATE TABLE enrollments (
student_id INT FOREIGN KEY,
course_id INT FOREIGN KEY,
PRIMARY KEY (student_id, course_id)
);
```
### **Indexing & Performance**
```sql
-- Create index
CREATE INDEX idx_email ON users(email);
CREATE INDEX idx_age_salary ON users(age, salary); -- Composite
-- Analyze query performance
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- Index types
-- B-tree: General purpose (default)
-- Hash: Exact matches only
-- GiST: Geospatial, full-text search
-- BRIN: Large datasets, sequential data
-- When to index
-- ✓ Columns in WHERE clause
-- ✓ Columns in JOIN ON clause
-- ✗ Low cardinality (yes/no, status)
-- ✗ Small tables
```
### **PostgreSQL Advanced**
```sql
-- JSONB (JSON with indexing)
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
metadata JSONB
);
INSERT INTO products VALUES (1, 'Laptop', '{"color": "silver", "specs": {"cpu": "M1"}}');
-- Query JSONB
SELECT * FROM products WHERE metadata->>'color' = 'silver';
SELECT * FROM products WHERE metadata->'specs'->>'cpu' = 'M1';
-- Array columns
CREATE TABLE tags (
id SERIAL PRIMARY KEY,
article_id INT,
tags TEXT[]
);
SELECT * FROM tags WHERE 'database' = ANY(tags);
-- Full-text search
CREATE TABLE articles (
id SERIAL PRIMARY KEY,
title VARCHAR(255),
content TEXT,
search_vector tsvector
);
UPDATE articles SET search_vector = to_tsvector('english', title || ' ' || content);
SELECT * FROM articles WHERE search_vector @@ to_tsquery('database');
```
---
## NoSQL Databases
### **MongoDB Document Storage**
```javascript
// Insert documents
db.users.insertOne({
_id: ObjectId(),
name: "Alice",
email: "[email protected]",
age: 25,
tags: ["developer", "python"],
address: {
street: "123 Main St",
city: "New York",
zip: "10001"
}
});
// Query documents
db.users.find({ name: "Alice" });
db.users.find({ age: { $gt: 25 } }); // Greater than
db.users.find({ tags: "python" }); // Array contains
// Update
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
);
db.users.updateOne(
{ _id: ObjectId(...) },
{ $push: { tags: "javascript" } } // Add to array
);
// Aggregation pipeline
db.users.aggregate([
{ $match: { age: { $gt: 20 } } },
{ $group: { _id: null, avg_age: { $avg: "$age" } } },
{ $sort: { avg_age: -1 } }
]);
// Indexes
db.users.createIndex({ email: 1 });
db.users.createIndex({ name: 1, age: 1 });
db.users.createIndex({ search: "text" }); // Full-text search
```
### **Redis Caching**
```python
import redis
r = redis.Redis(host='localhost', port=6379)
# Strings
r.set('user:1:name', 'Alice')
r.get('user:1:name') # b'Alice'
r.incr('page:views') # Increment counter
# TTL (Time to live)
r.setex('token:xyz', 3600, 'valid') # Expires in 1 hour
# Lists
r.lpush('queue:jobs', 'job1', 'job2')
r.rpop('queue:jobs') # Dequeue
r.llen('queue:jobs') # Length
# Sets
r.sadd('tags:post:1', 'python', 'database', 'backend')
r.smembers('tags:post:1')
r.sismember('tags:post:1', 'python') # Is member?
# Hashes
r.hset('user:1', mapping={'name': 'Alice', 'email': '[email protected]'})
r.hgetall('user:1')
# Pub/Sub
r.publish('channel:notifications', 'New message')
# Transactions
pipe = r.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.execute()
```
---
## API Design
### **REST API Best Practices**
```
HTTP Methods:
GET - Retrieve resource (safe, idempotent)
POST - Create resource
PUT - Replace entire resource (idempotent)
PATCH - Partial update
DELETE - Remove resource (idempotent)
Status Codes:
200 OK - Success
201 Created - Resource created
204 No Content - Success, no body
400 Bad Request - Client error
401 Unauthorized - Auth required
403 Forbidden - Not allowed
404 Not Found - Resource missing
500 Internal Server Error
```
**Resource URLs:**
```
GET /api/users # List all
GET /api/users/:id # Get one
POST /api/users # Create
PUT /api/users/:id # Update (full)
PATCH /api/users/:id # Update (partial)
DELETE /api/users/:id # Delete
// Nested resources
GET /api/users/:id/posts # User's posts
POST /api/users/:id/posts # Create post for user
```
**Request/Response Example:**
```json
POST /api/users
Content-Type: application/json
{
"name": "Alice",
"email": "[email protected]",
"age": 25
}
Response (201 Created):
{
"id": 123,
"name": "Alice",
"email": "[email protected]",
"age": 25,
"created_at": "2024-01-15T10:30:00Z"
}
```
### **GraphQL**
```graphql
# Schema
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
type Query {
user(id: ID!): User
users(limit: Int): [User!]!
post(id: ID!): Post
}
typRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.