Skip to content

Latest commit

 

History

History
324 lines (247 loc) · 10.1 KB

File metadata and controls

324 lines (247 loc) · 10.1 KB

Business Rules - Java Spring Boot Boilerplate

AI Context: This is the single source of truth for domain-specific business rules. For current status: see ../docs/status/progress.yaml For project overview: see ../docs/index.md

Overview

This document defines the business rules and domain logic for the Java Spring Boot boilerplate. These rules should be implemented in the Service layer and enforced throughout the application.

General Business Rules

Data Validation

  1. Required Fields

    • All entities must have valid created and updated timestamps
    • Required fields must be validated at the DTO level using Bean Validation
    • Null values in required fields should result in HTTP 400 Bad Request
  2. Data Constraints

    • Email addresses must be unique across the system
    • Passwords must meet minimum security requirements (8+ characters, mixed case, numbers)
    • String fields have maximum lengths defined in entity annotations
  3. Data Integrity

    • Foreign key relationships must be validated before deletion
    • Soft delete should be preferred over hard delete where applicable
    • Cascade operations must be explicitly defined

Authentication & Authorization

  1. User Authentication

    • Users must authenticate to access protected endpoints
    • JWT tokens expire after configurable duration (default: 24 hours)
    • Refresh tokens can be used to obtain new access tokens
    • Failed login attempts should be logged and rate-limited
  2. Authorization

    • Role-based access control (RBAC) must be enforced
    • Each endpoint should have defined required roles
    • Admin users have elevated privileges
    • Users can only access their own data unless admin
  3. Password Security

    • Passwords must be hashed using BCrypt
    • Minimum password strength requirements enforced
    • Password reset tokens expire after 1 hour
    • Old passwords cannot be reused (last 5 passwords)

Domain-Specific Rules

User Management

  1. User Registration

    • Email must be unique and valid format
    • Password must meet security requirements
    • New users are inactive by default (require email verification)
    • Default role is CLIENT
  2. User Profile Updates

    • Users can update their own profile
    • Admins can update any user profile
    • Email changes require re-verification
    • Role changes can only be performed by admins
  3. User Deletion

    • Users can deactivate their own account
    • Only admins can permanently delete users
    • Deletion should archive user data (soft delete)
    • Associated data should be handled according to retention policy

API Rate Limiting

  1. Request Limits

    • Authenticated users: 1000 requests per hour
    • Unauthenticated users: 100 requests per hour
    • Admin users: No rate limiting
  2. Throttling

    • Excessive requests return HTTP 429 Too Many Requests
    • Rate limit headers included in all responses
    • Exponential backoff recommended for clients

Transaction Management

  1. Database Transactions

    • All write operations must be transactional
    • Read-only operations should use @Transactional(readOnly = true)
    • Transaction timeout: 30 seconds
    • Failed transactions should rollback completely
  2. Idempotency

    • POST requests should be idempotent where possible
    • Use unique request IDs for duplicate detection
    • Duplicate requests return the original response

Error Handling

  1. Error Responses

    • All errors return consistent error response format
    • Include timestamp, status code, and error message
    • Sensitive information should not be exposed in error messages
    • Stack traces only included in development environment
  2. Validation Errors

    • Field-level validation errors return HTTP 400
    • Include field name and validation message
    • Multiple validation errors returned together
  3. Business Logic Errors

    • Business rule violations return HTTP 422 Unprocessable Entity
    • Include clear, user-friendly error messages
    • Log detailed error information for debugging

Audit and Logging

  1. Audit Trail

    • All entity changes should be audited
    • Include user ID, timestamp, and operation type
    • Audit logs should be immutable
    • Retention period: 7 years
  2. Application Logging

    • ERROR: System errors requiring immediate attention
    • WARN: Potential issues (failed validations, deprecations)
    • INFO: Important business events (user creation, orders)
    • DEBUG: Detailed diagnostic information
  3. Security Logging

    • All authentication attempts logged
    • Authorization failures logged with user ID
    • Sensitive data must not be logged
    • Security logs retained for 1 year

API Design Rules

