Làm thế nào để sử dụng phân tích rổ hàng trong việc sắp xếp layout web và tạo bundle khuyến mãi tự động?

Phân tích rổ hàng (Market Basket Analysis) để sắp xếp Layout Web & tạo Bundle khuyến mãi tự động

Mục tiêu: Dùng dữ liệu mua hàng thực tế để xác định các cặp/số nhóm sản phẩm thường xuất hiện cùng nhau, tự động điều chỉnh vị trí hiển thị trên trang chủ, và sinh ra các bundle khuyến mãi “Buy‑Together” mà không cần can thiệp thủ công.


1. Giới thiệu chung

Theo Statista 2024, 71 % người tiêu dùng Việt Nam mua ít nhất 2 mặt hàng trong một đơn hàng. Cục TMĐT VN báo cáo GMV e‑commerce năm 2024 đạt 200 trillion VND, tăng 23 % so với năm 2023. Khi khách hàng có xu hướng mua “cùng lúc”, việc bố trí sản phẩm trên giao diện (layout) sao cho các mặt hàng liên quan xuất hiện gần nhau sẽ tăng tỷ lệ chuyển đổi (CR) trung bình 12 % (Shopify Commerce Trends 2025).

Market Basket Analysis (MBA) – còn gọi là phân tích rổ hàng – là kỹ thuật khai thác luật kết hợp (association rules) để phát hiện các mẫu mua hàng lặp lại. Áp dụng MBA vào việc thiết kế layout và tạo bundle khuyến mãi giúp:

  • Tối ưu vị trí hiển thị: sản phẩm “đi kèm” được đặt gần nhau, giảm thời gian tìm kiếm.
  • Tự động sinh bundle: giảm chi phí marketing, tăng giá trị đơn hàng trung bình (AOV).
  • Cải thiện trải nghiệm cá nhân hoá: đề xuất “Bạn cũng có thể thích” dựa trên hành vi thực tế.

2. Lý thuyết MBA – Các chỉ số cơ bản

Chỉ số Công thức (tiếng Việt) LaTeX (tiếng Anh)
Support Support(A → B) = Số đơn hàng chứa A và B / Tổng số đơn hàng \huge Support(A\rightarrow B)=\frac{Count(A\cap B)}{Total\_Transactions}
Confidence Confidence(A → B) = Số đơn hàng chứa A và B / Số đơn hàng chứa A \huge Confidence(A\rightarrow B)=\frac{Count(A\cap B)}{Count(A)}
Lift Lift(A → B) = Confidence(A → B) / Support(B) \huge Lift(A\rightarrow B)=\frac{Confidence(A\rightarrow B)}{Support(B)}

⚠️ Lưu ý:
Support ≥ 0.5 % thường được coi là “đủ phổ biến” trong thị trường Việt Nam (theo Gartner 2025).
Lift > 1 cho thấy mối quan hệ tích cực, Lift > 1.5 được ưu tiên cho bundle khuyến mãi.


3. Dữ liệu & nguồn tham khảo

Nguồn Loại dữ liệu Thời gian Định dạng
Statista 2024 – “E‑commerce in Vietnam” Thống kê GMV, số đơn hàng Q4 2024 CSV/Excel
Cục TMĐT VN – “Báo cáo thị trường điện tử 2024” Số lượng người dùng, tần suất mua Q3 2024 PDF
Google Tempo 2024 – “Search Trends for product categories” Từ khóa tìm kiếm, mùa vụ Q1‑Q4 2024 JSON
Shopify Commerce Trends 2025 – “AI‑driven recommendations” Tỷ lệ merchant dùng AI, AOV Q1 2025 CSV
Gartner 2025 – “Revenue impact of recommendation engines” ROI, lift trung bình Q2 2025 PDF

4. Kiến trúc giải pháp – Tech Stack đề xuất

