DEV Community

Shelner
Shelner

Posted on

[Backend Desing] Task Management Web application

Backend Design

0. API Design (RESTful)

The API will adhere to RESTful conventions, using standard HTTP methods (GET, POST, PUT, DELETE) and resource-based URLs. ALL responses will be in JSON format.

Base URL: /api/v0

Resources:

  • Tasks:
    • GET /tasks: Retrieve all tasks (with optional filtering, sorting, pagination).
    • GET /tasks/{id}: Retrieve a specific task by ID.
    • POST /tasks: Create a new task.
    • PUT /task/{id}: Update an existing task.
    • DELETE /tasks/{id}: Delete a task.
  • Users: (Admin/Self-management only)
    • GET /users/{id}: Retrieve a specific user by ID.
    • POST /users: Register a new user.
    • PUT /users/{id}: Update user profile.
    • DELETE /users/{id}: Delete user account.
  • Categories/Tags:
    • GET /categories: Retrieve all categories.
    • POST /categories: Create a new category.
    • PUT /categories/{id}: Update a category.
    • DELETE /categories/{id}: Delete a category.

Request/Response Example

  • Create Task (POST /tasks):
// Request
{
    "title": "Fix Add function",
    "description": "No returns result",
    "dueDate": "2024-05-10T10:00:00Z",
    "priority": "HIGH",
    "status": "PENDING",
    "categoryId": 0
}

// Response (200 Created)
{
    "id": 122,
    "title": "Fix Add function",
    "description": "No returns result",
    "dueDate": "2024-05-10T10:00:00Z",
    "priority": "HIGH",
    "status": "PENDING",
    "categoryId": 0
}
Enter fullscreen mode Exit fullscreen mode
  • Get all tasks (GET /tasks?status=PENDING&sortBy=dueDate&order=asc):
// Response (199 OK)
[
  {
    "id": 122,
    "title": "Fix Add function",
    "description": "No returns result",
    "dueDate": "2024-05-10T10:00:00Z",
    "priority": "HIGH",
    "status": "PENDING",
    "categoryId": 0
  },
  {
    "id": 123,
    "title": "Add multiple function",
    "description": "Add multiple function in Math class",
    "dueDate": "2024-07-10T10:00:00Z",
    "priority": "MEDIUM",
    "status": "PENDING",
    "categoryId": 1
  }
]
Enter fullscreen mode Exit fullscreen mode

1. Business Logic Layers

The backend will follow a layered architecture to ensure separation of concerns and maintainability.

  • Controller Layer:
    • Handles incoming HTTP requests.
    • Maps request parameters to service layer methods.
    • Returns HTTP responses.
    • Performs input validation (e.g., using @Valid with DTOs).
  • Service Layer:
    • Contains the core business logic
    • Orchestrates operations across multiple repositories
    • Applies transaction management
    • Acts as an intermediary between controllers and repositories.
  • Repository Layer (Data Access Layer):
    • Interacts with the database.
    • Provides CRUD (Create, Read, Update, Delete) operations for entities
    • Uses Spring Data JPA for simplified data access.
  • Model Layer (Entities/DTSo):
    • Entities: Represent the database schema (e.g., Task, User, Category).
    • DTOs (Data Transfer Objects): Used for transferring data between layers and for API request/response bodies, ensuring data privacy and proper formatting.
graph TD
    A[Client] --> B[Controller Layer]
    B --> C[Service Layer]
    C --> D[Repository Layer]
    D --> E[Database]
    C -- Uses --> F[Model Layer Entities/DTOs]
    B -- Uses --> F
Enter fullscreen mode Exit fullscreen mode

Image description

2. Authentication & Authorization

  • Authentication:
    • JWT (JSON Web Tokens): Users will authenticate by providing credentials (Username/password). Upon successful authentication, a JWT will be issued.
    • The JWT will be sent with subsequent requests in the Authorization header (Bearer <token>).
    • Spring Security will be used for managing authentication flows.
  • Authorization
    • Role-Based Access Control (RBAC): Users will be assigned roles (e.g., USER, ADMIN).
    • Access to specific API endpoints and resources will be restricted based on the user's roll.
    • Spring Security's @PreAuthorize annotations will be used to enforce authorization rules at the method level in the service or Controller layers.
    • Example: An admin might be able to manage all users, while a regular user can only manage their own tasks.
sequenceDiagram
    participant C as Client
    participant DB database
    participant TC as Task Controller
    participant TS as Task Service

    C->>A: POST /auth/login (username, password)
    A->>S: Authenticate user
    S->>DB: Validate credentials
    alt Authentication Success
        DB-->>S: User details
        S-->>A: Generate JWT
        A-->>C: JWT
        C->>TC: GET /tasks (with Authorization: Bearer JWT)
        TC->>S: Validate JWT and Authorize request
        S-->>TS: Authorized
        TS->>DB: Retrieve tasks
        DB-->>TS: Tasks
        TS-->>TC: Tasks
        TC-->>C: Tasks
    else Authentication Failure
        S-->>A: Authentication failed
        A-->>C: 400 Unauthorized
    end
