用F#记录回滚版本与快照
解读
国内金融、SaaS、量化团队面试时,常把“版本回滚”与“快照”作为“不可变架构”落地能力的试金石。
题目看似只要“存一份旧数据”,实则考察:
- 能否用 F# 的不可变语义天然避免副作用;
- 能否在异步并发场景下保证快照读写一致性;
- 能否兼顾内存效率与 GC 压力;
- 能否与 C# 遗留系统互操作(如 EF Core、Kafka)而不破功。
因此,回答必须给出“可编译、可单元测试、可水平扩展”的完整骨架,而不是玩具级List.rev。
知识点
- 不可变持久化数据结构:Map、Vector、HashMap(FSharp.Data.Adaptive 或 FSharpPlus)
- 结构体记录与
IsByRefLike快照句柄,降低 Gen0 分配 - 异步工作流
async{ }与MailboxProcessor的并发模型 - 自定义
ComputationExpression实现“事务型”版本控制语义 unit of measure防止回滚索引越界CLIMutable与MessagePack零拷贝序列化,供下游 C# 微服务消费- 资源泄漏防护:
use+IAsyncDisposable - 单元测试:FsCheck 做不变式检验,Expecto 做性能基准
答案
// 核心域模型,全部不可变
[<Struct; CustomEquality; NoComparison>]
type VersionId = VersionId of int64<version>
and [<Measure>] version
type Snapshot<'state> = {
Id: VersionId
Timestamp: System.DateTimeOffset
Data: 'state
} with
member this.IsEmpty = obj.ReferenceEquals(this.Data, null)
// 持久化存储抽象,方便面试时切换 Postgres|Mongo|内存
type ISnapshotStore<'state> =
abstract GetMaxVersion: unit -> Async<VersionId option>
abstract Save: Snapshot<'state> -> Async<unit>
abstract Load: VersionId -> Async<'state option>
// 内存实现,供单元测试
module MemoryStore =
open System.Collections.Concurrent
let private store = ConcurrentDictionary<VersionId, 'state>()
let create() =
{ new ISnapshotStore<'state> with
member _.GetMaxVersion() =
async {
match store.Keys |> Seq.tryMax with
| Some v -> return Some v
| None -> return None
}
member _.Save snap =
async {
store.[snap.Id] <- snap.Data
}
member _.Load (VersionId v) =
async {
match store.TryGetValue(VersionId v) with
| true, data -> return Some data
| false, _ -> return None
}
}
// 业务聚合根,封装版本号自增与并发写
type VersionedAggregate<'state, 'command, 'event>
(init: 'state,
evolve: 'state -> 'event -> 'state,
handle: 'state -> 'command -> 'event list,
store: ISnapshotStore<'state>) =
let agent = MailboxProcessor.Start(fun inbox ->
let rec loop (state: 'state) (VersionId ver) = async {
let! msg = inbox.Receive()
match msg with
| :? 'command as cmd ->
let events = handle state cmd
let newState = events |> List.fold evolve state
let newVer = VersionId (ver + 1L<version>)
let snap = { Id = newVer
Timestamp = System.DateTimeOffset.UtcNow
Data = newState }
do! store.Save snap
return! loop newState newVer
| :? VersionId as rollbackVer ->
let! loaded = store.Load rollbackVer
match loaded with
| Some s -> return! loop s rollbackVer
| None -> return! loop state ver // 忽略非法回滚
| _ -> return! loop state ver
}
async {
let! max = store.GetMaxVersion()
let ver = defaultArg max (VersionId 0L<version>)
let! initial =
match max with
| Some v -> store.Load v |> Async.map (Option.defaultValue init)
| None -> async { return init }
return! loop initial ver
}
)
member _.Exec(cmd: 'command) = agent.Post cmd
member _.Rollback(ver: VersionId) = agent.Post(box ver)
member _.Current = async {
let! reply = agent.PostAndAsyncReply(fun reply -> box reply)
return reply :?> 'state
}
// 面试现场可跑的 Demo
module Demo =
type TradeState = { Count: int; Total: decimal }
type Cmd = Buy of decimal | Sell of decimal
type Ev = Bought of decimal | Sold of decimal
let init = { Count = 0; Total = 0m }
let evolve s = function
| Bought p -> { s with Count = s.Count + 1; Total = s.Total + p }
| Sold p -> { s with Count = s.Count - 1; Total = s.Total - p }
let handle s = function
| Buy p -> [Bought p]
| Sell p -> if s.Count <= 0 then [] else [Sold p]
let run() =
let store = MemoryStore.create()
let agg = VersionedAggregate(init, evolve, handle, store)
async {
agg.Exec(Buy 10m)
agg.Exec(Buy 20m)
let! v2 = agg.Current
printfn "v2: %A" v2
agg.Exec(Sell 15m)
let! v3 = agg.Current
printfn "v3: %A" v3
// 回滚到 v2
agg.Rollback(VersionId 2L<version>)
let! afterRollback = agg.Current
printfn "after rollback: %A" afterRollback
} |> Async.RunSynchronously
拓展思考
- 生产级回滚需考虑“快照 + 事件”双轨:快照用于快速恢复,事件流用于审计与重放;可用
Propulsion.FSharp对接 Kafka。 - 高频交易场景下,内存快照每 200 ms 一次,持久化线程使用
System.IO.Pipelines写入磁盘,避免阻塞交易线程。 - 多租户隔离时,把
VersionId改成Guid + 租户前缀,并用ConcurrentDictionary<Guid, WeakReference<'state>>做 LRU 缓存,防止百万租户打爆内存。 - 与 C# 互操作时,把
ISnapshotStore暴露为Task风格,利用Async.AwaitTask/TaskBuilder双向无缝,面试可主动提及“零样板”互操作是 F# 的卖点。 - 单元测试用 FsCheck 生成随机命令序列,断言“回滚后余额永不小于零”,既展示性质驱动测试,又体现金融系统对正确性的极端要求。