AI Context: This is the single source of truth for domain-specific business rules. For current status: see
../docs/status/progress.yamlFor project overview: see../docs/index.md
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.
-
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
-
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
-
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
-
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
-
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
-
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)
-
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
-
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
-
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
-
Request Limits
- Authenticated users: 1000 requests per hour
- Unauthenticated users: 100 requests per hour
- Admin users: No rate limiting
-
Throttling
- Excessive requests return HTTP 429 Too Many Requests
- Rate limit headers included in all responses
- Exponential backoff recommended for clients
-
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
-
Idempotency
- POST requests should be idempotent where possible
- Use unique request IDs for duplicate detection
- Duplicate requests return the original response
-
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
-
Validation Errors
- Field-level validation errors return HTTP 400
- Include field name and validation message
- Multiple validation errors returned together
-
Business Logic Errors
- Business rule violations return HTTP 422 Unprocessable Entity
- Include clear, user-friendly error messages
- Log detailed error information for debugging
-
Audit Trail
- All entity changes should be audited
- Include user ID, timestamp, and operation type
- Audit logs should be immutable
- Retention period: 7 years
-
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
-
Security Logging
- All authentication attempts logged
- Authorization failures logged with user ID
- Sensitive data must not be logged
- Security logs retained for 1 year
-
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
-
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
-
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
- Use plural nouns for collections (
- 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
- Use URI versioning (
-
List Endpoints
- All list endpoints must support pagination
- Default page size: 20 items
- Maximum page size: 100 items
- Include total count in response headers
-
Sorting
- Support sorting by multiple fields
- Default sort order should be specified
- Format:
?sort=field1,asc&sort=field2,desc
-
Filtering
- Support filtering on common fields
- Use query parameters for filters
- Document available filters in API docs
-
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
-
Cache Levels
- Application-level caching with Caffeine
- Distributed caching with Redis for multi-instance deployments
- HTTP caching headers for client-side caching
-
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
-
Connection Pooling
- Configure appropriate connection pool size
- Monitor connection pool metrics
- Set appropriate timeouts
-
Background Tasks
- Long-running operations should be asynchronous
- Email sending should be async
- Report generation should be async
- Use appropriate thread pool configuration
-
Message Queues
- Use message queues (Kafka/RabbitMQ) for decoupling
- Implement proper error handling and retry logic
- Monitor queue depths and processing times
-
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)
-
Data Validation
- Use Bean Validation for request validation
- Implement custom validators for complex rules
- Validate on both client and server side
-
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
-
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
- Cross-Origin Requests
- Configure allowed origins
- Specify allowed methods and headers
- Set appropriate max age for preflight requests
- Never use wildcard (*) in production
-
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
-
Data Retention
- Define retention periods for different data types
- Implement automatic data purging
- Maintain audit trail of deletions
-
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
-
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
-
Application Health
- Implement Spring Boot Actuator health endpoints
- Monitor database connectivity
- Monitor external service availability
- Include custom health indicators
-
Metrics
- Track request count and response times
- Monitor error rates
- Track business metrics (user registrations, etc.)
- Use Micrometer for metrics collection
- 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