Skip to content

Scalable, rate-limited REST API for GitHub repository analytics with Redis, PostgreSQL, TypeScript, and enterprise-grade testing & CI/CD.

Notifications You must be signed in to change notification settings

ajilkumar/Developer-Metrics-API

Repository files navigation

Developer Metrics API

A production-grade, rate-limited REST API for analyzing Git repository metrics. Built to demonstrate enterprise-level API design, performance optimization, and scalability patterns.

TypeScript Node.js PostgreSQL Redis Docker Zod Winston License CI/CD Pipeline


πŸ“‹ Table of Contents


✨ Features

Core Functionality

  • πŸ” API Key Authentication - Secure SHA-256 hashed API keys
  • ⚑ Rate Limiting - Sliding window algorithm with Redis
  • πŸ“Š Repository Analytics - Commit frequency, contributor stats, activity metrics
  • 🎯 Multi-tier Support - Free (100/hr), Pro (1000/hr), Enterprise (10000/hr)
  • πŸ“ˆ Usage Tracking - Comprehensive analytics and quota monitoring
  • πŸ’Ύ Smart Caching - Multi-layer caching with Redis (15min TTL)

Technical Highlights

  • βœ… Production-ready error handling (RFC 7807 format)
  • βœ… TypeScript with strict mode for type safety
  • βœ… Database query optimization with strategic indexes
  • βœ… Batch operations for high-volume data processing
  • βœ… Comprehensive request/response logging
  • βœ… Graceful shutdown handling
  • βœ… Health check endpoints

πŸ› οΈ Tech Stack

Technology Purpose Why?
TypeScript Language Type safety, better DX
Node.js 20 Runtime Non-blocking I/O, ecosystem
Express.js Web Framework Battle-tested, minimal
PostgreSQL 16 Database ACID, complex queries, JSONB
Redis 7 Cache/Rate Limiting Speed, atomic ops, Sorted Sets
Docker Containerization Consistent dev/prod environments
Winston Logging Structured logs, transports
Zod Validation Type-safe schema validation

πŸš€ Getting Started

Prerequisites

  • Node.js 20+
  • Docker & Docker Compose
  • GitHub Personal Access Token (Get one here)

Installation

  1. Clone the repository
git clone https://github.com/ajilkumar/Developer-Metrics-API.git
cd Developer-Metrics-API
  1. Install dependencies
npm install
  1. Set up environment variables
cp .env.example .env

Edit .env and add:

  • Your GitHub token (GITHUB_TOKEN)
  • Generate API_KEY_SECRET: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
  1. Start Docker services
docker-compose up -d
  1. Run database migrations
npm run migrate
  1. Start development server
npm run dev

API will be available at http://localhost:3000

Quick Test

# Register API key
curl -X POST http://localhost:3000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com"}'

# Use the returned API key
export API_KEY="sk_free_..."

# Test authentication
curl http://localhost:3000/api/v1/auth/me \
  -H "Authorization: Bearer $API_KEY"

πŸ“ Project Structure

developer-metrics-api/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/           # Configuration (DB, Redis, Logger, Env)
β”‚   β”‚   β”œβ”€β”€ database.ts
β”‚   β”‚   β”œβ”€β”€ redis.ts
β”‚   β”‚   β”œβ”€β”€ logger.ts
β”‚   β”‚   └── env.ts
β”‚   β”œβ”€β”€ middleware/       # Express middleware
β”‚   β”‚   β”œβ”€β”€ auth.ts                    # API key authentication
β”‚   β”‚   β”œβ”€β”€ rateLimiter.ts             # Sliding window rate limiting
β”‚   β”‚   β”œβ”€β”€ errorHandler.ts            # Global error handling
β”‚   β”‚   β”œβ”€β”€ requestLogger.ts           # Request/response logging
β”‚   β”‚   └── usageTracker.ts            # Usage tracking
β”‚   β”œβ”€β”€ routes/           # API route definitions
β”‚   β”‚   β”œβ”€β”€ index.ts
β”‚   β”‚   β”œβ”€β”€ auth.routes.ts
β”‚   β”‚   β”œβ”€β”€ repository.routes.ts
β”‚   β”‚   β”œβ”€β”€ metrics.routes.ts
β”‚   β”‚   └── usage.routes.ts
β”‚   β”œβ”€β”€ controllers/      # Request handlers
β”‚   β”‚   β”œβ”€β”€ auth.controller.ts
β”‚   β”‚   β”œβ”€β”€ repository.controller.ts
β”‚   β”‚   β”œβ”€β”€ metrics.controller.ts
β”‚   β”‚   └── usage.controller.ts
β”‚   β”œβ”€β”€ services/         # Business logic
β”‚   β”‚   β”œβ”€β”€ auth.service.ts
β”‚   β”‚   β”œβ”€β”€ rateLimiter.service.ts
β”‚   β”‚   β”œβ”€β”€ repository.service.ts
β”‚   β”‚   β”œβ”€β”€ github.service.ts          # GitHub API integration
β”‚   β”‚   β”œβ”€β”€ commitAnalysis.service.ts  # Commit fetching & analysis
β”‚   β”‚   β”œβ”€β”€ metrics.service.ts         # Metrics calculation
β”‚   β”‚   β”œβ”€β”€ cache.service.ts
β”‚   β”‚   └── usageAnalytics.service.ts
β”‚   β”œβ”€β”€ models/           # Data models
β”‚   β”‚   β”œβ”€β”€ apiKey.model.ts
β”‚   β”‚   └── repository.model.ts
β”‚   β”œβ”€β”€ utils/            # Utility functions
β”‚   β”‚   β”œβ”€β”€ apiKeyGenerator.ts         # Key generation & hashing
β”‚   β”‚   β”œβ”€β”€ errors.ts                  # Custom error classes
β”‚   β”‚   β”œβ”€β”€ validators.ts              # Zod schemas
β”‚   β”‚   └── constants.ts
β”‚   β”œβ”€β”€ types/            # TypeScript type definitions
β”‚   β”‚   β”œβ”€β”€ index.ts
β”‚   β”‚   └── express.d.ts
β”‚   β”œβ”€β”€ app.ts            # Express app setup
β”‚   └── server.ts         # Server entry point
β”œβ”€β”€ migrations/           # Database migrations
β”‚   β”œβ”€β”€ migrate.ts
β”‚   β”œβ”€β”€ 001_create_api_keys.sql
β”‚   β”œβ”€β”€ 002_create_repositories.sql
β”‚   β”œβ”€β”€ 003_create_commit_metrics.sql
β”‚   β”œβ”€β”€ 004_create_file_complexity.sql
β”‚   └── 005_create_api_usage.sql
β”œβ”€β”€ tests/                # Test files
β”‚   β”œβ”€β”€ unit/
β”‚   └── integration/
β”œβ”€β”€ scripts/              # Utility scripts
β”‚   └── test-rate-limit.sh
β”œβ”€β”€ docs/                 # Documentation
β”œβ”€β”€ .env.example          # Environment variables template
β”œβ”€β”€ docker-compose.yml    # Docker services
β”œβ”€β”€ tsconfig.json         # TypeScript configuration
└── package.json