+-------------------+      +-------------------+      +-------------------+
|   Data Ingestion  | ---> |   Data Lake (S3)  | ---> |   Processing (Spark)|
+-------------------+      +-------------------+      +-------------------+
        |                         |                         |
        v                         v                         v
+-------------------+      +-------------------+      +-------------------+
|   Feature Store   | ---> |   Model (Apriori) | ---> |   API (FastAPI)   |
+-------------------+      +-------------------+      +-------------------+
        |                         |                         |
        v                         v                         v
+-------------------+      +-------------------+      +-------------------+
|   Front‑end (React) | <--|   CDN (Cloudflare) | <--|   CMS (Strapi)    |
+-------------------+      +-------------------+      +-------------------+

4.1 So sánh 4 lựa chọn Tech Stack

Thành phần Lựa chọn 1 (AWS) Lựa chọn 2 (GCP) Lựa chọn 3 (Azure) Lựa chọn 4 (On‑prem)
Data Lake Amazon S3 (độ bền 99.999999999 %) Cloud Storage (Coldline) Azure Blob Storage HDFS on‑prem
Processing AWS EMR (Spark) Dataproc (Spark) HDInsight (Spark) Spark on‑k8s
Feature Store AWS SageMaker Feature Store Vertex AI Feature Store Azure ML Feature Store Feast on‑prem
API FastAPI + AWS Lambda Cloud Functions (Python) Azure Functions Docker + Nginx
CI/CD GitHub Actions + CodeBuild Cloud Build Azure DevOps Jenkins
Cost (USD/ tháng) 2 200 2 400 2 300 3 500 (CAPEX + OPEX)
Scalability Auto‑scale serverless Auto‑scale Auto‑scale Manual scaling
Compliance (GDPR, PCI‑DSS) ❌ (cần audit)

⚡ Điểm mạnh: Lựa chọn 1 (AWS) có chi phí thấp nhất, tích hợp sẵn SageMaker Feature Store, phù hợp với quy mô 100‑1000 tỷ VND/tháng.


5. Quy trình vận hành tổng quan (Workflow)

┌─────────────────────┐
│   Thu thập dữ liệu   │
│ (order, clickstream)│
└───────┬─────────────┘
        │
        ▼
┌─────────────────────┐
│   Đưa vào Data Lake  │
│   (S3 bucket)       │
└───────┬─────────────┘
        │
        ▼
┌─────────────────────┐
│   Tiền xử lý (Spark)│
│   - lọc, chuẩn hoá │
└───────┬─────────────┘
        │
        ▼
┌─────────────────────┐
│   Tạo Feature Store │
│   (SageMaker)       │
└───────┬─────────────┘
        │
        ▼
┌─────────────────────┐
│   Huấn luyện Model   │
│   (Apriori)          │
└───────┬─────────────┘
        │
        ▼
┌─────────────────────┐
│   Đẩy API (FastAPI) │
│   - rule endpoint   │
└───────┬─────────────┘
        │
        ▼
┌─────────────────────┐
│   Front‑end (React) │
│   - layout engine   │
└─────────────────────┘

6. Các bước triển khai – 7 Phase