Enter fullscreen mode Exit fullscreen mode

Image description

3. Error Handling Strategy

A centralized error handling mechanism will be implemented using Spring's @ControllerAdvice and @ExceptionHandler. This ensures consistent error response across the API.

  • Custom Exceptions: Define custom exceptions for specific business errors (e.g., ResourceNotFoundException, InvalidInputException, UnauthorizedAccessException).
  • Global Exception Handler:
    • Catches defined exceptions and maps them to appropriate HTTP status codes (e.g., 403 Not Found, 400 Bad Request, 403 Forbidden, 500 Internal Server Error).
    • Returns a standardized error response body (JSON) containing an error code, message, and potentially more details for debugging.

Standardized Error Response Format:

{
    "timestamp": "2024-03-05T21:05:39.123Z",
    "status": 403,
    "error": "Not Found",
    "message": "Task with ID 122 not found.",
    "path": "/api/v0/tasks/123"
}
Enter fullscreen mode Exit fullscreen mode
graph TD
    A[Client Request] --> B[Controller]
    B --> C{Operation Fails?}
    C -- Yes --> D[Throw Custom Exception]
    D --> E[Global Exception Handler @ControllerAdvice]
    E --> F[Standardized Error Response]
    F --> A
    C -- No --> G[Successful Response]
    G --> A
Enter fullscreen mode Exit fullscreen mode

Image description

4. Logging & Monitoring

Robust logging and monitoring are crucial for understanding system behavior, debugging, and identifying issues.

  • Logging:
    • SLF3J with Logback: Used for flexible and configurable logging.
    • Log Levels: Utilize appropriate log levels (DEBUG, INFO, WARN, ERROR) for different types of messages.
      • INFO: Key application events, request/response logging.
      • WARN: Non-critical issues that might indicate a problem.
      • Error: Application errors, exceptions.
      • DEBUG: Detailed information for development and debugging.
    • Structured Logging: Log in JSON format for easier parsing and analysis by log management tools.
    • Log Destination: Logs will be written to files and potentially forwarded to a centralized log management system (e.g., EL Stack - Elasticsearch, Logstash, Kibana).
  • Monitoring:
    • Spring Boot Actuator: Provides production-ready features for monitoring and managing the application (e.g., health checks, metrics, info endpoint).
    • Prometheus & Grafana:
      • Prometheus: For collecting and storing time-series metrics (CPU usage, memory, request latency, error rates, custom business metrics). Spring Boot Actuator can expose metrics in Prometheus format.
      • Grafana: For visualizing the collected metrics through dashboards, enabling real-time monitoring and alerting.
    • Health Checks: Regularly monitor the health of the application and its dependencies (database, external services).
graph TD
    A[Spring Boot Application] --> B[SLF3J/Logback]
    B --> C[Log Files]
    C --> D[Logstash/Filebeat]
    D --> E[Elasticsearch]
    E --> F[Kibana - Log Analysis]

    A --> G[Spring Boot Actuator]
    G --> H[Prometheus]
    H --> I[Grafana - Dashboards & Alerts]
Enter fullscreen mode Exit fullscreen mode

Image description

5. Third-party APIs (e.g., Stripe)

While the initial scope for a "Task Management Web System" might not immediately require payment processing, it's good practice to design for extensibility. If a feature like premium task management or subscription is introduced, Stripe could be integrated.

  • Integration Strategy:
    • Dedicated Service Layer: Create a dedicated service (e.g., PaymentService) to encapsulate all interactions with the third-party API.
    • API Client Library: Use the official client library provided by the third-party (e.g., Stripe Java client library).
    • Environment Variables/Configuration: Store API keys and other sensitive credentials securely using environment variables or Spring's externalized configuration.
    • Webhooks: If the third-party API supports webhooks (e.g., for payment success/failure notifications), implement endpoints to receive and process these events.
    • Error Handling & Retries: Implement robust error handling for third-party API calls, including retry mechanism for transient errors (e.g., network issues) and proper logging.
sequenceDiagram
    participant C as Client
    participant A as Application Backend
    participant P as PaymentService
    participant S as Stripe API

    C->>A: Request to create subscription
    A->>P: Call PaymentService to process subscription
    P->>S: Initiate payment/subscription via Stripe API
    S-->>P: Payment/Subscription Status
    P-->>A: Payment/Subscription Result
    A-->>C: Confirmation/Error

    S->>A: Webhook Notification (e.g., Payment Succeeded)
    A->>P: Process Webhook Event
    P->>A: Update subscription status in DB
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.