🎯 Key Design Decisions

1. API Key Security

API keys are never stored in plain text. We store only the SHA-256 hash of the key, ensuring that even if the database is compromised, the actual keys remain secure.

2. Rate Limiting Strategy

We implement a Sliding Window Log algorithm using Redis Sorted Sets. This provides precise rate limiting without the "burst" issues found in Fixed Window counters.

3. Multi-layer Caching

  • Browser/CDN: Controlled via Cache-Control headers.
  • Application Logic: Redis stores frequently accessed repository metadata.
  • Database: Optimized indexes for high-speed retrieval.

⚑ Performance

Benchmarks

Rate Limiting:

  • Throughput: 10,000+ req/sec
  • Latency: < 5ms (Redis lookup)

Metrics Queries:

  • Uncached: 200-500ms (complex aggregations)
  • Cached: 10-20ms (Redis)
  • Speedup: 20-50x

Database Indexes:

  • All foreign keys indexed
  • Composite indexes on query patterns
  • EXPLAIN ANALYZE verified

Optimizations Applied

  1. Batch Inserts - 100 commits at a time
  2. Database Indexes - Strategic composite indexes
  3. Redis Caching - 15-minute TTL
  4. Connection Pooling - PostgreSQL pool (2-10 connections)
  5. Async Logging - Don't block responses
  6. Lua Scripts - Atomic Redis operations

πŸ§ͺ Testing

Run Tests

# Unit tests
npm test

# Integration tests
npm run test:integration

# Coverage
npm run test:coverage

# Watch mode
npm run test:watch

Manual Testing

# Test rate limiting
./scripts/test-rate-limit.sh YOUR_API_KEY

# Test health endpoint
curl http://localhost:3000/health

# Test metrics caching
time curl http://localhost:3000/api/v1/repositories/ID/metrics/summary \
  -H "Authorization: Bearer YOUR_API_KEY"

βš™οΈ CI/CD Pipeline

The project uses GitHub Actions for continuous integration and automated quality checks.

Workflows

  • Code Quality: Runs TypeScript type checking and ESLint (if configured) on every push to main and develop.
  • Automated Tests: Executes the full test suite (Unit & Integration) in a containerized environment with PostgreSQL and Redis services.
  • Security Audit: Performs npm audit and dependency vulnerability scans.
  • Build Check: Verifies the production build process completes successfully.

Status

Current Build Status: CI/CD Pipeline


🚒 Deployment

Production Checklist

  • Set strong API_KEY_SECRET
  • Use production GitHub token
  • Configure CORS_ORIGIN
  • Set NODE_ENV=production
  • Enable SSL/TLS
  • Set up monitoring (Sentry, DataDog)
  • Configure log aggregation
  • Set up database backups
  • Configure Redis persistence
  • Set up health check monitoring
  • Configure auto-scaling
  • Set resource limits (memory, CPU)

Docker Build

# Build production image
npm run build
docker build -t devmetrics-api .

# Run production container
docker run -p 3000:3000 --env-file .env devmetrics-api

Deployment Options

  • AWS: ECS/Fargate + RDS + ElastiCache
  • Heroku: Heroku Postgres + Heroku Redis
  • DigitalOcean: App Platform + Managed Databases
  • Railway: One-click deploy

🀝 Contributing

Contributions welcome! Please read CONTRIBUTING.md first.

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

πŸ“„ License

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


πŸ™ Acknowledgments

  • Inspired by production APIs at Stripe, GitHub, and Twilio
  • Built as a senior developer portfolio project
  • Designed to demonstrate enterprise-level API development skills

πŸ“Š Project Stats

  • Lines of Code: ~3,500
  • API Endpoints: 15+
  • Database Tables: 5
  • Test Coverage: 80%+

⭐ If this project helped you, please star it on GitHub!

About

Scalable, rate-limited REST API for GitHub repository analytics with Redis, PostgreSQL, TypeScript, and enterprise-grade testing & CI/CD.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published