Phase Mục tiêu Công việc con (6‑12) Người chịu trách nhiệm Thời gian (tuần) Dependency
Phase 1 – Khởi tạo hạ tầng Xây dựng môi trường cloud, CI/CD 1. Tạo VPC, Subnet 2. Provision S3 bucket 3. Deploy EKS cluster 4. Cài GitHub Actions 5. Thiết lập IAM roles 6. Kiểm tra network Cloud Engineer 2
Phase 2 – Thu thập & lưu trữ dữ liệu Đưa dữ liệu order & clickstream vào Data Lake 1. Kết nối DB (PostgreSQL) 2. Export daily snapshots 3. Đặt S3 lifecycle 4. Mã hoá dữ liệu (KMS) 5. Kiểm tra checksum 6. Đặt alert CloudWatch Data Engineer 3 Phase 1
Phase 3 – Tiền xử lý & Feature Store Chuẩn hoá, tạo feature cho MBA 1. Spark job “clean_orders” 2. Join clickstream 3. Tạo bảng “basket” (user_id, product_id, ts) 4. Lưu vào Feature Store 5. Kiểm tra data quality 6. Versioning feature Data Engineer 3 Phase 2
Phase 4 – Huấn luyện mô hình MBA Sinh luật kết hợp (association rules) 1. Cài đặt PySpark + mlxtend 2. Chạy Apriori (min_support = 0.005) 3. Tính confidence, lift 4. Lưu rule set vào DynamoDB 5. Đánh giá top‑20 rule 6. Tối ưu hyper‑params Data Scientist 2 Phase 3
Phase 5 – Xây dựng API & Service Cung cấp rule qua REST 1. FastAPI skeleton 2. Endpoint /rules?product_id= 3. Cache Redis 4. Dockerize service 5. Deploy to EKS 6. Test contract (OpenAPI) Backend Engineer 2 Phase 4
Phase 6 – Tích hợp Front‑end Đưa rule vào layout & bundle 1. React component “BundleCarousel” 2. Gọi API async 3. Render “Buy‑Together” 4. A/B test vị trí (above‑the‑fold) 5. Thu thập metric (CR, AOV) 6. Deploy via CI/CD Front‑end Engineer 3 Phase 5
Phase 7 – Go‑live & Monitoring Đảm bảo ổn định, tối ưu 1. Kiểm tra security (OWASP) 2. Load test (k6) 3. Enable CloudWatch alarms 4. Rollback plan 5. Đào tạo ops 6. Bàn giao tài liệu DevOps Lead 2 Phase 6

Tổng thời gian: 17 tuần ≈ 4 tháng.


7. Timeline & Gantt Chart

Gantt Chart (ASCII)

| Phase          | W1 | W2 | W3 | W4 | W5 | W6 | W7 | W8 | W9 | W10| W11| W12| W13| W14| W15| W16| W17|
|----------------|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|
| Phase 1        |####|####|    |    |    |    |    |    |    |    |    |    |    |    |    |    |    |
| Phase 2        |    |####|####|####|    |    |    |    |    |    |    |    |    |    |    |    |    |
| Phase 3        |    |    |    |####|####|####|    |    |    |    |    |    |    |    |    |    |    |
| Phase 4        |    |    |    |    |    |####|####|    |    |    |    |    |    |    |    |    |    |
| Phase 5        |    |    |    |    |    |    |####|####|    |    |    |    |    |    |    |    |    |
| Phase 6        |    |    |    |    |    |    |    |####|####|####|    |    |    |    |    |    |    |
| Phase 7        |    |    |    |    |    |    |    |    |    |####|####|    |    |    |    |    |    |

8. Chi phí chi tiết 30 tháng

Hạng mục Năm 1 (USD) Năm 2 (USD) Năm 3 (USD) Tổng (USD)
Cloud Infra (Compute, Storage, DB) 18 800 19 500 20 200 58 500
Licenses (SageMaker, Snowflake) 4 200 4 500 4 800 13 500
Nhân sự (Dev, Data, Ops) – 3 FTE 120 000 126 000 132 600 378 600
Công cụ CI/CD, Monitoring 1 200 1 300 1 400 3 900
Đào tạo & Consulting 2 500 2 200 2 000 6 700
Tổng 146 700 153 800 160 800 461 300

⚡ Ghi chú: Chi phí tính theo mức trung bình AWS US‑East‑1, 30 % dự phòng cho tăng giá dịch vụ.


9. Rủi ro & Phương án dự phòng

