Skip to content
/ fastify-starter Public template

πŸš€ Production-ready Fastify starter with TypeScript, Prisma, Docker, Prometheus, Automated Grafana Dashboards, Authentication & DriftOS' Golden Orchestrator pattern. Includes CLI generator for instant service scaffolding. Zero boilerplate, 100% type-safe, fully tested.

License

Notifications You must be signed in to change notification settings

DriftOS/fastify-starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

54 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Fastify Gold Standard Starter

Production-ready Fastify starter template with TypeScript, Prisma, Docker, Prometheus, and the Golden Orchestrator pattern.

Built with Fastify Gold Standard Node.js Version TypeScript License: MIT

πŸŽ‰ Live Demo - See it in action with Swagger docs

πŸš€ Deployment Options

Quick Deploy (Demo/Testing)

One-click deployment - Great for demos and testing. Includes API + PostgreSQL only.

Platform Deploy Button Time Cost
Render ⭐ Deploy to Render 3 min ~$7/mo
Railway Deploy on Railway 5 min ~$5/mo

Full Production Stack (Recommended)

Docker Compose on VPS - Complete stack with Grafana dashboards and monitoring.

# One command - full production setup
npm run generate:dashboards
docker compose -f docker/docker-compose.yml up -d

βœ… API + PostgreSQL + Prometheus + Grafana
βœ… Auto-generated dashboards work perfectly
βœ… ~$5-10/mo on DigitalOcean, Hetzner, or Linode

πŸ“– Full instructions: See DEPLOY.md for all deployment options

πŸ† Why This Starter?

Production-ready Fastify template with best practices, type safety, and Prometheus metrics built-in.

Feature This Starter NestJS Express Other Fastify
Pipeline Architecture βœ… Built-in ⚠️ Different ❌ None ❌ None
Performance ⚑ Native Fastify 🐒 Express under hood 🐌 Express ⚑ Fastify
Type Safety βœ… Strict TypeScript βœ… Good ⚠️ Varies ⚠️ Varies
Metrics βœ… Prometheus built-in ⚠️ Manual ❌ Basic ❌ Basic
Docker βœ… Full stack ⚠️ App only ⚠️ Varies ⚠️ Varies

Perfect for:

  • Production APIs that need to scale
  • Teams that value developer experience
  • Projects that require strong type safety

✨ Features

Core Stack

  • Fastify - High-performance web framework (4x faster than Express)
  • TypeScript - Full type safety with strict mode
  • Prisma - Type-safe database ORM with migrations
  • PostgreSQL - Production database
  • Docker - Full containerization
  • Prometheus - Built-in metrics at /metrics
  • Swagger - Auto-generated API documentation

Architecture Patterns

  • Golden Orchestrator Pattern - Pipeline-based business logic
  • Singleton Services - Efficient resource management
  • Pure Operations - Testable, composable functions
  • Performance Tracking - Automatic metrics for every pipeline stage

Developer Experience

  • ESLint & Prettier - Consistent code formatting
  • Husky - Pre-commit hooks
  • Hot Reload - Fast development cycle with tsx
  • TypeBox - Runtime validation with TypeScript types
  • Swagger/OpenAPI - Auto-generated API documentation

Production Ready

  • JWT Authentication - Secure auth flow
  • Rate Limiting - DDoS protection
  • CORS - Configurable cross-origin support
  • Helmet - Security headers
  • Health Checks - Kubernetes-ready endpoints
  • Graceful Shutdown - Clean process termination
  • Structured Logging - Pino with correlation IDs
  • Environment Validation - Fail fast on missing config

πŸ—οΈ Project Structure

