使用 Rails 7 与 dry-transaction 实现 Saga 编排

解读

在国内 Rails 7 项目面试中,“Saga 编排”常被用来考察候选人对分布式事务一致性、补偿机制以及领域服务层设计的综合能力。
面试官真正想听的是:

  1. 你能否把长事务拆成可补偿的本地事务序列;
  2. 你能否用 dry-transaction 的 Step 管道 + 回滚钩子 把“正向流程”与“补偿流程”显式建模;
  3. 你能否在 Rails 7 zeitwerk 自动加载、无 Spring 重启、Fiber-safe 环境下,保证 Saga 编排器无全局状态、可单测、可并发;
  4. 你能否把业务语义(订单、库存、优惠券)与技术语义(事务、重试、幂等)彻底分离,让代码通过**“铁路轨道”式**的 Success / Failure 自解释。

知识点

  • Saga 模式:把分布式大事务拆成若干本地事务,每个本地事务发布事件或调用下一步,失败时触发补偿事务;
  • 编排式(Orchestration):中央编排器集中决策下一步与补偿路径,比协同式更易调试;
  • dry-transaction 1.x 的 step、map、try、tee 宏,以及 around 钩子;
  • dry-monads 的 Result::Success | Result::Failure 与 Ruby 3 的模式解构赋值;
  • Rails 7 的 Transactionable 模块、retry_on / discard_on、可加载型 Job;
  • 幂等键设计:使用 request_id + biz_type 唯一索引,防止补偿重复扣款;
  • 异步补偿:把补偿操作封装为 CompensationJob,利用 Sidekiq + Redis 流控做重试;
  • 可观测性:在每一步 around 钩子中注入 Rails.logger.tagged(saga_id:)`,方便阿里云 SLS 收集链路。

答案

  1. 领域建模
# app/sagas/create_order_saga.rb
class CreateOrderSaga
  include Dry::Transaction(container: Container)

  step :create_order,      with: "operations.create_order"
  step :reserve_inventory, with: "operations.reserve_inventory"
  step :apply_coupon,      with: "operations.apply_coupon"
  step :charge_payment,    with: "operations.charge_payment"

  around :log_saga
  around :capture_compensation

  private

  def log_saga(input, &block)
    Rails.logger.tagged(saga_id: input[:saga_id]) { block.call }
  end

  def capture_compensation(input, &block)
    block.call
  rescue StandardError => e
    CompensationJob.perform_async(input[:saga_id], e.step_name, input)
    Failure("补偿已触发: #{e.message}")
  end
end
  1. 操作容器注册
# app/sagas/container.rb
module Container
  extend Dry::Container::Mixin

  register "operations.create_order",      ->(input) { CreateOrder.new.call(input) }
  register "operations.reserve_inventory", ->(input) { ReserveInventory.new.call(input) }
  register "operations.apply_coupon",      ->(input) { ApplyCoupon.new.call(input) }
  register "operations.charge_payment",    ->(input) { ChargePayment.new.call(input) }
end
  1. 每个本地事务返回 Success(payload) 或 Failure(:error_code),并在内部自带本地 DB 事务;
  2. 补偿任务
class CompensationJob < ApplicationJob
  queue_as :saga_compensate
  sidekiq_options retry: 5, dead: false

  def perform(saga_id, failed_step, input)
    case failed_step
    when "charge_payment" then RefundPayment.new.call(input)
    when "apply_coupon"   then ReleaseCoupon.new.call(input)
    when "reserve_inventory" then ReleaseInventory.new.call(input)
    when "create_order"   then CancelOrder.new.call(input)
    end
  end
end
  1. 控制器入口
class OrdersController < ApplicationController
  def create
    saga = CreateOrderSaga.new
    case saga.call(order_params.merge(saga_id: SecureRandom.uuid))
    in Success(order)
      render json: { ok: true, order: order }, status: :created
    in Failure(msg)
      render json: { error: msg }, status: :unprocessable_entity
    end
  end
end
  1. 单测(RSpec)
it "补偿已触发" do
  allow(ReserveInventory).to receive(:new).and_raise("库存不足")
  expect(CompensationJob).to receive(:perform_async)
  result = CreateOrderSaga.new.call(params)
  expect(result).to be_failure
end

拓展思考

  1. 与 Seata 的 AT 模式对比:dry-transaction 方案无全局锁、无回滚日志表,适合对一致性要求最终一致、可接受短暂不一致的电商场景;
  2. 把 Saga 状态机持久化:引入 saga_executions 表,记录每一步的 step_name、status、compensated_at,方便审计与对账;
  3. 并发优化:对只读步骤使用 step :read_only, parallel: true,通过 Fiber.schedule 并行调用,Rails 7 + Ruby 3 的 Fiber Scheduler 可大幅降低等待时间;
  4. 与事件溯源结合:每一步产生的领域事件写入 Kafka,下游系统通过消费事件完成自身 Saga,实现跨部门协同;
  5. 灰度补偿:在补偿任务中增加 percentage_rollout 参数,先补偿 1% 订单验证逻辑正确性,再全量放开,降低资损风险;
  6. 面试追问准备:
    • 如果补偿也失败怎么办?——“补偿重试表 + 人工介入队列”;
    • 如何保证幂等?——“补偿操作本身带幂等键,利用数据库唯一索引”;
    • 与 TCC 的区别?——“Saga 没有 Try 阶段,直接提交本地事务,补偿逻辑更重”。