backend-patterns
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, NestJS, FastAPI, and Next.js API routes.
What this skill does
# Backend Development Patterns
Backend architecture patterns and best practices for scalable server-side applications.
## Framework-Specific Guidelines
When working with specific frameworks, combine this skill with framework-specific skills:
| Framework | Additional Skill | When to Use |
| --------------- | ----------------------------- | ---------------------------------------------------------------- |
| **NestJS** | `nestjs-best-practices` skill | Modules, Controllers, Providers, Guards, Interceptors, Pipes, DI |
| **FastAPI** | `fastapi-templates` skill | Routes, Decorators, DI, GraphQL, Microservices |
| **Next.js API** | This skill only | Serverless API routes |
### NestJS Integration
When using **NestJS**, the patterns in this skill should be adapted to NestJS conventions:
| Generic Pattern | NestJS Implementation |
| ------------------ | ------------------------------------------------------------ |
| Repository Pattern | Use `@Injectable()` repositories with DI |
| Service Layer | Use `@Injectable()` services |
| Middleware | Use NestJS `@Injectable()` middleware or Guards/Interceptors |
| Error Handling | Use Exception Filters (`@Catch()`) |
| Validation | Use Pipes with `class-validator` |
| Auth Middleware | Use Guards (`@UseGuards()`) |
| Rate Limiting | Use `@nestjs/throttler` module |
**Example - NestJS Repository Pattern:**
```typescript
// NestJS style with dependency injection
@Injectable()
export class MarketRepository {
constructor(
@InjectRepository(Market)
private marketRepo: Repository<Market>,
) {}
async findAll(filters?: MarketFilters): Promise<Market[]> {
const query = this.marketRepo.createQueryBuilder('market');
if (filters?.status) {
query.where('market.status = :status', { status: filters.status });
}
return query.getMany();
}
}
// Inject into service
@Injectable()
export class MarketService {
constructor(private marketRepo: MarketRepository) {}
}
```
**Example - NestJS Error Handling:**
```typescript
// Exception filter instead of middleware error handler
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
if (exception instanceof HttpException) {
return response.status(exception.getStatus()).json({
success: false,
error: exception.message,
});
}
return response.status(500).json({
success: false,
error: 'Internal server error',
});
}
}
```
> **Tip**: For NestJS-specific decorators, modules, and advanced features (GraphQL, Microservices, WebSockets), refer to the **nestjs skill** for detailed documentation.
## API Design Patterns
### RESTful API Structure
```typescript
// ✅ Resource-based URLs
GET /api/markets # List resources
GET /api/markets/:id # Get single resource
POST /api/markets # Create resource
PUT /api/markets/:id # Replace resource
PATCH /api/markets/:id # Update resource
DELETE /api/markets/:id # Delete resource
// ✅ Query parameters for filtering, sorting, pagination
GET /api/markets?status=active&sort=volume&limit=20&offset=0
```
### Repository Pattern
```typescript
// Abstract data access logic
interface MarketRepository {
findAll(filters?: MarketFilters): Promise<Market[]>;
findById(id: string): Promise<Market | null>;
create(data: CreateMarketDto): Promise<Market>;
update(id: string, data: UpdateMarketDto): Promise<Market>;
delete(id: string): Promise<void>;
}
class SupabaseMarketRepository implements MarketRepository {
async findAll(filters?: MarketFilters): Promise<Market[]> {
let query = supabase.from('markets').select('*');
if (filters?.status) {
query = query.eq('status', filters.status);
}
if (filters?.limit) {
query = query.limit(filters.limit);
}
const { data, error } = await query;
if (error) throw new Error(error.message);
return data;
}
// Other methods...
}
```
### Service Layer Pattern
```typescript
// Business logic separated from data access
class MarketService {
constructor(private marketRepo: MarketRepository) {}
async searchMarkets(query: string, limit: number = 10): Promise<Market[]> {
// Business logic
const embedding = await generateEmbedding(query);
const results = await this.vectorSearch(embedding, limit);
// Fetch full data
const markets = await this.marketRepo.findByIds(results.map((r) => r.id));
// Sort by similarity
return markets.sort((a, b) => {
const scoreA = results.find((r) => r.id === a.id)?.score || 0;
const scoreB = results.find((r) => r.id === b.id)?.score || 0;
return scoreA - scoreB;
});
}
private async vectorSearch(embedding: number[], limit: number) {
// Vector search implementation
}
}
```
### Middleware Pattern
```typescript
// Request/response processing pipeline
export function withAuth(handler: NextApiHandler): NextApiHandler {
return async (req, res) => {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
try {
const user = await verifyToken(token);
req.user = user;
return handler(req, res);
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
}
// Usage
export default withAuth(async (req, res) => {
// Handler has access to req.user
});
```
## Database Patterns
### Query Optimization
```typescript
// ✅ GOOD: Select only needed columns
const { data } = await supabase
.from('markets')
.select('id, name, status, volume')
.eq('status', 'active')
.order('volume', { ascending: false })
.limit(10);
// ❌ BAD: Select everything
const { data } = await supabase.from('markets').select('*');
```
### N+1 Query Prevention
```typescript
// ❌ BAD: N+1 query problem
const markets = await getMarkets();
for (const market of markets) {
market.creator = await getUser(market.creator_id); // N queries
}
// ✅ GOOD: Batch fetch
const markets = await getMarkets();
const creatorIds = markets.map((m) => m.creator_id);
const creators = await getUsers(creatorIds); // 1 query
const creatorMap = new Map(creators.map((c) => [c.id, c]));
markets.forEach((market) => {
market.creator = creatorMap.get(market.creator_id);
});
```
### Transaction Pattern
```typescript
async function createMarketWithPosition(
marketData: CreateMarketDto,
positionData: CreatePositionDto
) {
// Use Supabase transaction
const { data, error } = await supabase.rpc('create_market_with_position', {
market_data: marketData,
position_data: positionData
})
if (error) throw new Error('Transaction failed')
return data
}
// SQL function in Supabase
CREATE OR REPLACE FUNCTION create_market_with_position(
market_data jsonb,
position_data jsonb
)
RETURNS jsonb
LANGUAGE plpgsql
AS $$
BEGIN
-- Start transaction automatically
INSERT INTO markets VALUES (market_data);
INSERT INTO positions VALUES (position_data);
RETURN jsonb_build_object('success', true);
EXCEPTION
WHEN OTHERS THEN
-- Rollback happens automatically
RETURN jsonb_build_object('success', false, 'error', SQLERRM);
END;
$$;
```
## Caching Strategies
### Redis Caching Layer
```typescript
class CachedMarketRepository implements MarketRepository {
constructor(
private baseRepo: MarketRepository,
private redis: RedisClient,Related 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.