Skip to content

Pinchez25/library-microservices

Repository files navigation

📚 Enhanced Library Management System – Microservices Architecture

🔍 System Overview

A comprehensive digital library platform managing books, members, borrowing, payments, notifications, and analytics. Perfect for mastering enterprise-grade microservices patterns whilst remaining approachable for learning.


🧩 Core Microservices (Essential - Start Here)

1. Book Service 📚

Purpose: Catalogue and inventory management

Features:

  • CRUD operations for books
  • Full-text search with filters (title, author, genre, ISBN, language)
  • Real-time availability tracking
  • Book metadata management (publisher, edition, categories, ratings)
  • Soft delete with archive functionality

Key Endpoints:

GET    /books?search=&genre=&available=true
GET    /books/:id/availability
POST   /books
PUT    /books/:id
DELETE /books/:id (soft delete)
GET    /books/recommended/:memberId

Database: MariaDB with full-text search Port: 3001


2. Member Service 👥

Purpose: User lifecycle and authentication

Features:

  • JWT-based authentication with refresh tokens
  • Profile management with preferences
  • Member status workflow (active → expired → suspended)
  • Role-based access control (member, librarian, admin)
  • Password reset via email/SMS with OTP

Key Endpoints:

POST   /auth/login
POST   /auth/refresh
POST   /members/register
GET    /members/profile
PUT    /members/:id/status
POST   /members/password-reset

Database: MariaDB with encrypted passwords Port: 3002


3. Borrowing Service 📖

Purpose: Core lending business logic

Features:

  • Issue/return workflow with validation
  • Borrowing limits per member type (student: 3, faculty: 10)
  • Queue management for popular books (FIFO)
  • Renewal system with maximum limits
  • Overdue detection and escalation

Key Endpoints:

POST   /borrowings (issue book)
PUT    /borrowings/:id/return
POST   /borrowings/:id/renew
GET    /borrowings/member/:id
GET    /borrowings/overdue
POST   /reservations

Database: MAriadb with borrowing history Port: 3306


🚀 Enhanced Services (Phase 2)

4. Notification Service 📧

Purpose: Multi-channel communication hub

Features:

  • Email, SMS, push notifications, in-app messages
  • Template management with personalisation
  • Event-driven notifications with retry logic
  • Member preference management
  • Notification scheduling and batching

Key Endpoints:

POST   /notifications/send
GET    /notifications/member/:id
PUT    /notifications/preferences/:memberId
GET    /notifications/templates

Database: MongoDB for flexible notification logs Port: 3004


5. Fine Service 💰

Purpose: Financial penalties and payments

Features:

  • Configurable fine calculation rules
  • Multiple payment methods (M-Pesa, card, cash)
  • Fine waiver approval workflow
  • Payment history and receipts
  • Automated fine escalation

Key Endpoints:

GET    /fines/member/:id
POST   /fines/calculate
POST   /fines/pay
POST   /fines/waive/:id
GET    /fines/reports

Database: MariaDB with payment audit trail Port: 3005


6. Search Service 🔍

Purpose: Intelligent search and discovery

Features:

  • Elasticsearch integration for books and members
  • Auto-complete suggestions
  • Faceted search (genre, year, author, availability)
  • Search analytics and popular queries
  • Fuzzy matching for typos

Key Endpoints:

GET    /search/books?q=&filters=
GET    /search/suggestions?q=
GET    /search/popular-queries
GET    /search/facets

Database: Elasticsearch cluster Port: 3007


🎯 Supporting Services (Phase 3)

7. Analytics Service 📊

Purpose: Business intelligence and reporting

Features:

  • Real-time borrowing trends and patterns
  • Member engagement metrics
  • Popular books and genres analysis
  • Overdue pattern detection
  • Custom dashboard data

Key Endpoints:

GET    /analytics/dashboard
GET    /analytics/borrowing-trends
GET    /analytics/popular-books
GET    /analytics/member-activity/:id
GET    /analytics/overdue-patterns

Database: ClickHouse or MariaDB with time-series data Port: 3006


8. Admin Service 🛠️

Purpose: Administrative operations

Features:

  • Bulk operations (import/export books)
  • System configuration management
  • User role management
  • Audit log viewing
  • System health monitoring

Key Endpoints:

POST   /admin/books/bulk-import
GET    /admin/audit-logs
PUT    /admin/system-config
GET    /admin/health-check
POST   /admin/users/:id/promote

Database: MariaDB with admin audit logs Port: 3008


9. API Gateway 🚪

Purpose: Single entry point and cross-cutting concerns

Features:

  • Request routing with load balancing
  • JWT authentication and authorization
  • Rate limiting (per user, per IP)
  • Request/response logging with correlation IDs
  • Circuit breaker pattern for resilience

Port: 3000


🔗 Communication Architecture

Synchronous Communication (HTTP/REST)

API Gateway → All Services (routing)
Borrowing Service → Book Service (availability check)
Borrowing Service → Member Service (validation)
Fine Service → Borrowing Service (overdue data)
Admin Service → All Services (management operations)

Asynchronous Communication (Event-Driven)

Event Bus: RabbitMQ (recommended) or Apache Kafka

Core Events:

// Book Events
{ type: 'BookIssued', bookId, memberId, dueDate, borrowingId }
{ type: 'BookReturned', bookId, memberId, returnDate, borrowingId }
{ type: 'BookReserved', bookId, memberId, position }

