Creator · affaan-m
Last updated · Sep 7, 2026
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access.
Creator · affaan-m
Last updated · Sep 7, 2026
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access.
Creator · affaan-m
Last updated · Sep 7, 2026
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access.
Creator · affaan-m
Last updated · Sep 7, 2026
Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access.
Sandbox only
Install targets
Codex install prompt
Install the "backend-patterns" agent skill from https://github.com/affaan-m/ECC/tree/main/.agents/skills/backend-patterns. Read its SKILL.md or equivalent instructions first, install only the files needed for this workspace, and summarize any required setup before using it. Skill purpose: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. After the install attempt, report the result to https://www.openagentskill.com/api/agent/outcome with POST JSON {"event_id":"install_<unique-id>","skill_slug":"affaan-m-backend-patterns","task":"Install backend-patterns","agent":"codex","outcome":"success","install_used":true}. Replace event_id with a unique value and outcome with success or failed. Report success only after the skill is installed and a minimal verification passes.Supply asset profile
Code review, repo analysis, testing, CI, GitHub, DevOps, and developer workflow skills.
Scenario
Coding agents
I need a coding agent that can understand a repository, edit code, and review pull requests.
Agent fit
Claude Code + CLI + Codex
Codex, Claude Code, Cursor, CLI, or custom agents.
Install
Ready
npx skills add affaan-m/ECC --skill backend-patterns
Maintenance
fresh
Pushed today
Risk
Needs review
Dependency or permission surface needs review
GitHub quality
252K
95/100 Quality · 82/100 Trust
Coverage tags
Review notes
Dependency or permission surface needs review · Permission surface may require sandboxing
Agent adoption scorecard
These scores combine public repository metadata, OpenAgentSkill review signals, maintenance freshness, and install readiness. They are a shortlist signal, not a replacement for human review.
Quality
ExcellentHigh-confidence pick with strong adoption and healthy maintenance signals.
Trust
Sandbox onlyUseful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
Audit
Needs reviewA machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
OpenAgentSkill Trust Score v5
Run only in a sandbox and compare close alternatives before using it for real work.
Stars
252K GitHub stars
Repo activity
252K stars, 38K forks
Maintenance
Pushed today
License
MIT
Install
npx skills add affaan-m/ECC --skill backend-patterns
Install safety
Agent-readable metadata
Use this block or the embedded JSON to decide whether an agent should install this skill, choose an alternative, or ask for human review first.
Suited tasks
Suited agents
Install decision
Trust and risk
Outcome loop
Install command
npx skills add affaan-m/ECC --skill backend-patternsDo not use when
Alternative
175.1K Stars
npx skills add anthropics/skills --skill frontend-design
Alternative
85.2K Stars
npx skills add Leonxlnx/taste-skill --skill design-taste-frontend
Alternative
1.8K Stars
npx skills add Alisa0808/vox-director --skill vox-director
Alternative
175.1K Stars
npx skills add anthropics/skills --skill canvas-design
Agent safety v2
Sparse or mixed signals. Useful for discovery, but not for autonomous installation.
Test manually in an isolated workspace and compare against safer alternatives.
medium
Skill likely fetches remote pages, APIs, repositories, or external services.
medium
Skill may read or write project files, documents, generated artifacts, or local workspace state.
high
Skill metadata references credentials, tokens, environment variables, or secret-bearing workflows.
medium
Skill may inspect schemas, query databases, or work with persistent stores.
Agent resolve plan
The Resolve API returns the selected skill, alternatives, safety policy, audit notes, install target, and copy-paste prompt an agent can follow without scraping this page.
Open JSON
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Resolve text
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium&format=text
Install handoff
/api/skills/affaan-m-backend-patterns/install
Agent should check
Copy prompt
Task: Use backend-patterns in this workspace.
Resolve first: https://www.openagentskill.com/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Review install handoff: https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install
Install command: npx skills add affaan-m/ECC --skill backend-patterns
Before running it, summarize audit warnings, required permissions, and the fallback skill if install is risky.Agent handoff
Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.
Install handoff
/api/skills/affaan-m-backend-patterns/install
LLM text format
/api/skills/affaan-m-backend-patterns/install?format=text
Find alternatives
/api/skills/search?q=backend-patterns&limit=3
Agent prompt
Use backend-patterns for this task. Review https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install, then install with: npx skills add affaan-m/ECC --skill backend-patternsRegistry metadata
This page exposes the same decision, trust, audit, use-case, and install signals through the Registry API, so agents can rank this skill without scraping the UI.
Manifest
/api/registry/manifest/affaan-m-backend-patterns
LLM text
/api/registry/manifest/affaan-m-backend-patterns?format=text
Install alias
/api/registry/install/affaan-m-backend-patterns
Recommend
/api/registry/recommend?task=Use%20backend-patterns%20in%20an%20agent%20workflow&limit=3
Agent fit
Coding agents
Use-case tags
Platforms
Claude Code
Audit report
A machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
Agent decision cockpit
Use this as a leading candidate, then validate the README and install path in your own agent stack.
Role in stack
Primary pick
Primary fit
Coding agents
Trust label
Production-ready
Install path
Command ready
Use when
Evidence
review first
Implementation path
Trust profile
Useful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
GitHub adoption
PASS252K GitHub stars
Stars/forks activity
PASS252K stars, 38K forks; issue activity unavailable in current metadata
Recent maintenance
PASSPushed today
License clarity
PASSMIT
Good signals
Review before install
Recommended action
Run only in a sandbox and compare close alternatives before using it for real work.
Quality profile
High-confidence pick with strong adoption and healthy maintenance signals.
Workflow fit
Build and ship code
I need a coding agent that can understand a repository, edit code, and review pull requests.
Search private knowledge
I need my agent to build a RAG workflow over documents and retrieve reliable context.
Investigate faster
I need my agent to research a topic, compare sources, and produce a concise report.
Workflow fit
Inspect, patch, and verify code
A workflow for software agents that inspect repositories, review pull requests, generate tests, and turn findings into shippable patches.
Ingest, retrieve, and cite
A workflow for document-heavy agents that ingest files, create searchable knowledge, retrieve relevant context, and answer with grounded sources.
Find, compare, and synthesize
A workflow for agents that gather sources, compare claims, summarize long material, and draft useful research briefs.
Alternative shortlist
Similar skills that may fit this task.
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
--- name: backend-patterns description: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. ---
# Backend Development Patterns
Backend architecture patterns and best practices for scalable server-side applications.
## When to Activate
- Designing REST or GraphQL API endpoints - Implementing repository, service, or controller layers - Optimizing database queries (N+1, indexing, connection pooling) - Adding caching (Redis, in-memory, HTTP cache headers) - Setting up background jobs or async processing - Structuring error handling and validation for APIs - Building middleware (auth, logging, rate limiting)
## API Design Patterns
### RESTful API Structure
```typescript // PASS: 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
// PASS: 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 // PASS: 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)
// FAIL: BAD: Select everything const { data } = await supabase .from('markets') .select('*') ```
### N+1 Query Prevention
```typescript // FAIL: BAD: N+1 query problem const markets = await getMarkets() for (const market of markets) { market.creator = await getUser(market.creator_id) // N queries }
// PASS: 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 ) {}
async findById(id: string): Promise<Market | null> { // Check cache first const cached = await this.redis.get(`market:${id}`)
if (cached) { return JSON.parse(cached) }
// Cache miss - fetch from database const market = await this.baseRepo.findById(id)
if (market) { // Cache for 5 minutes await this.redis.setex(`market:${id}`, 300, JSON.stringify(market)) }
return market }
async invalidateCache(id: string): Promise<void> { await this.redis.del(`market:${id}`) } } ```
### Cache-Aside Pattern
```typescript async function getMarketWithCache(id: string): Promise<Market> { const cacheKey = `market:${id}`
// Try cache const cached = await redis.get(cacheKey) if (cached) return JSON.parse(cached)
// Cache miss - fetch from DB const market = await db.markets.findUnique({ where: { id } })
if (!market) throw new Error('Market not found')
// Update cache await redis.setex(cacheKey, 300, JSON.stringify(market))
return market } ```
## Error Handling Patterns
### Centralized Error Handler
```typescript class ApiError extends Error { constructor( public statusCode: number, public message: string, public isOperational = true ) { super(message) Object.setPrototypeOf(this, ApiError.prototype) } }
export function errorHandler(error: unknown, req: Request): Response { if (error instanceof ApiError) { return NextResponse.json({ success: false, error: error.message }, { status: error.statusCode }) }
if (error instanceof z.ZodError) { return NextResponse.json({ success: false, error: 'Validation failed', details: error.errors }, { status: 400 }) }
// Log unexpected errors console.error('Unexpected error:', error)
return NextResponse.json({ success: false, error: 'Internal server error' }, { status: 500 }) }
// Usage export async function GET(request: Request) { try { const data = await fetchData() return NextResponse.json({ success: true, data }) } catch (error) { return errorHandler(error, request) } } ```
### Retry with Exponential Backoff
```typescript async function fetchWithRetry<T>( fn: () => Promise<T>, maxRetries = 3 ): Promise<T> { let lastError: Error
for (let i = 0; i < maxRetries; i++) { try { return await fn() } catch (error) { lastError = error as Error
if (i < maxRetries - 1) { // Exponential backoff: 1s, 2s, 4s const delay = Math.pow(2, i) * 1000 await new Promise(resolve => setTimeout(resolve, delay)) } } }
throw lastError! }
// Usage const data = await fetchWithRetry(() => fetchFromAPI()) ```
## Authentication & Authorization
### JWT Token Validation
```typescript import jwt from 'jsonwebtoken'
interface JWTPayload { userId: string email: string role: 'admin' | 'user' }
export function verifyToken(token: string): JWTPayload { try { const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload return payload } catch (error) { throw new ApiError(401, 'Invalid token') } }
export async function requireAuth(request: Request) { const token = request.headers.get('authorization')?.replace('Bearer ', '')
if (!token) { throw new ApiError(401, 'Missing authorization token') }
return verifyToken(token) }
// Usage in API route export async function GET(request: Request) { const user = await requireAuth(request)
const data = await getDataForUser(user.userId)
return NextResponse.json({ success: true, data }) } ```
### Role-Based Access Control
```typescript type Permission = 'read' | 'write' | 'delete' | 'admin'
interface User { id: string role: 'admin' | 'moderator' | 'user' }
const rolePermissions: Record<User['role'], Permission[]> = { admin: ['read', 'write', 'delete', 'admin'], moderator: ['read', 'write', 'delete'], user: ['read', 'write'] }
export function hasPermission(user: User, permission: Permission): boolean { return rolePermissions[user.role].includes(permission) }
export function requirePermission(permission: Permission) { return (handler: (request: Request, user: User) => Promise<Response>) => { return async (request: Request) => { const user = await requireAuth(request)
if (!hasPermission(user, permission)) { throw new ApiError(403, 'Insufficient permissions') }
return handler(request, user) } } }
// Usage - HOF wraps the handler export const DELETE = requirePermission('delete')( async (request: Request, user: User) => { // Handler receives authenticated user with verified permission return new Response('Deleted', { status: 200 }) } ) ```
## Rate Limiting
### Simple In-Memory Rate Limiter
```typescript class RateLimiter { private requests = new Map<string, number[]>()
async checkLimit( identifier: string, maxRequests: number, windowMs: number ): Promise<boolean> { const now = Date.now() const requests = this.requests.get(identifier) || []
// Remove old requests outside window const recentRequests = requests.filter(time => now - time < windowMs)
if (recentRequests.length >= maxRequests) { return false // Rate limit exceeded }
// Add current request recentRequests.push(now) this.requests.set(identifier, recentRequests)
return true } }
const limiter = new RateLimiter()
export async function GET(request: Request) { const ip = request.headers.get('x-forwarded-for') || 'unknown'
const allowed = await limiter.checkLimit(ip, 100, 60000) // 100 req/min
if (!allowed) { return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 }) }
// Continue with request } ```
## Background Jobs & Queues
### Simple Queue Pattern
```typescript class JobQueue<T> { private queue: T[] = [] private processing = false
async add(job: T): Promise<void> { this.queue.push(job)
if (!this.processing) { this.process() } }
private async process(): Promise<void> { this.processing = true
while (this.queue.length > 0) { const job = this.queue.shift()!
try { await this.execute(job) } catch (error) { console.error('Job failed:', error) } }
this.processing
Source provenance
Decision snapshot
252,296 GitHub stars
Audit
Install and adoption review
Agent-proven evidence
Outcome reports after resolve, review, install, and one narrow run.
No agent outcome data yet. The first agent run can report success, setup needs, risk blocks, failure, or not-relevant through /api/agent/outcome.
Install
Free and open source. Review the report before installing into production agents.
Growth loop
Scenario-led draft for backend-patterns, ready for a manual X post.
backend-patterns: Backend architecture patterns, API design, database optimization, and server-side best practi... 252.3K stars https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x
Listing + install path for backend-patterns: https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x Install: npx skills add affaan-m/ECC --skill backend-patterns
Listing source
This listing was indexed from public sources and is not marked official until a maintainer claim is approved.
Attribution links to the public repository or creator profile. Creators can claim the listing to update ownership signals.
Claim this skillOwner claim
This Registry indexed listing is attributed to affaan-m but is not marked official yet. Claim it to add a verified owner signal and make future launch, install, and audit updates easier to trust.
Creator backlink kit
Show the canonical listing, current trust and audit signals, and real Agent-Proven evidence where developers evaluate the repository.
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns/audit)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)affaan-m
@affaan-m
Share whether this skill looks useful for your agent workflow. Aggregated feedback improves rankings over time.
Sandbox only
Frontend Design
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
175.1K StarsTaste Skill: Anti-Slop Frontend
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
85.2K StarsVox Director
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
1.8K StarsCanvas Design
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
175.1K StarsSandbox only
Install targets
Codex install prompt
Install the "backend-patterns" agent skill from https://github.com/affaan-m/ECC/tree/main/.agents/skills/backend-patterns. Read its SKILL.md or equivalent instructions first, install only the files needed for this workspace, and summarize any required setup before using it. Skill purpose: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. After the install attempt, report the result to https://www.openagentskill.com/api/agent/outcome with POST JSON {"event_id":"install_<unique-id>","skill_slug":"affaan-m-backend-patterns","task":"Install backend-patterns","agent":"codex","outcome":"success","install_used":true}. Replace event_id with a unique value and outcome with success or failed. Report success only after the skill is installed and a minimal verification passes.Supply asset profile
Code review, repo analysis, testing, CI, GitHub, DevOps, and developer workflow skills.
Scenario
Coding agents
I need a coding agent that can understand a repository, edit code, and review pull requests.
Agent fit
Claude Code + CLI + Codex
Codex, Claude Code, Cursor, CLI, or custom agents.
Install
Ready
npx skills add affaan-m/ECC --skill backend-patterns
Maintenance
fresh
Pushed today
Risk
Needs review
Dependency or permission surface needs review
GitHub quality
252K
95/100 Quality · 82/100 Trust
Coverage tags
Review notes
Dependency or permission surface needs review · Permission surface may require sandboxing
Agent adoption scorecard
These scores combine public repository metadata, OpenAgentSkill review signals, maintenance freshness, and install readiness. They are a shortlist signal, not a replacement for human review.
Quality
ExcellentHigh-confidence pick with strong adoption and healthy maintenance signals.
Trust
Sandbox onlyUseful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
Audit
Needs reviewA machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
OpenAgentSkill Trust Score v5
Run only in a sandbox and compare close alternatives before using it for real work.
Stars
252K GitHub stars
Repo activity
252K stars, 38K forks
Maintenance
Pushed today
License
MIT
Install
npx skills add affaan-m/ECC --skill backend-patterns
Install safety
Agent-readable metadata
Use this block or the embedded JSON to decide whether an agent should install this skill, choose an alternative, or ask for human review first.
Suited tasks
Suited agents
Install decision
Trust and risk
Outcome loop
Install command
npx skills add affaan-m/ECC --skill backend-patternsDo not use when
Alternative
175.1K Stars
npx skills add anthropics/skills --skill frontend-design
Alternative
85.2K Stars
npx skills add Leonxlnx/taste-skill --skill design-taste-frontend
Alternative
1.8K Stars
npx skills add Alisa0808/vox-director --skill vox-director
Alternative
175.1K Stars
npx skills add anthropics/skills --skill canvas-design
Agent safety v2
Sparse or mixed signals. Useful for discovery, but not for autonomous installation.
Test manually in an isolated workspace and compare against safer alternatives.
medium
Skill likely fetches remote pages, APIs, repositories, or external services.
medium
Skill may read or write project files, documents, generated artifacts, or local workspace state.
high
Skill metadata references credentials, tokens, environment variables, or secret-bearing workflows.
medium
Skill may inspect schemas, query databases, or work with persistent stores.
Agent resolve plan
The Resolve API returns the selected skill, alternatives, safety policy, audit notes, install target, and copy-paste prompt an agent can follow without scraping this page.
Open JSON
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Resolve text
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium&format=text
Install handoff
/api/skills/affaan-m-backend-patterns/install
Agent should check
Copy prompt
Task: Use backend-patterns in this workspace.
Resolve first: https://www.openagentskill.com/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Review install handoff: https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install
Install command: npx skills add affaan-m/ECC --skill backend-patterns
Before running it, summarize audit warnings, required permissions, and the fallback skill if install is risky.Agent handoff
Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.
Install handoff
/api/skills/affaan-m-backend-patterns/install
LLM text format
/api/skills/affaan-m-backend-patterns/install?format=text
Find alternatives
/api/skills/search?q=backend-patterns&limit=3
Agent prompt
Use backend-patterns for this task. Review https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install, then install with: npx skills add affaan-m/ECC --skill backend-patternsRegistry metadata
This page exposes the same decision, trust, audit, use-case, and install signals through the Registry API, so agents can rank this skill without scraping the UI.
Manifest
/api/registry/manifest/affaan-m-backend-patterns
LLM text
/api/registry/manifest/affaan-m-backend-patterns?format=text
Install alias
/api/registry/install/affaan-m-backend-patterns
Recommend
/api/registry/recommend?task=Use%20backend-patterns%20in%20an%20agent%20workflow&limit=3
Agent fit
Coding agents
Use-case tags
Platforms
Claude Code
Audit report
A machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
Agent decision cockpit
Use this as a leading candidate, then validate the README and install path in your own agent stack.
Role in stack
Primary pick
Primary fit
Coding agents
Trust label
Production-ready
Install path
Command ready
Use when
Evidence
review first
Implementation path
Trust profile
Useful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
GitHub adoption
PASS252K GitHub stars
Stars/forks activity
PASS252K stars, 38K forks; issue activity unavailable in current metadata
Recent maintenance
PASSPushed today
License clarity
PASSMIT
Good signals
Review before install
Recommended action
Run only in a sandbox and compare close alternatives before using it for real work.
Quality profile
High-confidence pick with strong adoption and healthy maintenance signals.
Workflow fit
Build and ship code
I need a coding agent that can understand a repository, edit code, and review pull requests.
Search private knowledge
I need my agent to build a RAG workflow over documents and retrieve reliable context.
Investigate faster
I need my agent to research a topic, compare sources, and produce a concise report.
Workflow fit
Inspect, patch, and verify code
A workflow for software agents that inspect repositories, review pull requests, generate tests, and turn findings into shippable patches.
Ingest, retrieve, and cite
A workflow for document-heavy agents that ingest files, create searchable knowledge, retrieve relevant context, and answer with grounded sources.
Find, compare, and synthesize
A workflow for agents that gather sources, compare claims, summarize long material, and draft useful research briefs.
Alternative shortlist
Similar skills that may fit this task.
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
--- name: backend-patterns description: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. ---
# Backend Development Patterns
Backend architecture patterns and best practices for scalable server-side applications.
## When to Activate
- Designing REST or GraphQL API endpoints - Implementing repository, service, or controller layers - Optimizing database queries (N+1, indexing, connection pooling) - Adding caching (Redis, in-memory, HTTP cache headers) - Setting up background jobs or async processing - Structuring error handling and validation for APIs - Building middleware (auth, logging, rate limiting)
## API Design Patterns
### RESTful API Structure
```typescript // PASS: 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
// PASS: 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 // PASS: 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)
// FAIL: BAD: Select everything const { data } = await supabase .from('markets') .select('*') ```
### N+1 Query Prevention
```typescript // FAIL: BAD: N+1 query problem const markets = await getMarkets() for (const market of markets) { market.creator = await getUser(market.creator_id) // N queries }
// PASS: 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 ) {}
async findById(id: string): Promise<Market | null> { // Check cache first const cached = await this.redis.get(`market:${id}`)
if (cached) { return JSON.parse(cached) }
// Cache miss - fetch from database const market = await this.baseRepo.findById(id)
if (market) { // Cache for 5 minutes await this.redis.setex(`market:${id}`, 300, JSON.stringify(market)) }
return market }
async invalidateCache(id: string): Promise<void> { await this.redis.del(`market:${id}`) } } ```
### Cache-Aside Pattern
```typescript async function getMarketWithCache(id: string): Promise<Market> { const cacheKey = `market:${id}`
// Try cache const cached = await redis.get(cacheKey) if (cached) return JSON.parse(cached)
// Cache miss - fetch from DB const market = await db.markets.findUnique({ where: { id } })
if (!market) throw new Error('Market not found')
// Update cache await redis.setex(cacheKey, 300, JSON.stringify(market))
return market } ```
## Error Handling Patterns
### Centralized Error Handler
```typescript class ApiError extends Error { constructor( public statusCode: number, public message: string, public isOperational = true ) { super(message) Object.setPrototypeOf(this, ApiError.prototype) } }
export function errorHandler(error: unknown, req: Request): Response { if (error instanceof ApiError) { return NextResponse.json({ success: false, error: error.message }, { status: error.statusCode }) }
if (error instanceof z.ZodError) { return NextResponse.json({ success: false, error: 'Validation failed', details: error.errors }, { status: 400 }) }
// Log unexpected errors console.error('Unexpected error:', error)
return NextResponse.json({ success: false, error: 'Internal server error' }, { status: 500 }) }
// Usage export async function GET(request: Request) { try { const data = await fetchData() return NextResponse.json({ success: true, data }) } catch (error) { return errorHandler(error, request) } } ```
### Retry with Exponential Backoff
```typescript async function fetchWithRetry<T>( fn: () => Promise<T>, maxRetries = 3 ): Promise<T> { let lastError: Error
for (let i = 0; i < maxRetries; i++) { try { return await fn() } catch (error) { lastError = error as Error
if (i < maxRetries - 1) { // Exponential backoff: 1s, 2s, 4s const delay = Math.pow(2, i) * 1000 await new Promise(resolve => setTimeout(resolve, delay)) } } }
throw lastError! }
// Usage const data = await fetchWithRetry(() => fetchFromAPI()) ```
## Authentication & Authorization
### JWT Token Validation
```typescript import jwt from 'jsonwebtoken'
interface JWTPayload { userId: string email: string role: 'admin' | 'user' }
export function verifyToken(token: string): JWTPayload { try { const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload return payload } catch (error) { throw new ApiError(401, 'Invalid token') } }
export async function requireAuth(request: Request) { const token = request.headers.get('authorization')?.replace('Bearer ', '')
if (!token) { throw new ApiError(401, 'Missing authorization token') }
return verifyToken(token) }
// Usage in API route export async function GET(request: Request) { const user = await requireAuth(request)
const data = await getDataForUser(user.userId)
return NextResponse.json({ success: true, data }) } ```
### Role-Based Access Control
```typescript type Permission = 'read' | 'write' | 'delete' | 'admin'
interface User { id: string role: 'admin' | 'moderator' | 'user' }
const rolePermissions: Record<User['role'], Permission[]> = { admin: ['read', 'write', 'delete', 'admin'], moderator: ['read', 'write', 'delete'], user: ['read', 'write'] }
export function hasPermission(user: User, permission: Permission): boolean { return rolePermissions[user.role].includes(permission) }
export function requirePermission(permission: Permission) { return (handler: (request: Request, user: User) => Promise<Response>) => { return async (request: Request) => { const user = await requireAuth(request)
if (!hasPermission(user, permission)) { throw new ApiError(403, 'Insufficient permissions') }
return handler(request, user) } } }
// Usage - HOF wraps the handler export const DELETE = requirePermission('delete')( async (request: Request, user: User) => { // Handler receives authenticated user with verified permission return new Response('Deleted', { status: 200 }) } ) ```
## Rate Limiting
### Simple In-Memory Rate Limiter
```typescript class RateLimiter { private requests = new Map<string, number[]>()
async checkLimit( identifier: string, maxRequests: number, windowMs: number ): Promise<boolean> { const now = Date.now() const requests = this.requests.get(identifier) || []
// Remove old requests outside window const recentRequests = requests.filter(time => now - time < windowMs)
if (recentRequests.length >= maxRequests) { return false // Rate limit exceeded }
// Add current request recentRequests.push(now) this.requests.set(identifier, recentRequests)
return true } }
const limiter = new RateLimiter()
export async function GET(request: Request) { const ip = request.headers.get('x-forwarded-for') || 'unknown'
const allowed = await limiter.checkLimit(ip, 100, 60000) // 100 req/min
if (!allowed) { return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 }) }
// Continue with request } ```
## Background Jobs & Queues
### Simple Queue Pattern
```typescript class JobQueue<T> { private queue: T[] = [] private processing = false
async add(job: T): Promise<void> { this.queue.push(job)
if (!this.processing) { this.process() } }
private async process(): Promise<void> { this.processing = true
while (this.queue.length > 0) { const job = this.queue.shift()!
try { await this.execute(job) } catch (error) { console.error('Job failed:', error) } }
this.processing
Source provenance
Decision snapshot
252,296 GitHub stars
Audit
Install and adoption review
Agent-proven evidence
Outcome reports after resolve, review, install, and one narrow run.
No agent outcome data yet. The first agent run can report success, setup needs, risk blocks, failure, or not-relevant through /api/agent/outcome.
Install
Free and open source. Review the report before installing into production agents.
Growth loop
Scenario-led draft for backend-patterns, ready for a manual X post.
backend-patterns: Backend architecture patterns, API design, database optimization, and server-side best practi... 252.3K stars https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x
Listing + install path for backend-patterns: https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x Install: npx skills add affaan-m/ECC --skill backend-patterns
Listing source
This listing was indexed from public sources and is not marked official until a maintainer claim is approved.
Attribution links to the public repository or creator profile. Creators can claim the listing to update ownership signals.
Claim this skillOwner claim
This Registry indexed listing is attributed to affaan-m but is not marked official yet. Claim it to add a verified owner signal and make future launch, install, and audit updates easier to trust.
Creator backlink kit
Show the canonical listing, current trust and audit signals, and real Agent-Proven evidence where developers evaluate the repository.
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns/audit)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)affaan-m
@affaan-m
Share whether this skill looks useful for your agent workflow. Aggregated feedback improves rankings over time.
Sandbox only
Frontend Design
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
175.1K StarsTaste Skill: Anti-Slop Frontend
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
85.2K StarsVox Director
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
1.8K StarsCanvas Design
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
175.1K StarsSandbox only
Install targets
Codex install prompt
Install the "backend-patterns" agent skill from https://github.com/affaan-m/ECC/tree/main/.agents/skills/backend-patterns. Read its SKILL.md or equivalent instructions first, install only the files needed for this workspace, and summarize any required setup before using it. Skill purpose: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. After the install attempt, report the result to https://www.openagentskill.com/api/agent/outcome with POST JSON {"event_id":"install_<unique-id>","skill_slug":"affaan-m-backend-patterns","task":"Install backend-patterns","agent":"codex","outcome":"success","install_used":true}. Replace event_id with a unique value and outcome with success or failed. Report success only after the skill is installed and a minimal verification passes.Supply asset profile
Code review, repo analysis, testing, CI, GitHub, DevOps, and developer workflow skills.
Scenario
Coding agents
I need a coding agent that can understand a repository, edit code, and review pull requests.
Agent fit
Claude Code + CLI + Codex
Codex, Claude Code, Cursor, CLI, or custom agents.
Install
Ready
npx skills add affaan-m/ECC --skill backend-patterns
Maintenance
fresh
Pushed today
Risk
Needs review
Dependency or permission surface needs review
GitHub quality
252K
95/100 Quality · 82/100 Trust
Coverage tags
Review notes
Dependency or permission surface needs review · Permission surface may require sandboxing
Agent adoption scorecard
These scores combine public repository metadata, OpenAgentSkill review signals, maintenance freshness, and install readiness. They are a shortlist signal, not a replacement for human review.
Quality
ExcellentHigh-confidence pick with strong adoption and healthy maintenance signals.
Trust
Sandbox onlyUseful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
Audit
Needs reviewA machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
OpenAgentSkill Trust Score v5
Run only in a sandbox and compare close alternatives before using it for real work.
Stars
252K GitHub stars
Repo activity
252K stars, 38K forks
Maintenance
Pushed today
License
MIT
Install
npx skills add affaan-m/ECC --skill backend-patterns
Install safety
Agent-readable metadata
Use this block or the embedded JSON to decide whether an agent should install this skill, choose an alternative, or ask for human review first.
Suited tasks
Suited agents
Install decision
Trust and risk
Outcome loop
Install command
npx skills add affaan-m/ECC --skill backend-patternsDo not use when
Alternative
175.1K Stars
npx skills add anthropics/skills --skill frontend-design
Alternative
85.2K Stars
npx skills add Leonxlnx/taste-skill --skill design-taste-frontend
Alternative
1.8K Stars
npx skills add Alisa0808/vox-director --skill vox-director
Alternative
175.1K Stars
npx skills add anthropics/skills --skill canvas-design
Agent safety v2
Sparse or mixed signals. Useful for discovery, but not for autonomous installation.
Test manually in an isolated workspace and compare against safer alternatives.
medium
Skill likely fetches remote pages, APIs, repositories, or external services.
medium
Skill may read or write project files, documents, generated artifacts, or local workspace state.
high
Skill metadata references credentials, tokens, environment variables, or secret-bearing workflows.
medium
Skill may inspect schemas, query databases, or work with persistent stores.
Agent resolve plan
The Resolve API returns the selected skill, alternatives, safety policy, audit notes, install target, and copy-paste prompt an agent can follow without scraping this page.
Open JSON
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Resolve text
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium&format=text
Install handoff
/api/skills/affaan-m-backend-patterns/install
Agent should check
Copy prompt
Task: Use backend-patterns in this workspace.
Resolve first: https://www.openagentskill.com/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Review install handoff: https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install
Install command: npx skills add affaan-m/ECC --skill backend-patterns
Before running it, summarize audit warnings, required permissions, and the fallback skill if install is risky.Agent handoff
Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.
Install handoff
/api/skills/affaan-m-backend-patterns/install
LLM text format
/api/skills/affaan-m-backend-patterns/install?format=text
Find alternatives
/api/skills/search?q=backend-patterns&limit=3
Agent prompt
Use backend-patterns for this task. Review https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install, then install with: npx skills add affaan-m/ECC --skill backend-patternsRegistry metadata
This page exposes the same decision, trust, audit, use-case, and install signals through the Registry API, so agents can rank this skill without scraping the UI.
Manifest
/api/registry/manifest/affaan-m-backend-patterns
LLM text
/api/registry/manifest/affaan-m-backend-patterns?format=text
Install alias
/api/registry/install/affaan-m-backend-patterns
Recommend
/api/registry/recommend?task=Use%20backend-patterns%20in%20an%20agent%20workflow&limit=3
Agent fit
Coding agents
Use-case tags
Platforms
Claude Code
Audit report
A machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
Agent decision cockpit
Use this as a leading candidate, then validate the README and install path in your own agent stack.
Role in stack
Primary pick
Primary fit
Coding agents
Trust label
Production-ready
Install path
Command ready
Use when
Evidence
review first
Implementation path
Trust profile
Useful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
GitHub adoption
PASS252K GitHub stars
Stars/forks activity
PASS252K stars, 38K forks; issue activity unavailable in current metadata
Recent maintenance
PASSPushed today
License clarity
PASSMIT
Good signals
Review before install
Recommended action
Run only in a sandbox and compare close alternatives before using it for real work.
Quality profile
High-confidence pick with strong adoption and healthy maintenance signals.
Workflow fit
Build and ship code
I need a coding agent that can understand a repository, edit code, and review pull requests.
Search private knowledge
I need my agent to build a RAG workflow over documents and retrieve reliable context.
Investigate faster
I need my agent to research a topic, compare sources, and produce a concise report.
Workflow fit
Inspect, patch, and verify code
A workflow for software agents that inspect repositories, review pull requests, generate tests, and turn findings into shippable patches.
Ingest, retrieve, and cite
A workflow for document-heavy agents that ingest files, create searchable knowledge, retrieve relevant context, and answer with grounded sources.
Find, compare, and synthesize
A workflow for agents that gather sources, compare claims, summarize long material, and draft useful research briefs.
Alternative shortlist
Similar skills that may fit this task.
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
--- name: backend-patterns description: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. ---
# Backend Development Patterns
Backend architecture patterns and best practices for scalable server-side applications.
## When to Activate
- Designing REST or GraphQL API endpoints - Implementing repository, service, or controller layers - Optimizing database queries (N+1, indexing, connection pooling) - Adding caching (Redis, in-memory, HTTP cache headers) - Setting up background jobs or async processing - Structuring error handling and validation for APIs - Building middleware (auth, logging, rate limiting)
## API Design Patterns
### RESTful API Structure
```typescript // PASS: 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
// PASS: 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 // PASS: 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)
// FAIL: BAD: Select everything const { data } = await supabase .from('markets') .select('*') ```
### N+1 Query Prevention
```typescript // FAIL: BAD: N+1 query problem const markets = await getMarkets() for (const market of markets) { market.creator = await getUser(market.creator_id) // N queries }
// PASS: 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 ) {}
async findById(id: string): Promise<Market | null> { // Check cache first const cached = await this.redis.get(`market:${id}`)
if (cached) { return JSON.parse(cached) }
// Cache miss - fetch from database const market = await this.baseRepo.findById(id)
if (market) { // Cache for 5 minutes await this.redis.setex(`market:${id}`, 300, JSON.stringify(market)) }
return market }
async invalidateCache(id: string): Promise<void> { await this.redis.del(`market:${id}`) } } ```
### Cache-Aside Pattern
```typescript async function getMarketWithCache(id: string): Promise<Market> { const cacheKey = `market:${id}`
// Try cache const cached = await redis.get(cacheKey) if (cached) return JSON.parse(cached)
// Cache miss - fetch from DB const market = await db.markets.findUnique({ where: { id } })
if (!market) throw new Error('Market not found')
// Update cache await redis.setex(cacheKey, 300, JSON.stringify(market))
return market } ```
## Error Handling Patterns
### Centralized Error Handler
```typescript class ApiError extends Error { constructor( public statusCode: number, public message: string, public isOperational = true ) { super(message) Object.setPrototypeOf(this, ApiError.prototype) } }
export function errorHandler(error: unknown, req: Request): Response { if (error instanceof ApiError) { return NextResponse.json({ success: false, error: error.message }, { status: error.statusCode }) }
if (error instanceof z.ZodError) { return NextResponse.json({ success: false, error: 'Validation failed', details: error.errors }, { status: 400 }) }
// Log unexpected errors console.error('Unexpected error:', error)
return NextResponse.json({ success: false, error: 'Internal server error' }, { status: 500 }) }
// Usage export async function GET(request: Request) { try { const data = await fetchData() return NextResponse.json({ success: true, data }) } catch (error) { return errorHandler(error, request) } } ```
### Retry with Exponential Backoff
```typescript async function fetchWithRetry<T>( fn: () => Promise<T>, maxRetries = 3 ): Promise<T> { let lastError: Error
for (let i = 0; i < maxRetries; i++) { try { return await fn() } catch (error) { lastError = error as Error
if (i < maxRetries - 1) { // Exponential backoff: 1s, 2s, 4s const delay = Math.pow(2, i) * 1000 await new Promise(resolve => setTimeout(resolve, delay)) } } }
throw lastError! }
// Usage const data = await fetchWithRetry(() => fetchFromAPI()) ```
## Authentication & Authorization
### JWT Token Validation
```typescript import jwt from 'jsonwebtoken'
interface JWTPayload { userId: string email: string role: 'admin' | 'user' }
export function verifyToken(token: string): JWTPayload { try { const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload return payload } catch (error) { throw new ApiError(401, 'Invalid token') } }
export async function requireAuth(request: Request) { const token = request.headers.get('authorization')?.replace('Bearer ', '')
if (!token) { throw new ApiError(401, 'Missing authorization token') }
return verifyToken(token) }
// Usage in API route export async function GET(request: Request) { const user = await requireAuth(request)
const data = await getDataForUser(user.userId)
return NextResponse.json({ success: true, data }) } ```
### Role-Based Access Control
```typescript type Permission = 'read' | 'write' | 'delete' | 'admin'
interface User { id: string role: 'admin' | 'moderator' | 'user' }
const rolePermissions: Record<User['role'], Permission[]> = { admin: ['read', 'write', 'delete', 'admin'], moderator: ['read', 'write', 'delete'], user: ['read', 'write'] }
export function hasPermission(user: User, permission: Permission): boolean { return rolePermissions[user.role].includes(permission) }
export function requirePermission(permission: Permission) { return (handler: (request: Request, user: User) => Promise<Response>) => { return async (request: Request) => { const user = await requireAuth(request)
if (!hasPermission(user, permission)) { throw new ApiError(403, 'Insufficient permissions') }
return handler(request, user) } } }
// Usage - HOF wraps the handler export const DELETE = requirePermission('delete')( async (request: Request, user: User) => { // Handler receives authenticated user with verified permission return new Response('Deleted', { status: 200 }) } ) ```
## Rate Limiting
### Simple In-Memory Rate Limiter
```typescript class RateLimiter { private requests = new Map<string, number[]>()
async checkLimit( identifier: string, maxRequests: number, windowMs: number ): Promise<boolean> { const now = Date.now() const requests = this.requests.get(identifier) || []
// Remove old requests outside window const recentRequests = requests.filter(time => now - time < windowMs)
if (recentRequests.length >= maxRequests) { return false // Rate limit exceeded }
// Add current request recentRequests.push(now) this.requests.set(identifier, recentRequests)
return true } }
const limiter = new RateLimiter()
export async function GET(request: Request) { const ip = request.headers.get('x-forwarded-for') || 'unknown'
const allowed = await limiter.checkLimit(ip, 100, 60000) // 100 req/min
if (!allowed) { return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 }) }
// Continue with request } ```
## Background Jobs & Queues
### Simple Queue Pattern
```typescript class JobQueue<T> { private queue: T[] = [] private processing = false
async add(job: T): Promise<void> { this.queue.push(job)
if (!this.processing) { this.process() } }
private async process(): Promise<void> { this.processing = true
while (this.queue.length > 0) { const job = this.queue.shift()!
try { await this.execute(job) } catch (error) { console.error('Job failed:', error) } }
this.processing
Source provenance
Decision snapshot
252,296 GitHub stars
Audit
Install and adoption review
Agent-proven evidence
Outcome reports after resolve, review, install, and one narrow run.
No agent outcome data yet. The first agent run can report success, setup needs, risk blocks, failure, or not-relevant through /api/agent/outcome.
Install
Free and open source. Review the report before installing into production agents.
Growth loop
Scenario-led draft for backend-patterns, ready for a manual X post.
backend-patterns: Backend architecture patterns, API design, database optimization, and server-side best practi... 252.3K stars https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x
Listing + install path for backend-patterns: https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x Install: npx skills add affaan-m/ECC --skill backend-patterns
Listing source
This listing was indexed from public sources and is not marked official until a maintainer claim is approved.
Attribution links to the public repository or creator profile. Creators can claim the listing to update ownership signals.
Claim this skillOwner claim
This Registry indexed listing is attributed to affaan-m but is not marked official yet. Claim it to add a verified owner signal and make future launch, install, and audit updates easier to trust.
Creator backlink kit
Show the canonical listing, current trust and audit signals, and real Agent-Proven evidence where developers evaluate the repository.
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns/audit)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)affaan-m
@affaan-m
Share whether this skill looks useful for your agent workflow. Aggregated feedback improves rankings over time.
Sandbox only
Frontend Design
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
175.1K StarsTaste Skill: Anti-Slop Frontend
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
85.2K StarsVox Director
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
1.8K StarsCanvas Design
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
175.1K StarsSandbox only
Install targets
Codex install prompt
Install the "backend-patterns" agent skill from https://github.com/affaan-m/ECC/tree/main/.agents/skills/backend-patterns. Read its SKILL.md or equivalent instructions first, install only the files needed for this workspace, and summarize any required setup before using it. Skill purpose: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. After the install attempt, report the result to https://www.openagentskill.com/api/agent/outcome with POST JSON {"event_id":"install_<unique-id>","skill_slug":"affaan-m-backend-patterns","task":"Install backend-patterns","agent":"codex","outcome":"success","install_used":true}. Replace event_id with a unique value and outcome with success or failed. Report success only after the skill is installed and a minimal verification passes.Supply asset profile
Code review, repo analysis, testing, CI, GitHub, DevOps, and developer workflow skills.
Scenario
Coding agents
I need a coding agent that can understand a repository, edit code, and review pull requests.
Agent fit
Claude Code + CLI + Codex
Codex, Claude Code, Cursor, CLI, or custom agents.
Install
Ready
npx skills add affaan-m/ECC --skill backend-patterns
Maintenance
fresh
Pushed today
Risk
Needs review
Dependency or permission surface needs review
GitHub quality
252K
95/100 Quality · 82/100 Trust
Coverage tags
Review notes
Dependency or permission surface needs review · Permission surface may require sandboxing
Agent adoption scorecard
These scores combine public repository metadata, OpenAgentSkill review signals, maintenance freshness, and install readiness. They are a shortlist signal, not a replacement for human review.
Quality
ExcellentHigh-confidence pick with strong adoption and healthy maintenance signals.
Trust
Sandbox onlyUseful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
Audit
Needs reviewA machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
OpenAgentSkill Trust Score v5
Run only in a sandbox and compare close alternatives before using it for real work.
Stars
252K GitHub stars
Repo activity
252K stars, 38K forks
Maintenance
Pushed today
License
MIT
Install
npx skills add affaan-m/ECC --skill backend-patterns
Install safety
Agent-readable metadata
Use this block or the embedded JSON to decide whether an agent should install this skill, choose an alternative, or ask for human review first.
Suited tasks
Suited agents
Install decision
Trust and risk
Outcome loop
Install command
npx skills add affaan-m/ECC --skill backend-patternsDo not use when
Alternative
175.1K Stars
npx skills add anthropics/skills --skill frontend-design
Alternative
85.2K Stars
npx skills add Leonxlnx/taste-skill --skill design-taste-frontend
Alternative
1.8K Stars
npx skills add Alisa0808/vox-director --skill vox-director
Alternative
175.1K Stars
npx skills add anthropics/skills --skill canvas-design
Agent safety v2
Sparse or mixed signals. Useful for discovery, but not for autonomous installation.
Test manually in an isolated workspace and compare against safer alternatives.
medium
Skill likely fetches remote pages, APIs, repositories, or external services.
medium
Skill may read or write project files, documents, generated artifacts, or local workspace state.
high
Skill metadata references credentials, tokens, environment variables, or secret-bearing workflows.
medium
Skill may inspect schemas, query databases, or work with persistent stores.
Agent resolve plan
The Resolve API returns the selected skill, alternatives, safety policy, audit notes, install target, and copy-paste prompt an agent can follow without scraping this page.
Open JSON
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Resolve text
/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium&format=text
Install handoff
/api/skills/affaan-m-backend-patterns/install
Agent should check
Copy prompt
Task: Use backend-patterns in this workspace.
Resolve first: https://www.openagentskill.com/api/agent/resolve?task=Use%20backend-patterns%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Review install handoff: https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install
Install command: npx skills add affaan-m/ECC --skill backend-patterns
Before running it, summarize audit warnings, required permissions, and the fallback skill if install is risky.Agent handoff
Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.
Install handoff
/api/skills/affaan-m-backend-patterns/install
LLM text format
/api/skills/affaan-m-backend-patterns/install?format=text
Find alternatives
/api/skills/search?q=backend-patterns&limit=3
Agent prompt
Use backend-patterns for this task. Review https://www.openagentskill.com/api/skills/affaan-m-backend-patterns/install, then install with: npx skills add affaan-m/ECC --skill backend-patternsRegistry metadata
This page exposes the same decision, trust, audit, use-case, and install signals through the Registry API, so agents can rank this skill without scraping the UI.
Manifest
/api/registry/manifest/affaan-m-backend-patterns
LLM text
/api/registry/manifest/affaan-m-backend-patterns?format=text
Install alias
/api/registry/install/affaan-m-backend-patterns
Recommend
/api/registry/recommend?task=Use%20backend-patterns%20in%20an%20agent%20workflow&limit=3
Agent fit
Coding agents
Use-case tags
Platforms
Claude Code
Audit report
A machine-readable review of install readiness, security metadata, maintenance, and adoption risk.
Agent decision cockpit
Use this as a leading candidate, then validate the README and install path in your own agent stack.
Role in stack
Primary pick
Primary fit
Coding agents
Trust label
Production-ready
Install path
Command ready
Use when
Evidence
review first
Implementation path
Trust profile
Useful candidate with missing or mixed trust signals. Keep it in an isolated workspace until the outcome loop proves task fit.
GitHub adoption
PASS252K GitHub stars
Stars/forks activity
PASS252K stars, 38K forks; issue activity unavailable in current metadata
Recent maintenance
PASSPushed today
License clarity
PASSMIT
Good signals
Review before install
Recommended action
Run only in a sandbox and compare close alternatives before using it for real work.
Quality profile
High-confidence pick with strong adoption and healthy maintenance signals.
Workflow fit
Build and ship code
I need a coding agent that can understand a repository, edit code, and review pull requests.
Search private knowledge
I need my agent to build a RAG workflow over documents and retrieve reliable context.
Investigate faster
I need my agent to research a topic, compare sources, and produce a concise report.
Workflow fit
Inspect, patch, and verify code
A workflow for software agents that inspect repositories, review pull requests, generate tests, and turn findings into shippable patches.
Ingest, retrieve, and cite
A workflow for document-heavy agents that ingest files, create searchable knowledge, retrieve relevant context, and answer with grounded sources.
Find, compare, and synthesize
A workflow for agents that gather sources, compare claims, summarize long material, and draft useful research briefs.
Alternative shortlist
Similar skills that may fit this task.
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
--- name: backend-patterns description: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes. Use when building or reviewing Node.js, Express, or Next.js API routes and their data access. ---
# Backend Development Patterns
Backend architecture patterns and best practices for scalable server-side applications.
## When to Activate
- Designing REST or GraphQL API endpoints - Implementing repository, service, or controller layers - Optimizing database queries (N+1, indexing, connection pooling) - Adding caching (Redis, in-memory, HTTP cache headers) - Setting up background jobs or async processing - Structuring error handling and validation for APIs - Building middleware (auth, logging, rate limiting)
## API Design Patterns
### RESTful API Structure
```typescript // PASS: 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
// PASS: 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 // PASS: 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)
// FAIL: BAD: Select everything const { data } = await supabase .from('markets') .select('*') ```
### N+1 Query Prevention
```typescript // FAIL: BAD: N+1 query problem const markets = await getMarkets() for (const market of markets) { market.creator = await getUser(market.creator_id) // N queries }
// PASS: 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 ) {}
async findById(id: string): Promise<Market | null> { // Check cache first const cached = await this.redis.get(`market:${id}`)
if (cached) { return JSON.parse(cached) }
// Cache miss - fetch from database const market = await this.baseRepo.findById(id)
if (market) { // Cache for 5 minutes await this.redis.setex(`market:${id}`, 300, JSON.stringify(market)) }
return market }
async invalidateCache(id: string): Promise<void> { await this.redis.del(`market:${id}`) } } ```
### Cache-Aside Pattern
```typescript async function getMarketWithCache(id: string): Promise<Market> { const cacheKey = `market:${id}`
// Try cache const cached = await redis.get(cacheKey) if (cached) return JSON.parse(cached)
// Cache miss - fetch from DB const market = await db.markets.findUnique({ where: { id } })
if (!market) throw new Error('Market not found')
// Update cache await redis.setex(cacheKey, 300, JSON.stringify(market))
return market } ```
## Error Handling Patterns
### Centralized Error Handler
```typescript class ApiError extends Error { constructor( public statusCode: number, public message: string, public isOperational = true ) { super(message) Object.setPrototypeOf(this, ApiError.prototype) } }
export function errorHandler(error: unknown, req: Request): Response { if (error instanceof ApiError) { return NextResponse.json({ success: false, error: error.message }, { status: error.statusCode }) }
if (error instanceof z.ZodError) { return NextResponse.json({ success: false, error: 'Validation failed', details: error.errors }, { status: 400 }) }
// Log unexpected errors console.error('Unexpected error:', error)
return NextResponse.json({ success: false, error: 'Internal server error' }, { status: 500 }) }
// Usage export async function GET(request: Request) { try { const data = await fetchData() return NextResponse.json({ success: true, data }) } catch (error) { return errorHandler(error, request) } } ```
### Retry with Exponential Backoff
```typescript async function fetchWithRetry<T>( fn: () => Promise<T>, maxRetries = 3 ): Promise<T> { let lastError: Error
for (let i = 0; i < maxRetries; i++) { try { return await fn() } catch (error) { lastError = error as Error
if (i < maxRetries - 1) { // Exponential backoff: 1s, 2s, 4s const delay = Math.pow(2, i) * 1000 await new Promise(resolve => setTimeout(resolve, delay)) } } }
throw lastError! }
// Usage const data = await fetchWithRetry(() => fetchFromAPI()) ```
## Authentication & Authorization
### JWT Token Validation
```typescript import jwt from 'jsonwebtoken'
interface JWTPayload { userId: string email: string role: 'admin' | 'user' }
export function verifyToken(token: string): JWTPayload { try { const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload return payload } catch (error) { throw new ApiError(401, 'Invalid token') } }
export async function requireAuth(request: Request) { const token = request.headers.get('authorization')?.replace('Bearer ', '')
if (!token) { throw new ApiError(401, 'Missing authorization token') }
return verifyToken(token) }
// Usage in API route export async function GET(request: Request) { const user = await requireAuth(request)
const data = await getDataForUser(user.userId)
return NextResponse.json({ success: true, data }) } ```
### Role-Based Access Control
```typescript type Permission = 'read' | 'write' | 'delete' | 'admin'
interface User { id: string role: 'admin' | 'moderator' | 'user' }
const rolePermissions: Record<User['role'], Permission[]> = { admin: ['read', 'write', 'delete', 'admin'], moderator: ['read', 'write', 'delete'], user: ['read', 'write'] }
export function hasPermission(user: User, permission: Permission): boolean { return rolePermissions[user.role].includes(permission) }
export function requirePermission(permission: Permission) { return (handler: (request: Request, user: User) => Promise<Response>) => { return async (request: Request) => { const user = await requireAuth(request)
if (!hasPermission(user, permission)) { throw new ApiError(403, 'Insufficient permissions') }
return handler(request, user) } } }
// Usage - HOF wraps the handler export const DELETE = requirePermission('delete')( async (request: Request, user: User) => { // Handler receives authenticated user with verified permission return new Response('Deleted', { status: 200 }) } ) ```
## Rate Limiting
### Simple In-Memory Rate Limiter
```typescript class RateLimiter { private requests = new Map<string, number[]>()
async checkLimit( identifier: string, maxRequests: number, windowMs: number ): Promise<boolean> { const now = Date.now() const requests = this.requests.get(identifier) || []
// Remove old requests outside window const recentRequests = requests.filter(time => now - time < windowMs)
if (recentRequests.length >= maxRequests) { return false // Rate limit exceeded }
// Add current request recentRequests.push(now) this.requests.set(identifier, recentRequests)
return true } }
const limiter = new RateLimiter()
export async function GET(request: Request) { const ip = request.headers.get('x-forwarded-for') || 'unknown'
const allowed = await limiter.checkLimit(ip, 100, 60000) // 100 req/min
if (!allowed) { return NextResponse.json({ error: 'Rate limit exceeded' }, { status: 429 }) }
// Continue with request } ```
## Background Jobs & Queues
### Simple Queue Pattern
```typescript class JobQueue<T> { private queue: T[] = [] private processing = false
async add(job: T): Promise<void> { this.queue.push(job)
if (!this.processing) { this.process() } }
private async process(): Promise<void> { this.processing = true
while (this.queue.length > 0) { const job = this.queue.shift()!
try { await this.execute(job) } catch (error) { console.error('Job failed:', error) } }
this.processing
Source provenance
Decision snapshot
252,296 GitHub stars
Audit
Install and adoption review
Agent-proven evidence
Outcome reports after resolve, review, install, and one narrow run.
No agent outcome data yet. The first agent run can report success, setup needs, risk blocks, failure, or not-relevant through /api/agent/outcome.
Install
Free and open source. Review the report before installing into production agents.
Growth loop
Scenario-led draft for backend-patterns, ready for a manual X post.
backend-patterns: Backend architecture patterns, API design, database optimization, and server-side best practi... 252.3K stars https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x
Listing + install path for backend-patterns: https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=x Install: npx skills add affaan-m/ECC --skill backend-patterns
Listing source
This listing was indexed from public sources and is not marked official until a maintainer claim is approved.
Attribution links to the public repository or creator profile. Creators can claim the listing to update ownership signals.
Claim this skillOwner claim
This Registry indexed listing is attributed to affaan-m but is not marked official yet. Claim it to add a verified owner signal and make future launch, install, and audit updates easier to trust.
Creator backlink kit
Show the canonical listing, current trust and audit signals, and real Agent-Proven evidence where developers evaluate the repository.
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns/audit)
[](https://www.openagentskill.com/skills/affaan-m-backend-patterns?ref=github&utm_source=github&utm_medium=referral&utm_campaign=creator_badge)affaan-m
@affaan-m
Share whether this skill looks useful for your agent workflow. Aggregated feedback improves rankings over time.
Sandbox only
Frontend Design
Guidance for distinctive, intentional UI design, typography, visual direction, and non-template-like product interfaces.
175.1K StarsTaste Skill: Anti-Slop Frontend
Design and implementation guidance for distinctive landing pages, portfolios, product demos, and purposeful redesigns.
85.2K StarsVox Director
Turn one topic into a narrated Vox-style paper-collage explainer or ad video, from script through captions.
1.8K StarsCanvas Design
Create original visual art, posters, PNG assets, and PDF documents through a clear design philosophy.
175.1K StarsPermission surface
secrets or environment access, filesystem or document access
Agent outcomes
No agent outcome data yet
Docs
Strong README/SKILL.md context
Risk summary
Install readiness
Permission surface
secrets or environment access, filesystem or document access
Agent outcomes
No agent outcome data yet
Docs
Strong README/SKILL.md context
Risk summary
Install readiness
Permission surface
secrets or environment access, filesystem or document access
Agent outcomes
No agent outcome data yet
Docs
Strong README/SKILL.md context
Risk summary
Install readiness
Permission surface
secrets or environment access, filesystem or document access
Agent outcomes
No agent outcome data yet
Docs
Strong README/SKILL.md context
Risk summary
Install readiness