REST API Conventions

  1. HTTP Methods

    • GET: Retrieve resources (no side effects)
    • POST: Create new resources
    • PUT: Full update of existing resources
    • PATCH: Partial update of existing resources
    • DELETE: Remove resources
  2. Status Codes

    • 200 OK: Successful GET, PUT, PATCH
    • 201 Created: Successful POST
    • 204 No Content: Successful DELETE
    • 400 Bad Request: Invalid input
    • 401 Unauthorized: Authentication required
    • 403 Forbidden: Insufficient permissions
    • 404 Not Found: Resource doesn't exist
    • 422 Unprocessable Entity: Business rule violation
    • 500 Internal Server Error: System error
  3. Resource Naming

    • Use plural nouns for collections (/users, /products)
    • Use hierarchical structure for related resources (/users/{id}/orders)
    • Use kebab-case for multi-word resources (/order-items)
    • Avoid verbs in endpoint names

Versioning

  1. API Versioning
    • Use URI versioning (/api/v1/users)
    • Major version changes for breaking changes
    • Maintain backward compatibility within major versions
    • Deprecation notice period: 6 months

Pagination and Filtering

  1. List Endpoints

    • All list endpoints must support pagination
    • Default page size: 20 items
    • Maximum page size: 100 items
    • Include total count in response headers
  2. Sorting

    • Support sorting by multiple fields
    • Default sort order should be specified
    • Format: ?sort=field1,asc&sort=field2,desc
  3. Filtering

    • Support filtering on common fields
    • Use query parameters for filters
    • Document available filters in API docs

Performance Rules

Caching Strategy

  1. Cache Usage

    • Frequently accessed data should be cached
    • Cache keys should be meaningful and namespaced
    • Cache expiration times defined per entity type
    • Cache invalidation on updates
  2. Cache Levels

    • Application-level caching with Caffeine
    • Distributed caching with Redis for multi-instance deployments
    • HTTP caching headers for client-side caching

Database Optimization

  1. Query Optimization

    • Use appropriate indexes on frequently queried fields
    • Avoid N+1 query problems (use JOIN FETCH)
    • Use pagination for large result sets
    • Monitor and optimize slow queries
  2. Connection Pooling

    • Configure appropriate connection pool size
    • Monitor connection pool metrics
    • Set appropriate timeouts

Async Processing

  1. Background Tasks

    • Long-running operations should be asynchronous
    • Email sending should be async
    • Report generation should be async
    • Use appropriate thread pool configuration
  2. Message Queues

    • Use message queues (Kafka/RabbitMQ) for decoupling
    • Implement proper error handling and retry logic
    • Monitor queue depths and processing times

Security Rules

Input Validation

  1. Sanitization

    • All user input must be sanitized
    • Prevent SQL injection with parameterized queries
    • Prevent XSS attacks by encoding output
    • Validate file uploads (type, size, content)
  2. Data Validation

    • Use Bean Validation for request validation
    • Implement custom validators for complex rules
    • Validate on both client and server side

Data Protection

  1. Sensitive Data

    • Passwords must be hashed, never stored plain text
    • PII data should be encrypted at rest
    • Credit card data must follow PCI DSS
    • Use HTTPS for all API communication
  2. Data Access

    • Implement row-level security where applicable
    • Users can only access their own data
    • Admin access should be logged
    • Implement data masking for sensitive fields

CORS Configuration

  1. Cross-Origin Requests
    • Configure allowed origins
    • Specify allowed methods and headers
    • Set appropriate max age for preflight requests
    • Never use wildcard (*) in production

Compliance and Standards

GDPR Compliance

  1. Data Privacy

    • Users can request their data (data portability)
    • Users can request data deletion (right to be forgotten)
    • Explicit consent required for data collection
    • Privacy policy must be accessible
  2. Data Retention

    • Define retention periods for different data types
    • Implement automatic data purging
    • Maintain audit trail of deletions

Testing Requirements

  1. Test Coverage

    • Minimum 80% code coverage for services
    • All business rules must have test cases
    • Integration tests for API endpoints
    • End-to-end tests for critical workflows
  2. Test Types

    • Unit tests with JUnit 5 and Mockito
    • Integration tests with @SpringBootTest
    • API tests with MockMvc or REST Assured
    • Performance tests for critical endpoints

Monitoring and Observability

Health Checks

  1. Application Health

    • Implement Spring Boot Actuator health endpoints
    • Monitor database connectivity
    • Monitor external service availability
    • Include custom health indicators
  2. Metrics

    • Track request count and response times
    • Monitor error rates
    • Track business metrics (user registrations, etc.)
    • Use Micrometer for metrics collection

Alerting

  1. Alert Conditions
    • Error rate exceeds threshold
    • Response time degradation
    • Database connection pool exhaustion
    • Disk space running low

Note: These business rules should be reviewed and updated regularly as requirements evolve. All changes must be documented and communicated to the development team.

Last Updated: 2025-10-08