fastify-gold-standard-starter/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”œβ”€β”€ orchestration/          # Golden orchestrator pattern
β”‚   β”‚   β”‚   β”œβ”€β”€ base-orchestrator.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ performance-interceptor.ts
β”‚   β”‚   β”‚   └── types.ts
β”‚   β”‚   └── hooks/                  # Fastify lifecycle hooks
β”‚   β”œβ”€β”€ plugins/                    # Fastify plugins
β”‚   β”‚   β”œβ”€β”€ auth.ts                 # JWT authentication
β”‚   β”‚   β”œβ”€β”€ cors.ts                 # CORS configuration
β”‚   β”‚   β”œβ”€β”€ env.ts                  # Environment validation
β”‚   β”‚   β”œβ”€β”€ metrics.ts              # Prometheus metrics
β”‚   β”‚   β”œβ”€β”€ prisma.ts               # Database client
β”‚   β”‚   └── swagger.ts              # API documentation
β”‚   β”œβ”€β”€ routes/                     # API endpoints
β”‚   β”‚   β”œβ”€β”€ health/                 # Health checks
β”‚   β”‚   β”œβ”€β”€ auth/                   # Authentication
β”‚   β”‚   β”œβ”€β”€ users/                  # User management
β”‚   β”‚   └── example/                # Example CRUD
β”‚   β”œβ”€β”€ services/                   # Business logic
β”‚   β”‚   └── todo/                   # Example service
β”‚   β”‚       β”œβ”€β”€ orchestrator.ts     # Pipeline orchestrator
β”‚   β”‚       β”œβ”€β”€ operations/         # Pure functions
β”‚   β”‚       β”œβ”€β”€ types/              # TypeScript types
β”‚   β”‚       β”œβ”€β”€ __tests__/          # Co-located tests
β”‚   β”‚       └── index.ts            # Service facade
β”‚   β”œβ”€β”€ utils/                      # Utilities
β”‚   β”œβ”€β”€ app.ts                      # Fastify app setup
β”‚   └── server.ts                   # Entry point
β”œβ”€β”€ prisma/
β”‚   β”œβ”€β”€ schema.prisma               # Database schema
β”‚   └── migrations/                 # Database migrations
β”œβ”€β”€ docker/
β”‚   β”œβ”€β”€ docker-compose.yml          # Local development
β”‚   β”œβ”€β”€ prometheus/                 # Prometheus config
β”‚   └── grafana/                    # Grafana dashboards
β”œβ”€β”€ scripts/
β”‚   └── generate-dashboards.ts      # Auto-generate Grafana dashboards
β”œβ”€β”€ Makefile                        # Make commands for common tasks
β”œβ”€β”€ setup.sh                        # One-command setup script
└── .github/
    └── workflows/
        └── ci.yml                  # CI/CD pipeline

πŸš€ Quick Start

Prerequisites

  • Node.js 18-20 LTS (Node 22+ may show dependency warnings)
  • Docker & Docker Compose
  • PostgreSQL (or use Docker)

🎨 NEW: Service Generator

Generate a complete service in 2 minutes!

npm run generate

? What do you want to generate? Service
? Service name: Order
? Operations: validate,process,notify
? Include Prisma model? Yes
? Include API route? Yes
? Include tests? Yes

✨ Created 14 files with ~600 lines of production code!

See docs/GETTING_STARTED.md for full details.

After generating services, automatically create Grafana dashboards:

npm run generate:dashboards

This scans all orchestrators and generates performance monitoring dashboards automatically!

Pre-built dashboards included:

  • System Overview - HTTP metrics, response times, error rates
  • Per-Service Dashboards - Auto-generated from orchestrators

Installation

  1. Clone the template
git clone https://github.com/yourusername/fastify-gold-standard-starter.git
cd fastify-gold-standard-starter
  1. Run setup script
./setup.sh

The script automatically:

  • βœ… Installs dependencies
  • βœ… Creates .env file
  • βœ… Starts Docker services
  • βœ… Runs database migrations
  • βœ… Generates Grafana dashboards
  1. Start development server
npm run dev
# Or use make commands:
make dev

Done! Your API is now running at:


🎯 Daily Workflow (Like DriftOS!)

# Start everything (one command!)
make up          # Starts Docker + runs migrations + generates dashboards

# Start dev server (in another terminal)
make dev

# Test the API (in another terminal)
make test-api    # Automated tests with auth

# Open Grafana
make grafana

# Stop everything
make down

πŸ”₯ See Dashboards In Action

Light up your monitoring in 3 steps:

# Terminal 1: Start API
npm run dev

# Terminal 2: Generate realistic traffic
npm run load-test

# Browser: Watch the magic
open http://localhost:3001

The load tester will:

  • βœ… Authenticate automatically
  • βœ… Send randomized requests (realistic traffic patterns)
  • βœ… Respect rate limits (no 429 errors)
  • βœ… Display live stats (requests, latency, success rate)

Watch your dashboards update in real-time! All operations visible, all metrics accurate, zero configuration.


🎯 API Endpoints

Public Routes (No Auth):

  • GET /api/v1/health - Health check
  • GET /api/v1/ready - Readiness probe
  • POST /api/v1/auth/login - User login
  • POST /api/v1/auth/register - User registration

Protected Routes (Auth Required):

  • GET /api/v1/users/me - Get current user
  • POST /api/v1/todos - Create todo (Golden Orchestrator pattern) ⭐
  • GET /api/v1/todos - List todos
  • POST /api/v1/examples - Create example (direct Prisma access)
  • GET /api/v1/examples - List examples (direct Prisma access)

πŸ“š Documentation


πŸš€ Using This Template

1. Click "Use this template" on GitHub

2. Add Repository Description

Production-ready Fastify starter with TypeScript, Prisma, Docker, Prometheus & the Golden Orchestrator pattern. Includes CLI generator for instant service scaffolding.

3. Add Topics

fastify, typescript, starter-template, orchestrator-pattern, 
prisma, docker, prometheus, grafana, cli-generator, production-ready

4. Clone and Start

git clone your-repo-url
cd your-repo
./setup.sh
make up
make dev

πŸ—οΈ Golden Orchestrator Pattern

The Golden Orchestrator pattern provides a structured way to handle complex business logic through pipelines.

See docs/ARCHITECTURE.md for complete examples and deep dive.

Quick Example

// Define pipeline context
interface TodoPipelineContext extends OperationContext {
  input: CreateTodoInput;
  todo?: Todo;
}

// Create orchestrator
class CreateTodoOrchestrator extends BaseOrchestrator<
  TodoPipelineContext,
  Todo,
  CreateTodoInput
> {
  protected getPipeline(): PipelineStage<TodoPipelineContext>[] {
    return [
      { name: 'validate-input', operation: validateInput, critical: true },
      { name: 'create-todo', operation: createTodo, critical: true },
      { name: 'notify-creation', operation: notifyCreation, critical: false },
    ];
  }
}

// Pure operation function
async function createTodo(context: TodoPipelineContext): Promise<TodoPipelineContext> {
  const todo = await prisma.todo.create({
    data: context.input
  });
  context.todo = todo;
  return context;
}

Benefits

  • Testability: Each operation is a pure function
  • Observability: Automatic performance tracking
  • Composability: Reuse operations across orchestrators
  • Reliability: Critical vs non-critical operations
  • Maintainability: Clear separation of concerns

πŸ“Š Monitoring & Observability

🎨 Automatic Dashboard Generation

Generate beautiful Grafana dashboards in seconds!

npm run generate:dashboards

Creates production-ready dashboards with:

  • βœ… Avg Response Time, Success Rate, P95 Latency, Ops/min
  • βœ… Stacked area charts showing operation breakdown
  • βœ… Time-range aware sparklines
  • βœ… All metrics extracted automatically from your orchestrator code

See docs/AUTOMATIC_DASHBOARDS.md for details.

πŸ”₯ Load Testing

Simulate production traffic and watch your dashboards light up!

npm run load-test

Features:

  • βœ… Rate-limit aware (respects 100 req/min limit)
  • βœ… Randomized traffic (Β±30% jitter for realistic patterns)
  • βœ… Authentication built-in
  • βœ… Configurable RPS and duration
  • βœ… Live stats display
# Custom load
RPS=2 DURATION=5 npm run load-test

# Disable randomization
RANDOMIZE=false npm run load-test

