Làm thế nào để xây dựng hệ thống gợi ý sản phẩm thay thế khi hết hàng sử dụng Knowledge Graph?

Hệ thống gợi ý sản phẩm thay thế (Substitute Recommender) khi hết hàng – Kiến trúc dựa trên Knowledge Graph

Mục tiêu: Khi một SKU hết hàng, hệ thống tự động đưa ra danh sách các sản phẩm thay thế có công năng tương đương ≥ 95 % dựa trên mô hình Knowledge Graph (KG).
Đối tượng: Kiến trúc sư, senior backend, data engineer, product owner, PM.


1. Bối cảnh thị trường & nhu cầu thực tế

Nguồn Dữ liệu 2024‑2025
Statista – Thị phần e‑commerce Đông Nam Á 2024: 23 % (VN), 19 % (TH), 15 % (ID)
Cục TMĐT VN – Tỷ lệ giỏ hàng bị hủy vì hết hàng 2023: 12,4 % (tăng 3 % so với 2022)
Google Tempo – Thời gian trung bình tìm kiếm sản phẩm thay thế 7,2 giây/truy vấn
Shopify Commerce Trends 2025 – 68 % người mua muốn “đề xuất sản phẩm thay thế” khi mặt hàng không có sẵn
Gartner – 2024: “Knowledge Graph là nền tảng quan trọng cho AI‑driven recommendation”

Kết luận: Mất 12 % doanh thu do hết hàng là cơ hội cải thiện bằng cách đưa ra đề xuất thay thế nhanh, chính xác và có tính năng tương đương.


2. Kiến trúc tổng quan

+-------------------+      +-------------------+      +-------------------+
|   Frontend (SPA)  |<---->|   API Gateway     |<---->|   Auth Service    |
+-------------------+      +-------------------+      +-------------------+
                               |   ^   |
                               |   |   |
                               v   |   v
+-------------------+   +-------------------+   +-------------------+
|   Recommendation |   |   Knowledge Graph|   |   Product Service |
|   Engine (Python)|   |   (Neo4j)        |   |   (Microservice) |
+-------------------+   +-------------------+   +-------------------+
                               |
                               v
                       +-------------------+
                       |   Data Lake (S3)  |
                       +-------------------+
  • API Gateway: Kong + JWT.
  • Recommendation Engine: Python FastAPI, sử dụng Neo4j để truy vấn KG, Redis cache 5 phút.
  • Knowledge Graph: Neo4j 5.x, mô hình SKU‑Feature‑Category‑Brand‑Usage.
  • Data Lake: Amazon S3, lưu trữ log click, purchase, inventory.

2.1 Workflow vận hành (text art)

[Inventory Update] --> (Kafka Topic: stock_change)
        |
        v
[Stock Service] --(Event)--> [KG Updater] --(Neo4j Cypher)--> KG
        |
        v
[User Request: SKU X] --> API GW --> Recommendation Engine
        |
        v
[KG Query] --> Neo4j --> List<Substitutes>
        |
        v
[Cache] <-- Redis (TTL 5m)
        |
        v
[Response] --> Frontend (Show 3‑5 alternatives)

3. Lựa chọn công nghệ (Tech Stack Comparison)

Thành phần Lựa chọn A Lựa chọn B Lựa chọn C Lựa chọn D
Graph DB Neo4j 5.x (Enterprise) Amazon Neptune TigerGraph JanusGraph (Cassandra)
Cache Redis 7 (Cluster) Memcached AWS ElastiCache (Redis) Nginx FastCGI Cache
Message Bus Apache Kafka 3.x RabbitMQ AWS SNS/SQS Google Pub/Sub
API Framework FastAPI (Python) Spring Boot (Java) NestJS (Node) Go‑Fiber
Orchestration Docker Compose + Traefik Kubernetes (EKS) Docker Swarm Nomad
CI/CD GitHub Actions GitLab CI Jenkins X Azure Pipelines
Monitoring Prometheus + Grafana Datadog New Relic CloudWatch
Cost (USD/yr) 45 k 62 k 38 k 55 k