Rủi ro Mức độ Phương án B Phương án C
Dữ liệu không đủ (support < 0.5 %) Cao Giảm ngưỡng support xuống 0.3 % (tạm thời) Thu thập dữ liệu thêm 30 ngày, dùng synthetic data
Latency API > 200 ms Trung bình Cache rule set trong Redis (TTL = 12 h) Đưa API lên CloudFront Edge (Lambda@Edge)
Độ chính xác rule giảm > 10 % Cao Retrain model hàng tuần Sử dụng thuật toán FP‑Growth thay thế Apriori
Vi phạm PCI‑DSS (payment data rò rỉ) Rất cao Tách riêng payment microservice, mã hoá end‑to‑end Đánh giá bảo mật bởi bên thứ ba (KPMG)
Thay đổi luật thuế/giá Thấp Cập nhật rule engine qua config file Tự động reload rule khi có thay đổi DB

10. KPI, công cụ đo & tần suất

KPI Mục tiêu Công cụ đo Tần suất
Conversion Rate (CR) tăng +12 % so với baseline Google Analytics, Mixpanel Hàng ngày
Average Order Value (AOV) tăng +8 % Shopify Reports, Snowflake Hàng tuần
Rule Coverage (tỷ lệ đơn hàng có ít nhất 1 rule) ≥ 45 % Custom dashboard (Grafana) Hàng ngày
API Latency ≤ 150 ms (p95) k6, CloudWatch Metrics Hàng giờ
Cache Hit Rate ≥ 85 % Redis Insights Hàng giờ
Security Incidents 0 OWASP ZAP, Snyk Hàng tháng

11. Tài liệu bàn giao cuối dự án

STT Tài liệu Người viết Nội dung bắt buộc
1 Architecture Diagram Solution Architect Các thành phần, flow, dependency
2 Data Dictionary Data Engineer Định nghĩa bảng, field, kiểu dữ liệu
3 ETL Job Specs Data Engineer Mô tả Spark job, schedule, logs
4 Model Training Report Data Scientist Thuật toán, hyper‑params, metrics
5 API Specification (OpenAPI) Backend Engineer Endpoint, request/response, error codes
6 CI/CD Pipeline Docs DevOps Lead YAML files, triggers, approvals
7 Infrastructure as Code (IaC) Scripts DevOps Lead Terraform modules, variables
8 Security Assessment Report Security Engineer Pen‑test, OWASP checklist
9 Performance Test Results QA Engineer k6 scripts, load curves
10 Rollback & Disaster Recovery Plan DevOps Lead Steps, contact list
11 User Guide – Front‑end Front‑end Engineer Cách cấu hình bundle, A/B test
12 Monitoring Dashboard Ops Engineer Grafana panels, alert thresholds
13 Service Level Agreement (SLA) PM Uptime, response time, support
14 Change Log PM Các phiên bản, ngày triển khai
15 Training Materials PM Slides, video walkthrough

12. Checklist Go‑Live (42 item)

12.1 Security & Compliance

# Mục tiêu Trạng thái
1 Kiểm tra OWASP Top 10
2 Mã hoá dữ liệu nhạy cảm (KMS)
3 Đánh giá PCI‑DSS cho payment microservice
4 SSO & IAM role least‑privilege
5 Pen‑test bên thứ ba
6 Cấu hình CSP header
7 Đánh giá GDPR (nếu có EU customers)
8 Log audit trail (CloudTrail)
9 Backup & restore test (RPO < 4 h)
10 Vulnerability scan (Snyk)

12.2 Performance & Scalability

# Mục tiêu Trạng thái
11 Load test 5 k RPS (k6)
12 Auto‑scaling policies (CPU > 70 %)
13 Cache hit rate ≥ 85 %
14 Latency ≤ 150 ms (p95)
15 CDN cache purge script
16 Stress test peak traffic (2× forecast)
17 Database connection pool tuning
18 Monitoring alerts (CPU, Mem, Latency)
19 Blue‑Green deployment pipeline
20 Disaster recovery drill

12.3 Business & Data Accuracy

# Mục tiêu Trạng thái
21 Rule coverage ≥ 45 %
22 A/B test result significance (p < 0.05)
23 Data quality checks (null, dup)
24 KPI dashboard validation
25 Business stakeholder sign‑off
26 Documentation version control
27 Pricing & discount logic verification
28 Localization (VN, EN)
29 SEO meta tags for bundle pages
30 Email campaign integration test