// Member Events
{ type: 'MemberRegistered', memberId, membershipType }
{ type: 'MemberStatusChanged', memberId, oldStatus, newStatus }

// Fine Events
{ type: 'FineCalculated', memberId, amount, reason, borrowingId }
{ type: 'FinePaid', memberId, amount, paymentMethod }

Event Flow Example:

BookIssued Event:
├── Notification Service: Send confirmation email
├── Fine Service: Set up due date monitoring
├── Book Service: Update availability count
├── Analytics Service: Record borrowing stats
└── Search Service: Update book popularity index

🧰 Technology Stack

Backend Framework

  • Node.js with Express.js and TypeScript
  • Fastify alternative for better performance

Databases

  • MariaDB: Main relational data (books, members, borrowings, fines)
  • MongoDB: Flexible data (notifications, logs)
  • Redis: Caching and session storage
  • Elasticsearch: Search indexing
  • ClickHouse: Analytics data (optional)

Message Queue

  • RabbitMQ: Event streaming and async communication
  • Redis Pub/Sub: Lightweight alternative

Infrastructure

  • Docker + Docker Compose: Development environment
  • Kubernetes: Production orchestration
  • NGINX: Load balancer and reverse proxy

Monitoring & Observability

  • Prometheus + Grafana: Metrics and dashboards
  • Jaeger: Distributed tracing
  • ELK Stack: Centralised logging
  • Health checks: Custom endpoints per service

🛡️ Security & Best Practices

Authentication & Authorization

  • JWT tokens with short expiry (15 mins) + refresh tokens
  • Role-based access control (RBAC) middleware
  • API key authentication for service-to-service calls

Data Protection

  • Password hashing with bcrypt (cost factor 12)
  • Input validation with Joi or Yup
  • SQL injection protection with parameterised queries
  • Rate limiting to prevent abuse

Infrastructure Security

  • HTTPS everywhere (Let's Encrypt certificates)
  • Docker secrets for sensitive configuration
  • Network isolation between services
  • Regular security updates and vulnerability scanning

🧪 Testing Strategy

Testing Pyramid

  1. Unit Tests (70%): Jest with high coverage (>90%)
  2. Integration Tests (20%): Supertest with test databases
  3. Contract Tests (5%): Pact for API contracts
  4. End-to-End Tests (5%): Playwright for critical user journeys

Testing Tools

# Unit & Integration
npm test                    # Jest test suite
npm run test:coverage       # Coverage reports

# Load Testing
k6 run load-tests/          # Performance testing
artillery run scenarios/    # Load testing scenarios

# Contract Testing
pact-broker publish         # API contract testing

📁 Development Workflow

Repository Structure

library-microservices/
├── services/
│   ├── books/              # Book Service
│   ├── members/            # Member Service
│   ├── borrowing/          # Borrowing Service
│   └── ...
├── shared/
│   ├── events/             # Event schemas
│   ├── middleware/         # Common middleware
│   └── utils/              # Shared utilities
├── infrastructure/
│   ├── docker-compose.yml  # Development setup
│   ├── k8s/               # Kubernetes manifests
│   └── monitoring/        # Prometheus, Grafana configs
└── docs/
    ├── api/               # OpenAPI specifications
    └── architecture/      # System documentation

Development Order (Recommended)

  1. Infrastructure Setup: Docker Compose, databases, message queue
  2. Book Service: Simplest CRUD operations
  3. Member Service: Authentication and user management
  4. Borrowing Service: Core business logic
  5. API Gateway: Request routing and authentication
  6. Notification Service: Async communication patterns
  7. Fine Service: Business rules and calculations
  8. Search Service: Advanced querying
  9. Analytics Service: Data aggregation
  10. Admin Service: Management operations

🚀 Deployment & DevOps

CI/CD Pipeline

# GitHub Actions example
stages:
  - lint: ESLint, Prettier
  - test: Unit, integration tests
  - build: Docker images
  - security: SAST scanning
  - deploy: Kubernetes rollout

Monitoring Dashboard

  • Service health: Response times, error rates
  • Business metrics: Books borrowed, active members
  • Infrastructure: CPU, memory, disk usage
  • Alerts: Slack/email notifications for issues

🎯 Learning Outcomes

By building this system, you'll master:

Microservices Patterns

  • Service decomposition strategies
  • Database per service pattern
  • API Gateway and BFF patterns
  • Event-driven architecture
  • Circuit breaker and bulkhead patterns

Communication Patterns

  • Synchronous vs asynchronous communication
  • Request-response vs publish-subscribe
  • Event sourcing and CQRS basics
  • Service mesh concepts

Data Management

  • Distributed data patterns
  • Eventual consistency
  • Transaction patterns (Saga pattern)
  • Caching strategies

Operational Excellence

  • Service discovery and registration
  • Configuration management
  • Monitoring and alerting
  • Distributed tracing
  • Chaos engineering basics

💡 Next Steps

  1. Start Small: Begin with Books and Members services
  2. Add Complexity Gradually: Introduce events and async patterns
  3. Focus on Observability: Add monitoring early
  4. Test Everything: Comprehensive testing strategy
  5. Document Thoroughly: API docs and architectural decisions

This enhanced architecture provides a comprehensive learning platform whilst remaining manageable. Each service teaches specific microservices concepts, and the system scales naturally as your understanding grows.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors