A production-ready TypeScript-based microservice implementing Clean Architecture principles with gRPC and HTTP interfaces, Redis caching, PostgreSQL database, and comprehensive observability stack.
This project follows Clean Architecture (Hexagonal Architecture) with clear separation of concerns:
src/
βββ app/ # Application layer (interface adapters)
β βββ grpc/ # gRPC server implementation
β β βββ server.ts # gRPC server setup
β β βββ handlers/ # gRPC method handlers
β β βββ ioc/ # Inversion of Control containers
β β βββ mappers/ # Data mapping utilities
β βββ http/ # HTTP server implementation
β βββ server.ts # Fastify HTTP server setup
β βββ controllers/ # HTTP route controllers
β βββ mappers/ # HTTP data mappers
β βββ transporters/ # HTTP transport layer
βββ core/ # Core utilities and shared logic
β βββ either.ts/.spec.ts # Functional error handling (Either monad)
β βββ entities/ # Base entity classes and value objects
β βββ errors/ # Custom error classes
β βββ types/ # Shared type definitions
βββ domain/ # Business logic layer (entities and use cases)
β βββ cache/ # Cache domain interfaces
β β βββ repositories/ # Cache repository contracts
β βββ customer/ # Customer domain
β β βββ customers.ts # Customer entity
β β βββ adapters/ # Domain adapters
β β βββ repositories/ # Customer repository interfaces
β β βββ use-case/ # Customer business use cases
β βββ store/ # Store domain
β βββ store.ts # Store entity
β βββ adapters/ # Store adapters
β βββ repositories/ # Store repository interfaces
β βββ use-case/ # Store business use cases
βββ infra/ # Infrastructure layer (external concerns)
βββ client.ts # External client configurations
βββ server-grpc.ts # gRPC server entry point
βββ server-http.ts # HTTP server entry point
βββ cache/ # Cache implementations
β βββ redis/ # Redis client and repositories
βββ db/ # Database implementations
βββ prisma/ # Prisma ORM integration
- Domain Layer: Contains business entities, use cases, and repository interfaces
- Infrastructure Layer: Contains implementations of repositories, gRPC services, HTTP endpoints, and external dependencies
- Core Layer: Contains shared utilities and error handling
- Repository Pattern: Abstracts data access logic for both database and cache
- Use Case Pattern: Encapsulates business logic
- Factory Pattern: Creates and wires dependencies
- Either Pattern: Functional error handling without exceptions
- Cache-Aside Pattern: Performance optimization with Redis caching
- Dual Interface: Both gRPC and HTTP REST endpoints
- gRPC Communication: High-performance RPC with Protocol Buffers
- TypeScript: Full type safety across the application
- Clean Architecture: Domain-driven design with clear separation of concerns
- Functional Error Handling: Using Either monad for explicit error handling
- Redis Caching: Performance optimization with intelligent caching strategies
- PostgreSQL + Prisma: Robust database with type-safe ORM
- Observability Stack: Prometheus metrics, Grafana dashboards, and Loki logging
- Environment Validation: Type-safe configuration with Zod
- Testing: Comprehensive test suite with Vitest
- Code Quality: Automated linting and formatting with Biome
- Language: TypeScript (ES2022, ESM modules)
- gRPC: @grpc/grpc-js with Protocol Buffer code generation
- HTTP Server: Fastify with Pino logging
- Database: PostgreSQL with Prisma ORM and pg adapter
- Cache: Redis with connection pooling
- Package Manager: pnpm with workspace support
- Code Quality: Biome (ESLint + Prettier replacement)
- Testing: Vitest with TypeScript support
- Build: tsx for development, TypeScript compiler for production
- Database: Prisma migrations and introspection
- Containerization: Docker Compose for local development
- Metrics: Prometheus with prom-client
- Visualization: Grafana dashboards
- Logging: Pino with Loki integration
- Monitoring: Grafana Alloy for telemetry collection
The project includes a complete local development stack:
services:
postgres: # PostgreSQL database (port 5432)
redis: # Redis cache (port 6379, password: redis)
prometheus: # Metrics collection (port 9090)
grafana: # Monitoring dashboards (port 3001)
loki: # Log aggregation
alloy: # Telemetry collection agent- Node.js 18+
- pnpm 10.28.2+
- Docker and Docker Compose
# Clone the repository
git clone <repository-url>
cd grpc
# Install dependencies
pnpm install
# Start infrastructure services
docker-compose up -d
# Generate Protocol Buffer types
pnpm run build:proto
# Run database migrations
pnpm run migrate
# Generate Prisma client
pnpm run generate
# Seed the database (optional)
pnpm run seed# Start gRPC server (port 50051)
pnpm run start:dev:grpc
# Start HTTP server (port 3000)
pnpm run start:dev:http
# Or run both servers simultaneously
# Terminal 1:
pnpm run start:dev:grpc
# Terminal 2:
pnpm run start:dev:http- gRPC Server:
localhost:50051 - HTTP Server:
localhost:3000 - Grafana Dashboard:
http://localhost:3001 - Prometheus Metrics:
http://localhost:9090 - PostgreSQL:
localhost:5432(user: grpc, password: grpc, database: grpc) - Redis:
localhost:6379(password: redis)
The project implements the StoresService defined in proto/stores.proto:
service StoresService {
rpc ListStores(Void) returns (StoresResponse) {}
rpc ListCustomers(Void) returns (CustomersListResponse) {}
rpc CreateCustomer(CreateCustomerRequest) returns (Void) {}
rpc CreateStore(CreateStoreRequest) returns (Void) {}
}Available Methods:
ListStores: Get all storesListCustomers: Get all customersCreateCustomer: Create a new customerCreateStore: Create a new store
RESTful API endpoints mirroring gRPC functionality:
- GET
/stores- List all stores - GET
/customers- List all customers - POST
/customers- Create a new customer - POST
/stores- Create a new store
- ListStores: Retrieves all stores with caching
- CreateStore: Creates new store with validation
- ListCustomers: Retrieves customers with intelligent caching strategy:
- Cache Check: First checks Redis cache for existing customers
- Database Fallback: If cache miss, fetches from PostgreSQL
- Cache Population: Stores results in Redis with TTL
- Error Handling: Returns Either<Error, Customer[]> for explicit error handling
- CreateCustomer: Creates new customer with business validation
gRPC Client β gRPC Server β Container β Use Case β Cache/Repository β Response
HTTP Client β Fastify β Controller β Use Case β Cache/Repository β Response
Request β Redis Check β [Hit: Return Data] or [Miss: PostgreSQL β Cache β Return Data]
# Generate Protocol Buffer types from .proto files
pnpm run build:proto
# Run database migrations
pnpm run migrate
# Generate Prisma client
pnpm run generate
# Start gRPC server in watch mode
pnpm run start:dev:grpc
# Start HTTP server in watch mode
pnpm run start:dev:http
# Seed database with test data
pnpm run seed# Lint and format with Biome
pnpm run lint
# Run all tests
pnpm test
# Run tests in watch mode
pnpm run test:watch# Open Prisma Studio (database GUI)
npx prisma studio
# Reset database (development only)
npx prisma migrate reset
# Deploy migrations (production)
npx prisma migrate deployThe project uses Vitest for testing with full TypeScript support:
# Run all tests once
pnpm test
# Run tests in watch mode
pnpm run test:watch
# Run tests with coverage
pnpm run test:coverageTest structure:
- Unit tests:
src/**/*.spec.ts - Integration tests:
test/**/*.test.ts - Domain tests:
test/domain/**/*.test.ts - Cache tests:
test/cache/**/*.test.ts
Create a .env file in the project root:
# Database
DATABASE_URL="postgres://grpc:grpc@localhost:5432/grpc"
# Cache
REDIS_URL="redis://localhost:6379"
REDIS_PASSWORD="redis"
# Application
NODE_ENV="development"
LOG_LEVEL="info"
# gRPC
GRPC_PORT="50051"
# HTTP
HTTP_PORT="3000"# Build TypeScript for production
pnpm run build
# Or use the production Dockerfile
docker build -t grpc-microservice .- Database: Configure PostgreSQL connection string
- Cache: Set up Redis instance with authentication
- Environment Variables: Set production environment variables
- Monitoring: Configure Prometheus scraping and Grafana dashboards
- Logging: Set up log aggregation with appropriate log levels
- Set
NODE_ENV=production - Configure database migrations
- Set up Redis with persistence
- Configure monitoring and alerting
- Set up log aggregation
- Configure SSL/TLS certificates
- Set up load balancing (if needed)
- Configure backup strategies
- Application metrics via prom-client
- Database connection pool metrics
- Cache hit/miss ratios
- Request latency and throughput
- Error rates and status codes
- Application performance overview
- Database performance metrics
- Cache performance monitoring
- Infrastructure health checks
- Structured logging with Pino
- Configurable log levels
- Request/response logging
- Error tracking and stack traces
- Testability: Each layer can be tested in isolation with dependency injection
- Maintainability: Clear separation of concerns and single responsibility
- Scalability: Easy to add new features without breaking existing code
- Flexibility: Swap implementations without affecting business logic
- Connection Pooling: Efficient database connection management
- Redis Caching: Reduces database load and improves response times
- gRPC Efficiency: Binary protocol for high-performance communication
- TypeScript: Compile-time optimization and error prevention
- Type Safety: Full TypeScript coverage prevents runtime errors
- Hot Reload: Instant feedback during development
- Code Quality: Automated formatting and linting
- Testing: Comprehensive test coverage with fast feedback
- Architecture: Follow Clean Architecture principles
- Types: Use TypeScript for complete type safety
- Errors: Implement proper error handling with Either pattern
- Caching: Add appropriate caching strategies
- Testing: Write tests for each layer (unit, integration, e2e)
- Code Quality: Use Biome for formatting and linting
- Follow the existing domain structure
- Use dependency injection for external dependencies
- Implement repository pattern for data access
- Use value objects for domain primitives
- Write descriptive commit messages
- Create feature branch from
main - Implement changes following project conventions
- Add/update tests for new functionality
- Ensure all tests pass and code quality checks pass
- Update documentation if needed
- Submit pull request with clear description
This project is licensed under the ISC License - see the LICENSE file for details.
Gustavo Murdiga
Note: This microservice demonstrates production-ready Clean Architecture implementation with practical examples of caching, database access, monitoring, and dual communication protocols (gRPC + HTTP) suitable for enterprise applications.