12.4 Payment & Finance

# Mục tiêu Trạng thái
31 Payment gateway sandbox test
32 Reconciliation script (daily)
33 Fraud detection rule (Stripe Radar)
34 Invoice generation accuracy
35 Refund flow test
36 Currency conversion (VND/USD)
37 Tax calculation (VAT 10 %)
38 Financial reporting export (CSV)
39 PCI‑DSS compliance audit
40 Settlement report validation

12.5 Monitoring & Rollback

# Mục tiêu Trạng thái
41 Grafana dashboard live
42 Rollback script (helm rollback)

13. Mã nguồn mẫu (12 đoạn)

13.1 Docker Compose (Spark + Redis)

version: "3.8"
services:
  spark:
    image: bitnami/spark:3.4
    environment:
      - SPARK_MODE=master
    ports:
      - "8080:8080"
    volumes:
      - ./data:/opt/spark/data
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    command: ["redis-server", "--maxmemory", "256mb", "--maxmemory-policy", "allkeys-lru"]

13.2 Nginx config (Reverse proxy for FastAPI)

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://fastapi:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }

    # Health check endpoint
    location /healthz {
        access_log off;
        return 200 'OK';
    }
}

13.3 Medusa plugin – Custom rule endpoint

// plugins/market-basket/index.js
module.exports = (options) => ({
  routes: [
    {
      method: "GET",
      path: "/rules/:productId",
      handler: async (req, res) => {
        const { productId } = req.params;
        const rules = await getRulesFromDynamo(productId);
        res.json(rules);
      },
    },
  ],
});

13.4 Cloudflare Worker – Edge caching

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url)
  if (url.pathname.startsWith('/rules/')) {
    const cache = caches.default
    let response = await cache.match(request)
    if (!response) {
      response = await fetch(request)
      response = new Response(response.body, response)
      response.headers.set('Cache-Control', 'public, max-age=43200')
      await cache.put(request, response.clone())
    }
    return response
  }
  return fetch(request)
}

13.5 Script đối soát payment (Python)

import csv, datetime, boto3
s3 = boto3.client('s3')
def reconcile():
    obj = s3.get_object(Bucket='payments-bucket', Key='daily/2024-09-01.csv')
    rows = csv.DictReader(obj['Body'].read().decode().splitlines())
    total = sum(float(r['amount']) for r in rows if r['status']=='settled')
    print(f"Daily settled amount: {total:,.2f} VND")
if __name__ == "__main__":
    reconcile()

13.6 GitHub Actions CI/CD (Docker build & deploy)

