404 Not Found

404 Not Found


nginx

Comprehensive Hands-On Exercise: OrderFlow Project Design

Project design is the blueprint for development—requirements determine the direction, technology selection determines the approach, and design determines the architecture. Preparation is half the battle.

1. What You'll Learn


2. A Product Manager's True Story

(1) Pain Point: The Gap Between Requirements and Code

Charlie approached Alice with a vague requirements document: "We need an e-commerce order management system." Alice asked, "What features does it need?" "What are the different user roles? What attributes do the products have? How are orders and payments linked?" Charlie couldn't explain it clearly, so Alice had to guess based on her experience. As a result, after two weeks of development, Charlie said, "This isn't what I wanted."

(2) System Design Solutions

Design first, then develop—Requirements Analysis → Technology Selection → Database Design → API Specifications. Confirm each step with Charlie:

100%
graph TD
    A["Requirements<br/>Analysis"] --> B["Tech Stack<br/>Selection"]
    B --> C["Database<br/>Design"]
    C --> D["API<br/>Specification"]
    D --> E["Development<br/>Plan"]

(3) Revenue

After Alice and Charlie spent two days finalizing the system design, the development direction was clear, and they delivered an MVP that met expectations within three weeks. Charlie said, "It was exactly what I wanted the first time around."


3. Requirements Analysis

(1) Four Major Modules

Module Core Features User Roles
User Management Registration, Login, Personal Information, Role Management ALL
Product Management CRUD, Categories, Search, Inventory Management ADMIN
Order Management Place Orders, View Orders, Cancel Orders, Automatic Cancellation Due to Timeout CUSTOMER / ADMIN
Payment Management Initiate Payments, Callback Handling, Refunds CUSTOMER / ADMIN

(2) Role-Permission Matrix

Feature CUSTOMER ADMIN
Sign Up / Log In
Browse Products
Search for Products
Create / Manage Products
Place Order
View Your Orders
View All Orders
Cancel Your Order
Cancel any order
Initiate Payment
Process Refund

(1) ▶ Example: User Story

TEXT
As a CUSTOMER, I want to:
  - Browse and search products
  - Add products to cart (future)
  - Place an order with multiple items
  - View my order history
  - Cancel an unpaid order within 30 minutes
  - Pay for an order
  - View payment status

As an ADMIN, I want to:
  - Manage products (CRUD)
  - View all orders
  - Cancel any order
  - Process refunds
  - View business statistics

Output:

TEXT
Execution Successful

4. Technology Selection

(1) Product Selection Decision Matrix

Decision Point Option A Option B Choice Reason
Web Frameworks WebMVC WebFlux WebMVC Primarily CRUD, concurrency < 5,000; WebMVC is simpler
Authentication Method Session JWT JWT Microservices architecture, multi-instance deployment, stateless authentication
Caching Strategy Local Caffeine Distributed Redis L1 Caffeine + L2 Redis Fast local access to hot data; distributed caching ensures consistency
Database PostgreSQL MySQL MySQL Familiar to the team, mature ecosystem
Database Access JPA MyBatis JPA More natural object mapping, reduces the need to write SQL
API Documentation SpringDoc Manual SpringDoc Automatically Generate OpenAPI Documentation

(2) Technology Stack Overview

Level Technology Version
Language Java 17 LTS
Framework Spring Boot 3.2.x
Web Spring MVC 6.x
Security Spring Security + JWT 6.x
Database MySQL 8.0
ORM Spring Data JPA 3.x
Caching Caffeine + Redis 3.x / 7.x
Validation Bean Validation 3.x
Testing JUnit 5 + Mockito + TestContainers 5.x
Documentation SpringDoc OpenAPI 2.x
Monitoring Actuator + Micrometer 3.x
Deployment Docker + Kubernetes 24.x / 1.28

5. Database Design

(1) Complete ER Diagram