Đánh giá: Neo4j + FastAPI + Kafka + Docker Compose đáp ứng nhanh, chi phí vừa phải, dễ triển khai trên môi trường on‑premise hoặc cloud.


4. Chi phí chi tiết 30 tháng (đơn vị USD)

Hạng mục Tháng 1‑12 Tháng 13‑24 Tháng 25‑30 Tổng
Licenses (Neo4j Enterprise) 12 000 12 000 6 000 30 000
Infrastructure (VM, Storage, Network) 8 500 8 500 4 250 21 250
Third‑party services (Redis Cloud, Kafka Managed) 3 200 3 200 1 600 8 000
DevOps & Monitoring (Datadog) 2 400 2 400 1 200 6 000
Personnel (30 % of total cost) 7 200 7 200 3 600 18 000
Dự phòng 10 % 3 300 3 300 1 650 8 250
Tổng 36 600 36 600 18 300 91 500

Công thức tính tổng chi phí:
Tổng = Σ (Chi phí hạng mục × Số tháng) + Dự phòng


5. Timeline triển khai (30 ngày)

Giai đoạn Tuần Công việc chính Người chịu trách nhiệm
Phase 1 – Khởi tạo KG 1‑2 Thu thập dữ liệu SKU, tạo schema Neo4j, import CSV Data Engineer
Phase 2 – Xây dựng API 3‑4 FastAPI skeleton, JWT auth, Swagger Backend Lead
Phase 3 – Recommendation Engine 5‑6 Implement Cypher queries, Redis cache, unit tests ML Engineer
Phase 4 – Integration 7‑8 Kết nối Kafka, event handling, CI/CD pipeline DevOps
Phase 5 – Load Test & Optimisation 9‑10 JMeter, query tuning, autoscaling config QA Lead
Phase 6 – Go‑Live 11‑12 Deploy prod, monitoring dashboards, rollback plan PM

5.1 Gantt chart (ASCII)

| Phase | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 |
|------|---|---|---|---|---|---|---|---|---|---|---|---|
| KG   |===|===|   |   |   |   |   |   |   |   |   |   |
| API  |   |===|===|   |   |   |   |   |   |   |   |   |
| RE   |       |===|===|   |   |   |   |   |   |   |   |
| INT  |           |===|===|===|   |   |   |   |   |   |
| LT   |               |===|===|===|===|   |   |   |   |
| GO   |                       |===|===|===|===|===|===|

6. Các bước triển khai chi tiết (6 Phase)

Phase 1 – Xây dựng Knowledge Graph

Mục tiêu Thu thập, chuẩn hoá, import dữ liệu SKU vào Neo4j
Công việc con 1. Export CSV từ ERP (SKU, attributes, category).
2. Định nghĩa ontology: (:SKU)-[:HAS_FEATURE]->(:Feature), (:SKU)-[:BELONGS_TO]->(:Category), (:SKU)-[:BRANDED_AS]->(:Brand).
3. Viết script Python kg_import.py (sử dụng neo4j driver).
4. Kiểm tra tính toàn vẹn (unique constraints).
5. Tạo index trên :SKU(id).
Người chịu trách nhiệm Data Engineer
Thời gian Tuần 1‑2
Dependency Không có

Code: kg_import.py

from neo4j import GraphDatabase
import csv

uri = "bolt://neo4j:7687"
auth = ("neo4j", "password")
driver = GraphDatabase.driver(uri, auth=auth)

