🛡️ Backend Expert

This skill helps you design and enforce enterprise-grade backend architectures with security, performance, and scalable patterns across frameworks and

QUICK INSTALL
npx playbooks add skill shajar5110/hackathon-ii-phase-3 --skill backend-expert

Backend Expert instructions

🔥 ULTIMATE BACKEND MASTERY - 25+ YEARS EXPERT LEVEL

Enterprise-grade backend architecture with genius-level optimization, comprehensive security hardening, advanced architectural patterns, and complete coverage across all frameworks, databases, and deployment strategies.

---

TABLE OF CONTENTS

  1. [Core Architecture Decision Trees](#core-architecture)
  2. [Route Protection & Middleware (PERFECTION)](#route-protection)
  3. [Authentication Systems (ALL METHODS)](#authentication)
  4. [Authorization & RBAC](#authorization)
  5. [API Design (REST, GraphQL, WebSockets, gRPC)](#api-design)
  6. [Database Patterns & ORM](#databases)
  7. [Caching Strategies](#caching)
  8. [Message Queues & Async Jobs](#message-queues)
  9. [Security Hardening (COMPREHENSIVE)](#security)
  10. [Performance Optimization](#performance)
  11. [Microservices & Advanced Patterns](#microservices)
  12. [Monitoring, Logging, Tracing](#monitoring)
  13. [Testing (Unit, Integration, E2E, Load, Security)](#testing)
  14. [Deployment (Docker, Kubernetes, CI/CD)](#deployment)
  15. [Real-World Implementations](#implementations)

---

PART 1: CORE ARCHITECTURE & DECISION TREES

Backend Technology Decision Matrix

Need to build a backend?

STEP 1: Choose Primary Framework
├─ Need high performance + async? → FastAPI (Python)
├─ Need full JavaScript ecosystem? → Express/Node.js
├─ Need type safety + performance? → Node.js with TypeScript
├─ Need full-stack with backend? → Next.js API routes
└─ Need extreme performance + concurrency? → Go/Rust

STEP 2: Choose Database(s)
├─ Relational data + complex queries? → PostgreSQL
├─ Document storage + flexibility? → MongoDB
├─ Cache layer + sessions? → Redis
├─ Full-text search? → Elasticsearch
├─ Time-series data? → TimescaleDB/InfluxDB
└─ All of above → Use what fits each use case

STEP 3: Choose API Style
├─ Simple CRUD operations? → REST
├─ Complex data requirements? → GraphQL
├─ Real-time features needed? → WebSockets
├─ Internal services? → gRPC
└─ Combination? → Use all, not monolithic

STEP 4: Choose Architectural Pattern
├─ Starting small? → Monolith (with modular structure)
├─ Need scaling? → Microservices
├─ Heavy background work? → Event-driven
├─ Complex business logic? → DDD (Domain-Driven Design)
└─ Combination? → Hybrid approach

STEP 5: Choose Deployment
├─ Single server? → Docker + systemd
├─ Multiple servers? → Docker + Docker Compose
├─ Enterprise scale? → Kubernetes
├─ Serverless? → AWS Lambda / Google Cloud Functions
└─ Cloud native? → Managed services (RDS, ElastiCache, etc.)

Project Structure - Next-Generation Backend

backend/
├── src/
│   ├── core/                          // Core infrastructure
│   │   ├── config.ts                 // Configuration management
│   │   ├── env.ts                    // Environment validation (Zod)
│   │   ├── database.ts               // Database connections
│   │   └── cache.ts                  // Cache setup (Redis)
│   │
│   ├── middleware/                    // Global middleware (PERFECTION)
│   │   ├── authentication.ts         // JWT/session verification
│   │   ├── authorization.ts          // RBAC enforcement
│   │   ├── validation.ts             // Input validation (Zod)
│   │   ├── error-handling.ts         // Centralized errors
│   │   ├── logging.ts                // Request logging
│   │   ├── rate-limiting.ts          // DDoS protection
│   │   ├── cors.ts                   // CORS handling
│   │   ├── helmet.ts                 // Security headers
│   │   ├── request-id.ts             // Correlation IDs
│   │   └── compression.ts            // Response compression
│   │
│   ├── routes/                        // API endpoints (PROTECTED)
│   │   ├── auth.routes.ts            // Authentication endpoints
│   │   ├── user.routes.ts            // User endpoints
│   │   ├── products.routes.ts        // Product endpoints
│   │   ├── orders.routes.ts          // Order endpoints
│   │   └── admin.routes.ts           // Admin endpoints (admin only)
│   │
│   ├── controllers/                   // Business logic
│   │   ├── auth.controller.ts
│   │   ├── user.controller.ts
│   │   ├── product.controller.ts
│   │   └── order.controller.ts
│   │
│   ├── services/                      // Core services
│   │   ├── auth.service.ts           // Auth logic
│   │   ├── user.service.ts
│   │   ├── product.service.ts
│   │   ├── order.service.ts
│   │   ├── email.service.ts          // Email sending
│   │   ├── payment.service.ts        // Payment processing
│   │   └── notification.service.ts   // Notifications
│   │
│   ├── models/                        // Database models
│   │   ├── user.model.ts
│   │   ├── product.model.ts
│   │   ├── order.model.ts
│   │   └── schema.ts                 // Validation schemas
│   │
│   ├── repositories/                  // Data access layer
│   │   ├── user.repository.ts
│   │   ├── product.repository.ts
│   │   └── order.repository.ts
│   │
│   ├── guards/                        // Route protection (PERFECTION)
│   │   ├── auth.guard.ts             // Is authenticated?
│   │   ├── role.guard.ts             // Has role?
│   │   ├── permission.guard.ts       // Has permission?
│   │   └── rate-limit.guard.ts       // Rate limit check?
│   │
│   ├── pipes/                         // Data transformation
│   │   ├── validation.pipe.ts
│   │   └── parse-int.pipe.ts
│   │
│   ├── interceptors/                  // Request/response handling
│   │   ├── logging.interceptor.ts
│   │   ├── transform.interceptor.ts
│   │   └── error.interceptor.ts
│   │
│   ├── decorators/                    // Custom decorators
│   │   ├── @Auth()
│   │   ├── @Role('admin')
│   │   ├── @Permission('create:user')
│   │   └── @RateLimit(5, '1m')
│   │
│   ├── utils/
│   │   ├── security.ts               // Encryption, hashing
│   │   ├── validation.ts             // Input validation
│   │   ├── jwt.ts                    // JWT utilities
│   │   ├── pagination.ts             // Pagination helpers
│   │   └── error-handling.ts         // Error utilities
│   │
│   ├── queue/                         // Background jobs
│   │   ├── jobs/
│   │   │   ├── send-email.job.ts
│   │   │   ├── process-payment.job.ts
│   │   │   └── generate-report.job.ts
│   │   └── queue.ts                  // Queue setup
│   │
│   ├── events/                        // Event-driven architecture
│   │   ├── user.events.ts
│   │   ├── order.events.ts
│   │   └── event-bus.ts
│   │
│   ├── types/                         // TypeScript types
│   │   ├── auth.types.ts
│   │   ├── user.types.ts
│   │   ├── api.types.ts
│   │   └── database.types.ts
│   │
│   └── main.ts                        // Entry point
│
├── tests/
│   ├── unit/
│   ├── integration/
│   ├── e2e/
│   └── load/
│
├── docker/
│   ├── Dockerfile
│   └── docker-compose.yml
│
├── kubernetes/
│   ├── deployment.yaml
│   ├── service.yaml
│   └── ingress.yaml
│
├── .env.example
├── .env.local                         // gitignored
├── docker-compose.yml
├── .dockerignore
├── .eslintrc.json
├── .prettierrc.json
├── tsconfig.json
├── jest.config.js
├── package.json
└── README.md

---

PART 2: ROUTE PROTECTION & MIDDLEWARE (PERFECTION)

2.1 Authentication Middleware

// src/middleware/authentication.ts
import { NextFunction, Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { UnauthorizedError } from '@/utils/error-handling';

/**
 * Express authentication middleware
 * Verifies JWT token and attaches user to request
 * PERFECTION: Handles all edge cases
 */
export function authenticationMiddleware() {
    return (req: Request, res: Response, next: NextFunction) => {
        try {
            // Extract token from multiple sources
            let token = extractToken(req);

            if (!token) {
                throw new UnauthorizedError('No token provided');
            }

            // Verify token signature and expiration
            const decoded = jwt.verify(token, process.env.JWT_SECRET!);

            // Check if token is blacklisted (revoked)
            if (isTokenBlacklisted(decoded.jti)) {
                throw new UnauthorizedError('Token has been revoked');
            }

            // Attach user to request for later use
            (req as any).user = {
                id: decoded.sub,
                email: decoded.email,
                role: decoded.role,
                permissions: decoded.permissions,
                sessionId: decoded.jti,
            };

            // Store token expiration for refresh logic
            (req as any).tokenExp = decoded.exp;

            next();
        } catch (error) {
            if (error instanceof jwt.TokenExpiredError) {
                res.status(401).json({ error: 'Token expired' });
            } else if (error instanceof jwt.JsonWebTokenError) {
                res.status(401).json({ error: 'Invalid token' });
            } else {
                next(error);
            }
        }
    };
}

/**
 * Extract token from Authorization header, cookies, or query
 */
function extractToken(req: Request): string | null {
    // 1. Check Authorization header (Bearer token)
    const authHeader = req.headers.authorization;
    if (authHeader?.startsWith('Bearer ')) {
        return authHeader.slice(7);
    }

    // 2. Check HTTP-only cookie
    if (req.cookies?.accessToken) {
        return req.cookies.accessToken;
    }

    // 3. Check custom header
    if (req.headers['x-access-token']) {
        return req.headers['x-access-token'] as string;
    }

    // 4. Don't extract from query string (XSS vulnerability)
    // if (req.query?.token) { ... } // NEVER DO THIS

    return null;
}

/**
 * Check if token is in blacklist (revoked)
 */
function isTokenBlacklisted(jti: string): boolean {
    // In production: Check Redis or database
    // For now: Simple in-memory cache
    return cache.exists(`blacklist:${jti}`);
}

2.2 Authorization Middleware (RBAC)

// src/middleware/authorization.ts
import { NextFunction, Request, Response } from 'express';
import { ForbiddenError } from '@/utils/error-handling';

/**
 * Role-based access control middleware
 * PERFECTION: Enforces roles at route level
 */
export function requireRole(...allowedRoles: string[]) {
    return (req: Request, res: Response, next: NextFunction) => {
        const user = (req as any).user;

        if (!user) {
            res.status(401).json({ error: 'Unauthorized' });
            return;
        }

        if (!allowedRoles.includes(user.role)) {
            // Log unauthorized attempt
            logSecurityEvent({
                type: 'unauthorized_access',
                userId: user.id,
                requiredRole: allowedRoles,
                userRole: user.role,
                endpoint: req.path,
                method: req.method,
            });

            throw new ForbiddenError(
                `This endpoint requires one of roles: ${allowedRoles.join(', ')}`
            );
        }

        next();
    };
}

/**
 * Permission-based access control
 * PERFECTION: Fine-grained permissions
 */
export function requirePermission(...permissions: string[]) {
    return (req: Request, res: Response, next: NextFunction) => {
        const user = (req as any).user;

        if (!user) {
            res.status(401).json({ error: 'Unauthorized' });
            return;
        }

        // Check if user has at least one required permission
        const hasPermission = permissions.some((perm) =>
            user.permissions?.includes(perm)
        );

        if (!hasPermission) {
            logSecurityEvent({
                type: 'insufficient_permissions',
                userId: user.id,
                requiredPermissions: permissions,
                userPermissions: user.permissions,
                endpoint: req.path,
            });

            throw new ForbiddenError(
                `This endpoint requires one of permissions: ${permissions.join(', ')}`
            );
        }

        next();
    };
}

/**
 * Resource-based access control
 * PERFECTION: Check ownership
 */
export function canAccessResource(
    resourceOwnerField: string = 'userId'
) {
    return async (req: Request, res: Response, next: NextFunction) => {
        const user = (req as any).user;
        const resourceId = req.params.id;

        if (!user) {
            res.status(401).json({ error: 'Unauthorized' });
            return;
        }

        // Fetch resource
        const resource = await db.query(
            `SELECT * FROM resources WHERE id = $1`,
            [resourceId]
        );

        if (!resource) {
            res.status(404).json({ error: 'Resource not found' });
            return;
        }

        // Check ownership
        if (resource[resourceOwnerField] !== user.id && user.role !== 'admin') {
            logSecurityEvent({
                type: 'resource_access_denied',
                userId: user.id,
                resourceId,
                ownerId: resource[resourceOwnerField],
            });

            throw new ForbiddenError('You do not have access to this resource');
        }

        // Attach resource for later use
        (req as any).resource = resource;

        next();
    };
}

2.3 Route-Level Protection (Express Example)

// src/routes/protected.routes.ts
import { Router } from 'express';
import { authenticationMiddleware } from '@/middleware/authentication';
import { requireRole, requirePermission } from '@/middleware/authorization';
import { validateInput } from '@/middleware/validation';
import { rateLimitGuard } from '@/middleware/rate-limiting';
import { userController } from '@/controllers/user.controller';
import { createUserSchema, updateUserSchema } from '@/models/user.model';

const router = Router();

/**
 * Public endpoints (no protection)
 */
router.post('/auth/login', userController.login);
router.post('/auth/register', userController.register);

/**
 * Protected endpoints (authentication required)
 */
router.use(authenticationMiddleware());

// Get current user profile
router.get(
    '/users/me',
    userController.getCurrentUser
);

// Update own profile
router.patch(
    '/users/me',
    validateInput(updateUserSchema),
    userController.updateProfile
);

/**
 * Admin-only endpoints (role required)
 */
router.use(requireRole('admin'));

// List all users (admin only)
router.get(
    '/users',
    userController.listUsers
);

// Delete user (admin only)
router.delete(
    '/users/:id',
    userController.deleteUser
);

/**
 * Permission-based endpoints
 */
router.post(
    '/users',
    requirePermission('create:user'),
    validateInput(createUserSchema),
    userController.createUser
);

/**
 * Rate-limited endpoints
 */
router.post(
    '/exports/generate',
    rateLimitGuard({ maxRequests: 5, windowMs: 60000 }), // 5 per minute
    userController.generateExport
);

export const protectedRoutes = router;

2.4 FastAPI Route Protection (Python)

# src/middleware/authentication.py
from fastapi import Depends, HTTPException, status, Request
from fastapi.security import HTTPBearer, HTTPAuthCredentials
import jwt
from typing import Optional, Dict, Any

security = HTTPBearer()

class User:
    def __init__(
        self,
        id: str,
        email: str,
        role: str,
        permissions: list[str],
    ):
        self.id = id
        self.email = email
        self.role = role
        self.permissions = permissions

async def get_current_user(
    credentials: HTTPAuthCredentials = Depends(security),
) -> User:
    """
    Verify JWT token and return current user
    PERFECTION: Complete authentication
    """
    token = credentials.credentials

    try:
        # Verify token signature
        payload = jwt.decode(
            token,
            os.getenv("JWT_SECRET"),
            algorithms=["HS256"],
            options={
                "verify_signature": True,
                "verify_exp": True,
                "verify_aud": False,
            },
        )

        user_id: str = payload.get("sub")
        if user_id is None:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid token",
            )

        # Check if token is blacklisted
        if cache.exists(f"blacklist:{payload.get('jti')}"):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Token has been revoked",
            )

        user = User(
            id=payload.get("sub"),
            email=payload.get("email"),
            role=payload.get("role"),
            permissions=payload.get("permissions", []),
        )

        return user

    except jwt.ExpiredSignatureError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token expired",
        )
    except jwt.InvalidTokenError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token",
        )

def require_role(*allowed_roles: str):
    """Check if user has required role"""
    async def check_role(user: User = Depends(get_current_user)) -> User:
        if user.role not in allowed_roles:
            log_security_event({
                "type": "unauthorized_access",
                "user_id": user.id,
                "required_role": allowed_roles,
                "user_role": user.role,
            })
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Required role: {', '.join(allowed_roles)}",
            )
        return user
    return check_role

def require_permission(*permissions: str):
    """Check if user has required permission"""
    async def check_permission(
        user: User = Depends(get_current_user),
    ) -> User:
        if not any(perm in user.permissions for perm in permissions):
            log_security_event({
                "type": "insufficient_permissions",
                "user_id": user.id,
                "required_permissions": permissions,
                "user_permissions": user.permissions,
            })
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Required permission: {', '.join(permissions)}",
            )
        return user
    return check_permission

# src/routes/users.py
from fastapi import APIRouter, Depends
from src.middleware.authentication import (
    get_current_user,
    require_role,
    require_permission,
    User,
)

router = APIRouter()

# Public endpoint
@router.post("/auth/login")
async def login(credentials: LoginRequest):
    # Login logic
    pass

# Protected endpoint (authentication required)
@router.get("/users/me")
async def get_current_user_profile(
    user: User = Depends(get_current_user),
):
    return {"id": user.id, "email": user.email}

# Admin-only endpoint
@router.get("/users")
async def list_users(
    user: User = Depends(require_role("admin")),
):
    return {"users": [...]}

# Permission-based endpoint
@router.post("/users")
async def create_user(
    user_data: UserCreate,
    user: User = Depends(require_permission("create:user")),
):
    return {"id": "...", "email": user_data.email}

# Resource ownership check
@router.get("/orders/{order_id}")
async def get_order(
    order_id: str,
    current_user: User = Depends(get_current_user),
):
    order = await db.get_order(order_id)
    
    # Check ownership or admin
    if order.user_id != current_user.id and current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You do not have access to this resource",
        )
    
    return order

2.5 Global Middleware Chain (Express)

// src/main.ts
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
imp

Related Skills

Get the best new skills
in your inbox

Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.