Prometheus Metrics

  • HTTP metrics: Request duration, count, status codes
  • Orchestrator metrics: Pipeline duration, stage latency, success rate
  • System metrics: Active connections, memory, CPU
  • Custom metrics: Business-specific tracking

Grafana Dashboards

  • System Overview: HTTP performance, P95 latency, error rates, requests/min
  • Service Dashboards: Auto-generated per orchestrator with operation breakdown
  • Time-range aware: All metrics adapt to selected time range
  • Production-ready: 5-30s auto-refresh, proper sparklines

Health Checks

  • /health - Basic health check
  • /ready - Readiness probe (checks DB connection)

πŸ§ͺ Testing

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

# Run tests with UI
npm run test:ui

πŸ“¦ Production Deployment

Using Docker

# Build production image
docker build -t fastify-app .

# Run container
docker run -p 3000:3000 --env-file .env fastify-app

Using PM2

# Build the application
npm run build

# Start with PM2
pm2 start dist/server.js --name fastify-app

Environment Variables

Key environment variables for production:

NODE_ENV=production
PORT=3000
DATABASE_URL=postgresql://user:pass@host:5432/db
JWT_SECRET=your-secret-key
RATE_LIMIT_MAX=100
CORS_ORIGIN=https://yourdomain.com

πŸ› οΈ Scripts

npm run dev           # Start development server
npm run build         # Build for production
npm run start         # Start production server
npm run typecheck     # TypeScript type checking
npm run lint          # Run ESLint
npm run format        # Format code with Prettier
npm run db:migrate    # Run database migrations
npm run db:studio     # Open Prisma Studio
npm run docker:up     # Start Docker services
npm run docker:down   # Stop Docker services

πŸ”’ Security

  • JWT-based authentication
  • Rate limiting on all endpoints
  • Input validation with TypeBox
  • SQL injection protection via Prisma
  • XSS protection with Helmet
  • CORS properly configured
  • Environment variables validation

πŸ… Built With This Starter

Show that your project uses the Fastify Gold Standard! Add this badge to your README:

[![Built with Fastify Gold Standard](https://img.shields.io/badge/Built%20with-Fastify%20Gold%20Standard-blue?style=flat&logo=fastify)](https://github.com/DriftOS/fastify-starter)

Built with Fastify Gold Standard

Benefits:

  • πŸ”— Builds backlinks to help others discover this starter
  • πŸ“ˆ Social proof shows you're using production-grade architecture
  • 🀝 Supports the open-source community

🌟 Used By

Projects and companies using this starter:

  • DriftOS - AI-powered branching memory system
  • Your Project Here - Submit a PR to be featured!

Using this starter in production? We'd love to feature you! Submit a PR with your project.

❓ When to Use Orchestrators vs Direct Access

Use the Orchestrator Pattern (TodoService) when:

  • βœ… Business logic has multiple steps
  • βœ… You need performance tracking per operation
  • βœ… Operations might fail independently (critical vs non-critical)
  • βœ… Logic will grow in complexity
  • βœ… You want automatic Grafana dashboards

Use Direct Access (ExampleService - being removed) when:

  • βœ… Simple CRUD operations
  • βœ… Single database query
  • βœ… No complex business logic
  • βœ… Performance tracking not needed

Note: The /api/v1/examples routes demonstrate simple CRUD without orchestrators. These will be removed in v2.0. For production apps, we recommend the orchestrator pattern for all business logic to ensure consistent observability.

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Fastify - Fast and low overhead web framework
  • Prisma - Next-generation ORM
  • TypeBox - JSON Schema Type Builder

πŸ“§ Support

For support, email hello@driftos.dev or open an issue in the repository.


Built with ❀️ using the Fastify Gold Standard architecture

About

πŸš€ Production-ready Fastify starter with TypeScript, Prisma, Docker, Prometheus, Automated Grafana Dashboards, Authentication & DriftOS' Golden Orchestrator pattern. Includes CLI generator for instant service scaffolding. Zero boilerplate, 100% type-safe, fully tested.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published