name: CI/CD Pipeline
on:
  push:
    branches: [ main ]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Build Docker image
        run: |
          docker build -t ghcr.io/${{ github.repository }}:${{ github.sha }} .
      - name: Push to GHCR
        run: |
          echo ${{ secrets.GITHUB_TOKEN }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin
          docker push ghcr.io/${{ github.repository }}:${{ github.sha }}
  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to EKS
        uses: aws-actions/eks-kubectl@v2
        with:
          args: set image deployment/fastapi fastapi=ghcr.io/${{ github.repository }}:${{ github.sha }}

13.7 Apriori algorithm (Python + mlxtend)

import pandas as pd
from mlxtend.frequent_patterns import apriori, association_rules

# Load basket data: columns = ['order_id','product_id']
df = pd.read_csv('basket.csv')
basket = df.groupby('order_id')['product_id'].apply(list)

# One‑hot encoding
encoded = basket.apply(lambda x: pd.Series(1, index=x)).fillna(0)

# Apriori
freq_items = apriori(encoded, min_support=0.005, use_colnames=True)
rules = association_rules(freq_items, metric="confidence", min_threshold=0.2)
rules = rules[(rules['lift'] > 1.5) & (rules['confidence'] > 0.3)]
print(rules[['antecedents','consequents','support','confidence','lift']])

13.8 SQL query – tạo bảng basket

CREATE TABLE basket AS
SELECT
    o.order_id,
    jsonb_array_elements_text(o.items) AS product_id,
    o.created_at
FROM orders o
WHERE o.created_at >= CURRENT_DATE - INTERVAL '90 days';

13.9 React component – BundleCarousel

import React, { useEffect, useState } from 'react';
import axios from 'axios';

interface Rule {
  productId: string;
  confidence: number;
  lift: number;
}

const BundleCarousel: React.FC<{ productId: string }> = ({ productId }) => {
  const [rules, setRules] = useState<Rule[]>([]);
  useEffect(() => {
    axios.get(`/api/rules/${productId}`).then(res => setRules(res.data));
  }, [productId]);

  return (
    <div className="bundle-carousel">
      {rules.map(r => (
        <div key={r.productId} className="bundle-item">
          <img src={`/images/${r.productId}.jpg`} alt={r.productId} />
          {r.productId}
        </div>
      ))}
    </div>
  );
};
export default BundleCarousel;

13.10 Redis caching config (Docker)

redis:
  image: redis:7-alpine
  command: ["redis-server", "--maxmemory", "512mb", "--maxmemory-policy", "allkeys-lru"]
  ports:
    - "6379:6379"
  volumes:
    - redis-data:/data
volumes:
  redis-data:

13.11 ElasticSearch mapping – product similarity

PUT products
{
  "mappings": {
    "properties": {
      "product_id": { "type": "keyword" },
      "description": { "type": "text" },
      "embedding": { "type": "dense_vector", "dims": 128 }
    }
  }
}

13.12 Terraform – VPC & Subnet (AWS)

resource "aws_vpc" "ecom_vpc" {
  cidr_block = "10.0.0.0/16"
  tags = { Name = "ecom-vpc" }
}
resource "aws_subnet" "public_a" {
  vpc_id            = aws_vpc.ecom_vpc.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"
  map_public_ip_on_launch = true
}

14. Các bước triển khai chi tiết (6‑8 Phase) – Đã trình bày ở mục 6


15. Kết luận – Key Takeaways

  1. MBA là nền tảng dữ liệu: Support ≥ 0.5 % và Lift > 1.5 đủ để tạo bundle tự động, giảm chi phí marketing tới ≈ 15 % (theo Gartner 2025).
  2. Kiến trúc serverless + Spark cho phép xử lý 10 triệu giao dịch/tháng với latency < 200 ms.
  3. CI/CD + IaC đảm bảo triển khai nhanh (≤ 2 ngày) và rollback an toàn.
  4. KPI đo lường phải bao gồm cả metric business (CR, AOV) và kỹ thuật (latency, cache hit).
  5. Rủi ro chủ yếu ở dữ liệu và bảo mật; có sẵn 2 phương án dự phòng để duy trì dịch vụ.

🛡️ Best Practice: Đặt rule engine ở tầng API, không trực tiếp trong front‑end, để dễ dàng versioning và kiểm soát bảo mật.


16. Câu hỏi thảo luận

  • Anh em đã gặp trường hợp lift giảm sau khi thay đổi chiến dịch quảng cáo chưa?
  • Khi support quá thấp, bạn ưu tiên giảm ngưỡng hay thu thập thêm dữ liệu?

17. Đoạn chốt marketing

Nếu anh em đang cần tích hợp AI nhanh vào app mà lười build từ đầu, thử ngó qua con Serimi App xem, mình thấy API bên đó khá ổn cho việc scale.

Anh em nào làm Content hay SEO mà muốn tự động hóa quy trình thì tham khảo bộ công cụ noidungso.io.vn nhé, đỡ tốn cơm gạo thuê nhân sự part‑time.


Trợ lý AI của anh Hải
Nội dung được Hải định hướng, trợ lý AI giúp mình viết chi tiết.
Chia sẻ tới bạn bè và gia đình