100%
erDiagram
    USER ||--o{ ORDER : "places"
    PRODUCT ||--o{ ORDER_ITEM : "included in"
    ORDER ||--o{ ORDER_ITEM : "contains"
    ORDER ||--o| PAYMENT : "has"

    USER {
        bigint id PK
        varchar username UK
        varchar email UK
        varchar password_hash
        varchar role
        timestamp created_at
        timestamp updated_at
    }
    PRODUCT {
        bigint id PK
        varchar name
        varchar sku UK
        decimal price
        int stock
        varchar category
        tinyint status
        timestamp created_at
        timestamp updated_at
    }
    ORDER {
        bigint id PK
        bigint user_id FK
        varchar order_number UK
        varchar status
        decimal total_amount
        timestamp created_at
        timestamp updated_at
    }
    ORDER_ITEM {
        bigint id PK
        bigint order_id FK
        bigint product_id FK
        int quantity
        decimal unit_price
        decimal subtotal
    }
    PAYMENT {
        bigint id PK
        bigint order_id FK
        varchar transaction_id UK
        varchar method
        varchar status
        decimal amount
        timestamp paid_at
        timestamp created_at
    }

(1) ▶ Example: DDL table creation statement

SQL
CREATE TABLE users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    role VARCHAR(20) NOT NULL DEFAULT 'CUSTOMER',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

CREATE TABLE products (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    sku VARCHAR(20) NOT NULL UNIQUE,
    price DECIMAL(10,2) NOT NULL,
    stock INT NOT NULL DEFAULT 0,
    category VARCHAR(50),
    status TINYINT NOT NULL DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_product_name (name),
    INDEX idx_product_category (category)
);

CREATE TABLE orders (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT NOT NULL,
    order_number VARCHAR(20) NOT NULL UNIQUE,
    status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
    total_amount DECIMAL(10,2) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_order_user (user_id),
    INDEX idx_order_status_created (status, created_at DESC),
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE order_items (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    order_id BIGINT NOT NULL,
    product_id BIGINT NOT NULL,
    quantity INT NOT NULL,
    unit_price DECIMAL(10,2) NOT NULL,
    subtotal DECIMAL(10,2) NOT NULL,
    FOREIGN KEY (order_id) REFERENCES orders(id),
    FOREIGN KEY (product_id) REFERENCES products(id)
);

CREATE TABLE payments (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    order_id BIGINT NOT NULL UNIQUE,
    transaction_id VARCHAR(50) UNIQUE,
    method VARCHAR(20) NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
    amount DECIMAL(10,2) NOT NULL,
    paid_at TIMESTAMP NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (order_id) REFERENCES orders(id)
);

Output:

TEXT
CREATE TABLE

6. API Specification Design

(1) RESTful API Specifications

(1) ▶ Example: List of API Endpoints

Module Method URI Description Permissions
Auth POST /api/v1/auth/login Login Public
Auth POST /api/v1/auth/register Register Public
Product GET /api/v1/products Product List Public
Product GET /api/v1/products/{id} Product Details Public
Product POST /api/v1/products Create Product ADMIN
Product PUT /api/v1/products/{id} Update Product ADMIN
Product DELETE /api/v1/products/{id} Delete Product ADMIN
Order POST /api/v1/orders Place Order CUSTOMER+
Order GET /api/v1/orders My Orders CUSTOMER+
Order GET /api/v1/orders/{id} Order Details Owner/ADMIN
Order GET /api/v1/admin/orders All Orders ADMIN
Order DELETE /api/v1/orders/{id} Cancel Order Owner/ADMIN
Payment POST /api/v1/payments Initiate Payment CUSTOMER+
Payment POST /api/v1/payments/callback Payment Callback Internal

(2) ▶ Example: Standardized Response Format

JAVA
// Success response
public record ApiResponse<T>(
    int code,
    String message,
    T data,
    Instant timestamp
) {
    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<>(200, "OK", data, Instant.now());
    }
    public static <T> ApiResponse<T> created(T data) {
        return new ApiResponse<>(201, "Created", data, Instant.now());
    }
}

// Paged response
public record PagedResponse<T>(
    List<T> content,
    int page,
    int size,
    long totalElements,
    int totalPages
) {}

Output:

TEXT
// Execution Successful

(3) ▶ Example: Pagination and Sorting Parameters

BASH
# List products with pagination, sorting, and filtering
GET /api/v1/products?page=0&size=20&sort=price,desc&category=electronics&minPrice=100&maxPrice=999

Output:

TEXT
# Command executed successfully

7. Development Plan and Module Assignments

(1) ▶ Example: Iteration Plan

Sprint Iteration Goal Deliverables
Sprint 1 Weeks 1-2 Basic Framework Project Structure + Authentication + Product CRUD
Sprint 2 Weeks 3-4 Core Business Order Module + Transactions + Validation + Exceptions
Sprint 3 Weeks 5-6 Advanced Features Caching + Scheduled Tasks + Asynchronous Notifications
Sprint 4 Weeks 7-8 Operations and Deployment Docker + K8s + Monitoring and Alerts

8. Comprehensive Example: OrderFlow Project Design Document

MARKDOWN
# OrderFlow System Design Document

## 1. Business Requirements
- E-commerce order management system
- 4 modules: User, Product, Order, Payment
- 2 roles: CUSTOMER, ADMIN
- Expected: 10,000 DAU, 1,000 orders/day

## 2. Tech Stack
- Java 17 + Spring Boot 3.2.x
- MySQL 8.0 + Spring Data JPA
- Redis 7 + Caffeine (two-level cache)
- Spring Security + JWT (OAuth2 Resource Server)
- Docker + Kubernetes deployment

## 3. Database Design
- 5 tables: users, products, orders, order_items, payments
- Indexes on high-frequency query columns

## 4. API Specification
- RESTful API with versioning (/api/v1/)
- JWT Bearer authentication
- Unified response format: ApiResponse<T>
- Pagination: page, size, sort parameters

## 5. Non-functional Requirements
- P99 latency < 100ms
- Error rate < 0.1%
- Availability > 99.9%
- Automated test coverage > 80%

❓ FAQ

Q Why choose WebMVC over WebFlux?
A OrderFlow primarily involves CRUD operations, with an expected concurrency of < 5,000 QPS; WebMVC is simpler and more mature. WebFlux is suitable for I/O-intensive, high-concurrency, and real-time streaming scenarios; using it for a CRUD project would actually increase complexity.
Q Why use a two-level cache instead of just Redis?
A L1 Caffeine is the fastest (nanosecond-level), while L2 Redis ensures consistency across multiple instances. Hot data hits the local cache, reducing Redis network overhead.
Q Should API versioning use URL paths or headers?
A URL path versioning (/api/v1/) is more intuitive, easier to test, and more SEO-friendly. Header versioning is more RESTful but harder to debug. In practice, we recommend URL versioning.
Q How is the security of payment callbacks ensured?
A 1) The callback URL is accessible only from the internal network; 2) The callback signature is verified; 3) Idempotent processing is used (repeated callbacks do not result in duplicate charges); 4) Callback logs are recorded for reconciliation purposes.
Q How should soft deletes and hard deletes be handled in database design?
A Use soft deletes (status=CANCELLED) for critical business data (orders, payments) to preserve audit trails. Auxiliary data (test products) can be hard deleted. Soft deletes require filtering out deleted records in all queries.
Q How detailed should project design documents be?
A They should be detailed enough for new team members to understand the big picture of the system. They should include: business requirements, technology choices and the rationale behind them, database design, API specifications, and non-functional requirements. There's no need to include code implementation details—the code itself serves as the most detailed documentation.

📖 Summary


📝 Exercises

  1. Basic Task (Difficulty: ⭐): Complete the OrderFlow requirements analysis document, listing all user stories and API endpoints.

  2. Advanced Problem (Difficulty: ⭐⭐): Complete the database ER design and DDL table creation statements, including all indexes. Design a standardized response format and error code system.

  3. Challenge (Difficulty: ⭐⭐⭐): Use SpringDoc OpenAPI to write an API specification and generate an interactive API documentation page. Consider how to keep the API documentation in sync with the code implementation.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