def import_sku(csv_path):
    with driver.session() as session:
        with open(csv_path, newline='', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            for row in reader:
                session.run(
                    """
                    MERGE (s:SKU {id: $sku_id})
                    SET s.name = $name, s.price = toFloat($price)
                    MERGE (c:Category {name: $category})
                    MERGE (s)-[:BELONGS_TO]->(c)
                    WITH s
                    UNWIND $features AS f
                    MERGE (feat:Feature {name: f})
                    MERGE (s)-[:HAS_FEATURE]->(feat)
                    """,
                    sku_id=row["sku_id"],
                    name=row["name"],
                    price=row["price"],
                    category=row["category"],
                    features=row["features"].split("|")
                )
    print("Import completed")

import_sku("data/sku_master.csv")

Phase 2 – Xây dựng API Gateway & Auth

Mục tiêu Cung cấp endpoint /recommendations/{sku_id} bảo mật JWT
Công việc con 1. Cài đặt Kong (Docker Compose).
2. Cấu hình plugin JWT.
3. Định nghĩa Service & Route cho Recommendation Engine.
4. Viết unit test Postman.
Người chịu trách nhiệm Backend Lead
Thời gian Tuần 3‑4
Dependency Phase 1 (KG đã sẵn sàng)

Docker Compose (Kong + PostgreSQL)

version: "3.8"
services:
  kong-db:
    image: postgres:13
    environment:
      POSTGRES_USER: kong
      POSTGRES_PASSWORD: kong
      POSTGRES_DB: kong
    volumes:
      - pgdata:/var/lib/postgresql/data

  kong:
    image: kong:3.3
    environment:
      KONG_DATABASE: postgres
      KONG_PG_HOST: kong-db
      KONG_PG_PASSWORD: kong
      KONG_ADMIN_LISTEN: 0.0.0.0:8001
    ports:
      - "8000:8000"
      - "8443:8443"
      - "8001:8001"
    depends_on:
      - kong-db

volumes:
  pgdata:

Kong JWT Plugin (curl)

curl -i -X POST http://localhost:8001/services \
  --data "name=recommendation" \
  --data "url=http://recommendation:8000"

curl -i -X POST http://localhost:8001/services/recommendation/routes \
  --data "paths[]=/recommendations"

curl -i -X POST http://localhost:8001/services/recommendation/plugins \
  --data "name=jwt"

Phase 3 – Recommendation Engine

Mục tiêu Trả về danh sách SKU thay thế có công năng ≥ 95 %
Công việc con 1. Viết Cypher query tính similarity dựa trên HAS_FEATURE.
2. Cache kết quả trong Redis (TTL 5 phút).
3. Định dạng JSON response.
4. Kiểm thử với pytest.
Người chịu trách nhiệm ML Engineer
Thời gian Tuần 5‑6
Dependency Phase 2 (API đã sẵn)

Cypher query (Similarity ≥ 95 %)

MATCH (s:SKU {id: $sku_id})-[:HAS_FEATURE]->(f:Feature)
WITH s, collect(f) AS srcFeatures
MATCH (t:SKU)-[:HAS_FEATURE]->(f2:Feature)
WHERE t.id <> s.id
WITH s, t, srcFeatures, collect(f2) AS tgtFeatures,
     size(apoc.coll.intersection(srcFeatures, tgtFeatures)) AS common,
     size(apoc.coll.union(srcFeatures, tgtFeatures)) AS total
WHERE toFloat(common) / total >= 0.95
RETURN t.id AS substitute_id, t.name AS name, t.price AS price
ORDER BY common DESC LIMIT 5

Giải thích: apoc.coll.intersection lấy số tính năng chung, apoc.coll.union lấy tổng tính năng, tỷ lệ ≥ 0.95 đáp ứng yêu cầu công năng tương đương.

FastAPI endpoint (Python)

from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import redis
from neo4j import GraphDatabase

app = FastAPI()
security = HTTPBearer()
redis_client = redis.Redis(host="redis", port=6379, db=0)
neo4j_driver = GraphDatabase.driver("bolt://neo4j:7687", auth=("neo4j", "password"))

def verify_jwt(token: HTTPAuthorizationCredentials = Depends(security)):
    # TODO: validate JWT signature, expiry
    return token.credentials

@app.get("/recommendations/{sku_id}")
def get_substitutes(sku_id: str, token: str = Depends(verify_jwt)):
    cache_key = f"substitutes:{sku_id}"
    cached = redis_client.get(cache_key)
    if cached:
        return {"sku_id": sku_id, "substitutes": eval(cached)}
    with neo4j_driver.session() as session:
        result = session.run(
            """<Cypher query from above>""",
            sku_id=sku_id
        )
        substitutes = [record.data() for record in result]
    redis_client.setex(cache_key, 300, str(substitutes))
    return {"sku_id": sku_id, "substitutes": substitutes}

Phase 4 – Integration & CI/CD

Mục tiêu Đảm bảo pipeline tự động build, test, deploy
Công việc con 1. Dockerfile cho Recommendation Engine.
2. GitHub Actions workflow (build → test → push image).
3. Helm chart (nếu dùng K8s) hoặc Docker‑Compose override cho prod.
4. Thiết lập Kafka topic stock_change.
Người chịu trách nhiệm DevOps
Thời gian Tuần 7‑8
Dependency Phase 3 (engine đã hoàn thiện)

GitHub Actions CI/CD (yaml)

name: CI/CD Recommendation Engine
on:
  push:
    branches: [ main ]
jobs:
  build-test-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.11"
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        run: pytest -q
      - name: Build Docker image
        run: |
          docker build -t ghcr.io/yourorg/recommendation:${{ github.sha }} .
          echo ${{ secrets.GITHUB_TOKEN }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin
          docker push ghcr.io/yourorg/recommendation:${{ github.sha }}
      - name: Deploy to prod (Docker Compose)
        if: github.ref == 'refs/heads/main'
        run: |
          ssh prod-user@prod-server '
            cd /opt/recommendation
            docker compose pull
            docker compose up -d
          '

Phase 5 – Load Test & Optimisation

Mục tiêu Đảm bảo hệ thống chịu tải 10 k QPS, latency < 200 ms
Công việc con 1. JMeter script mô phỏng 10 k QPS.
2. Profiling Neo4j query (EXPLAIN).
3. Tuning Redis maxmemory‑policy.
4. Auto‑scale rule (CPU > 70 % → add replica).
Người chịu trách nhiệm QA Lead
Thời gian Tuần 9‑10
Dependency Phase 4 (pipeline đã chạy)

JMeter HTTP Request (XML snippet)

<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="GET Substitutes" enabled="true">
  <stringProp name="HTTPSampler.domain">api.yourshop.vn</stringProp>
  <stringProp name="HTTPSampler.port">443</stringProp>
  <stringProp name="HTTPSampler.protocol">https</stringProp>
  <stringProp name="HTTPSampler.path">/recommendations/SKU12345</stringProp>
  <stringProp name="HTTPSampler.method">GET</stringProp>
  <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
  <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
  <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
  <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
  <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
  <stringProp name="HTTPSampler.connect_timeout"></stringProp>
  <stringProp name="HTTPSampler.response_timeout"></stringProp>
</HTTPSamplerProxy>

Phase 6 – Go‑Live & Monitoring

Mục tiêu Đưa hệ thống vào production, thiết lập monitoring, rollback
Công việc con 1. Deploy prod stack (Docker‑Compose + Traefik).
2. Grafana dashboards (QPS, latency, cache hit‑rate).
3. Alert rule: avg_over_time(response_time[5m]) > 200ms → Slack.
4. Rollback script (docker compose down + previous image).
Người chịu trách nhiệm PM & DevOps
Thời gian Tuần 11‑12
Dependency Hoàn thành Phase 5

Grafana Dashboard JSON (excerpt)

{
  "title": "Recommendation Engine",
  "panels": [
    {
      "type": "graph",
      "title": "QPS",
      "targets": [
        {
          "expr": "sum(rate(http_requests_total{service=\"recommendation\"}[1m]))",
          "legendFormat": "QPS"
        }
      ]
    },
    {
      "type": "graph",
      "title": "Latency (ms)",
      "targets": [
        {
          "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{service=\"recommendation\"}[5m])) by (le)) * 1000",
          "legendFormat": "95th percentile"
        }
      ]
    }
  ]
}

7. Danh sách 15 tài liệu bàn giao bắt buộc

STT Tài liệu Người viết Nội dung chính
1 Kiến trúc tổng quan (Architecture Overview) Solution Architect Diagram, component description, tech stack
2 Knowledge Graph Schema (Ontology) Data Engineer Entity‑Relationship, constraints, index
3 Data Ingestion Pipeline (ETL) Data Engineer CSV → Neo4j, schedule, error handling
4 API Specification (OpenAPI 3.0) Backend Lead Endpoint, request/response, auth
5 JWT Authentication Guide Security Engineer Token format, rotation, revocation
6 Recommendation Algorithm Document ML Engineer Similarity formula, thresholds
7 Cypher Query Library ML Engineer All queries, performance notes
8 Redis Cache Strategy DevOps Key naming, TTL, eviction policy
9 CI/CD Pipeline (GitHub Actions) DevOps Workflow yaml, secrets, rollback
10 Docker Compose / Helm Chart DevOps Service definitions, env vars
11 Monitoring & Alerting Playbook SRE Grafana dashboards, Prometheus alerts
12 Load Test Report (JMeter) QA Lead Scenarios, results, bottlenecks
13 Security & Compliance Checklist Security Engineer OWASP, GDPR, PCI‑DSS
14 Disaster Recovery & Rollback Procedure PM Steps, RTO, RPO
15 Operation Runbook (Day‑to‑Day) Ops Lead Incident handling, escalation matrix

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

Rủi ro Ảnh hưởng Phương án B Phương án C
KG dữ liệu không đồng bộ Gợi ý sai, mất doanh thu Sử dụng CDC (Debezium) để đồng bộ real‑time Batch sync mỗi 4 giờ + alert
Latency > 200 ms Trải nghiệm người dùng giảm Scale Neo4j read replicas (2 → 4) Chuyển sang Amazon Neptune (managed)
Cache miss > 30 % Tăng tải DB Tăng TTL lên 10 phút, pre‑warm cache cho SKU hot Dùng Redis Cluster sharding
Lỗi JWT Người dùng không truy cập Implement token refresh endpoint Fallback to API key (temporary)
Outage Kafka Không cập nhật stock Switch sang RabbitMQ (mirrored) Sử dụng DB trigger + polling

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

KPI Mục tiêu Công cụ đo Tần suất
Hit‑rate cache ≥ 85 % Redis INFO keyspace_hits/keyspace_misses 5 phút
Similarity accuracy ≥ 95 % (đúng công năng) A/B test (control vs. substitute) Hàng tuần
Latency (p95) ≤ 200 ms Grafana (Prometheus http_request_duration_seconds) 1 phút
Conversion rate of substitutes ≥ 12 % Google Analytics (event substitute_click) Hàng ngày
System uptime 99,9 % UptimeRobot / CloudWatch 5 phút
Cost per recommendation ≤ 0,001 USD Cost Explorer (AWS) + custom script Hàng tháng

10. Checklist Go‑Live (42 item)

10.1 Security & Compliance (9 item)

# Kiểm tra Trạng thái
S‑01 TLS 1.3 trên tất cả endpoint
S‑02 JWT ký bằng RSA‑2048, key rotation mỗi 30 ngày
S‑03 OWASP Top 10 kiểm tra (SQLi, XSS)
S‑04 PCI‑DSS scope: không lưu trữ PAN
S‑05 GDPR: anonim hoá IP trong logs
S‑06 Rate‑limit 100 req/s/user
S‑07 Audit log cho mọi thay đổi KG
S‑08 Vulnerability scan (Trivy) trên image
S‑09 Backup Neo4j daily, test restore

10.2 Performance & Scalability (9 item)

# Kiểm tra Trạng thái
P‑01 Load test 10 k QPS, p95 ≤ 200 ms
P‑02 Auto‑scale rule (CPU > 70 % → +1 replica)
P‑03 Redis maxmemory‑policy allkeys-lru
P‑04 Neo4j query plan EXPLAIN không full‑scan
P‑05 CDN (Cloudflare) cache static assets
P‑06 Connection pool size (Neo4j driver) ≥ 50
P‑07 Health check endpoint /healthz trả 200
P‑08 Circuit breaker (Hystrix) cho KG calls
P‑09 Latency alert rule đã bật

10.3 Business & Data Accuracy (8 item)

# Kiểm tra Trạng thái
B‑01 SKU‑Feature mapping completeness ≥ 99 %
B‑02 Similarity threshold 0.95 đã được xác nhận
B‑03 A/B test conversion ≥ 12 %
B‑04 Log click‑through cho substitutes
B‑05 Data pipeline error rate < 0.1 %
B‑06 Inventory sync latency < 5 s
B‑07 Business rule “exclude discontinued SKUs” hoạt động
B‑08 Documentation cập nhật version

10.4 Payment & Finance (8 item)

# Kiểm tra Trạng thái
F‑01 Không có giao dịch liên quan tới substitutes
F‑02 Refund rule khi substitute không mua được
F‑03 Audit log cho mọi thay đổi giá
F‑04 PCI‑DSS tokenization cho payment gateway
F‑05 Reconciliation script chạy nightly
F‑06 KPI “Revenue from substitutes” tính đúng
F‑07 Alert khi conversion < 10 %
F‑08 Backup DB trước mỗi release

10.5 Monitoring & Rollback (8 item)

# Kiểm tra Trạng thái
M‑01 Grafana dashboards live
M‑02 Alert channel Slack hoạt động
M‑03 Log aggregation (ELK) thu thập toàn bộ
M‑04 Rollback script kiểm tra image version
M‑05 Canary deployment 5 % traffic
M‑06 Health check trả 200 trong 5 phút liên tục
M‑07 Incident response runbook đã phân phối
M‑08 Post‑mortem template sẵn sàng

11. Các công thức tính toán

ROI = (Tổng lợi ích – Chi phí đầu tư) / Chi phí đầu tư × 100 %

\huge ROI=\frac{Total\_Benefits - Investment\_Cost}{Investment\_Cost}\times 100

Giải thích: Total_Benefits bao gồm tăng doanh thu từ gợi ý thay thế và giảm chi phí lost‑sale; Investment_Cost là tổng chi phí triển khai (bảng chi phí 30 tháng).

Hit‑rate cache = (Cache hits) / (Cache hits + Cache misses) × 100 %

\huge HitRate=\frac{Cache\_hits}{Cache\_hits+Cache\_misses}\times 100

12. Kết luận – Key Takeaways

# Điểm cốt lõi
1 Knowledge Graph cho phép mô hình quan hệ SKU‑Feature chi tiết, hỗ trợ tính toán similarity ≥ 95 % một cách giải thích được.
2 Kiến trúc microservice + API Gateway + JWT bảo mật giúp mở rộng độc lập giữa recommendation và các service khác.
3 Cache Redis giảm tải DB tới > 85 % hit‑rate, đáp ứng latency < 200 ms cho 10 k QPS.
4 CI/CD tự động, load test, và monitoring toàn diện giảm RTO xuống < 5 phút.
5 Chi phí 30 tháng ≈ USD 91 500, ROI dự kiến > 250 % trong 2 năm nhờ giảm lost‑sale 12 % và tăng conversion substitutes 12 %.

Câu hỏi thảo luận: Anh em đã gặp trường hợp KG không đồng bộ dẫn đến gợi ý sai chưa? Đã giải quyết như thế nào để giảm thời gian phục hồi?


13. Kêu gọi hành động

Nếu anh em đang muốn tích hợp AI nhanh vào hệ thống mà không muốn xây dựng từ đầu, thử xem Serimi App – API cung cấp mô hình recommendation dựa trên KG đã được train sẵn, giúp scale nhanh chóng.

Nếu công việc của anh em liên quan tới Content hoặc SEO và muốn tự động hoá quy trình, tham khảo bộ công cụ noidungso.io.vn – giảm 30 % thời gian biên tập.


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