九章算法-系统设计#5 优惠券系统设计

Design a Coupon Management System for XYZ e-commerce website where 10k newcoupons are released into the system by employees of company every day and1Musersare trying to get hold of coupon, so that they can buy something on the website. Thesearethe constraints:

  • One user can get only one coupon per day
  • One coupon can only be allocated to a single user at any given time
  • Once a user gets a coupon he/she has to buy something on the website within5mins.

Scenario 场景

GetRequirement:

  • Functional Requirements: 创建coupon, 更新coupon
  • Non-functional Requirements: Availbaility, latency
  • Extended Requirements:
    • 使用次数
    • 时间
    • 减价
    • 先决条件

核心流程

  • 发卷: 同步 or 异步;减价方式: 绝对值、百分比
  • 领卷: 所有用户 or 指定用户
  • 用卷: 商品,商户,类目

Storage 存储

Coupon_batch table

  • Integer batch_id = 1;
  • String bacth_name = 2;
  • String coupon_name = 3;
  • Integer rule_id = 4;
  • Integer total_count = 5;
  • Integer assign_count = 6;
  • Integer used_count = 7;

Rule table

  • Integer rule_id = 1;
  • String name = 2;
  • Integer/Enum type = 3;
  • Message/Blob rule_content = 4;

Coupon table

  • Integer coupon_id = 1;
  • Integer user_id = 2;
  • Integer batch_id = 3;
  • Integer/Enum status = 4;

优惠券table可能被多个不同的系统Access,我们如何保持一致性?

使用分布式事务

  1. Transaction Coordinator
  2. (TCC) Try-Confirm-Cancel

TCC核心:用一个新的table来track操作记录。TCC是目前分布式业务主流解决方案

Coupon_opt_record table

  • Integer user_id = 1;
  • Integer coupan_id = 2;
  • Integer operating = 3;
  • Timestamp operated_at = 4;

TCC 阶段

  1. TCC 实现阶段一 Try: 对资源进行冻结,预留业务资源
  2. TCC 实现阶段二 Confirm: 确认执行业务,开始提交业务
  3. TCC 实现阶段三 Cancel: 取消Try阶段预留的业务资源

Scale 拓展