用F#实现可靠消息队列

解读

国内互联网/金融公司面试时,这道题考察的不是“写一个能跑起来的队列”,而是“用函数式思维把『可靠』这件事讲清楚”。
“可靠”在中文技术语境里通常包含四点:

  1. 消息不丢(持久化、刷盘、副本)。
  2. 消息不重(幂等生产、幂等消费)。
  3. 消息不乱(顺序、事务、Exactly-Once)。
  4. 故障可恢复(崩溃重启后状态一致)。

F# 运行在 .NET,天然能调 System.IO、SQLite、RocksDB、PostgreSQL、EventStore、Azure Service Bus、Kafka 等,因此面试官想看:

  • 你能否用 F# 的不可变数据、异步工作流、MailboxProcessor、Result 型、事务计算把“可靠”建模出来;
  • 你是否知道把副作用推到边界,核心逻辑纯函数化;
  • 你是否给出可测试、可演进的架构,而不是一把梭“lock + ConcurrentQueue”。

知识点

  1. 不可变消息类型与 DUs(Discriminated Unions)
  2. MailboxProcessor(Actor)的串行邮箱保证单线程语义,天然顺序、无锁。
  3. async { … } 异步工作流 + CancellationToken 实现优雅关闭。
  4. Result<’ok,’error> 型替代异常,把“写失败”“刷盘失败”显式化。
  5. 事务日志:WAL(Write-Ahead Log)或本地 SQLite 事务,先记日志再改内存状态。
  6. 幂等:消息自带 MessageId(Guid/ULID),消费端用幂等表或幂等键。
  7. 快照 + 重放:内存状态定期快照,重启时重放日志,借鉴 Event Sourcing。
  8. 背压:MailboxProcessor 的 PostAndAsyncReply 结合 AsyncSemaphore,防止内存爆炸。
  9. 单元测试:用 FsCheck 做属性测试,模拟崩溃、乱序、重复。
  10. .NET 生态:可插拔持久层(SQLite 单文件、RocksDB、PostgreSQL、Kafka),用 Reader 抽象隔离。

答案

下面给出一个“可嵌入式、单节点、持久化、幂等、顺序”消息队列的最小核心,约 120 行。
把持久化、网络、分区都抽象成接口,方便后续替换成 Kafka、PostgreSQL 或云存储。

// 核心领域模型,纯函数部分
module Domain =
    type MessageId = MessageId of System.Guid
    type Topic = Topic of string
    type Payload = Payload of byte array

    type Message =
        { Id: MessageId
          Topic: Topic
          Body: Payload
          Timestamp: System.DateTimeOffset }

    type ConsumerGroup = ConsumerGroup of string
    type Offset = Offset of int64

    // 幂等键:MessageId + Topic 即可唯一
    let messageKey msg = msg.Id, msg.Topic

// 持久化抽象,副作用推到边界
module Persistence =
    open Domain

    type ILogStore =
        abstract Append: Message -> Async<Result<Offset, exn>>
        abstract ReadFrom: Topic * Offset -> Async<Message list>
        abstract Flush: unit -> Async<Result<unit, exn>>

    type IOffsetStore =
        abstract Commit: ConsumerGroup * Topic * Offset -> Async<Result<unit, exn>>
        abstract LastCommitted: ConsumerGroup * Topic -> Async<Offset option>

// 内存状态 + 邮箱代理
module Agent =
    open Domain
    open Persistence
    open System.Collections.Immutable

    type private State =
        { Topics: Map<Topic, ImmutableQueue<Message>>
          Offsets: Map<Topic * ConsumerGroup, Offset> }

    type Command =
        | Produce of Message * AsyncReplyChannel<Result<Offset, exn>>
        | Consume of Topic * ConsumerGroup * AsyncReplyChannel<Result<Message option, exn>>
        | Commit of Topic * ConsumerGroup * Offset * AsyncReplyChannel<Result<unit, exn>>
        | Snapshot of AsyncReplyChannel<unit>

    let makeAgent (log: ILogStore) (offset: IOffsetStore) (cancel: System.Threading.CancellationToken) =
        MailboxProcessor<Command>.Start((fun inbox ->
            let rec loop (state: State) =
                async {
                    let! msg = inbox.Receive()
                    match msg with
                    | Produce (m, reply) ->
                        match! log.Append m with
                        | Error e -> reply.Reply (Error e); return! loop state
                        | Ok off ->
                            let q = state.Topics.TryFind m.Topic |> Option.defaultValue ImmutableQueue.Empty
                            let q' = q.Enqueue m
                            let state' = { state with Topics = state.Topics.Add(m.Topic, q') }
                            reply.Reply (Ok off)
                            return! loop state'
                    | Consume (topic, cg, reply) ->
                        let last = state.Offsets.TryFind (topic, cg) |> Option.defaultValue (Offset 0L)
                        let! batch = log.ReadFrom (topic, last)
                        match batch with
                        | [] -> reply.Reply (Ok None); return! loop state
                        | head :: _ ->
                            reply.Reply (Ok (Some head))
                            return! loop state
                    | Commit (topic, cg, off, reply) ->
                        match! offset.Commit (cg, topic, off) with
                        | Error e -> reply.Reply (Error e); return! loop state
                        | Ok () ->
                            let state' = { state with Offsets = state.Offsets.Add ((topic, cg), off) }
                            reply.Reply (Ok ())
                            return! loop state'
                    | Snapshot reply ->
                        do! log.Flush ()
                        reply.Reply ()
                        return! loop state
                }
            loop { Topics = Map.empty; Offsets = Map.empty }), cancel)

// 公开 API,方便替换成 gRPC、WebAPI、背景服务
module ReliableQueue =
    open Domain
    open Agent

    type Queue(agent: MailboxProcessor<Command>) =
        member _.ProduceAsync(msg: Message) =
            agent.PostAndAsyncReply(fun ch -> Produce (msg, ch))
        member _.ConsumeAsync(topic, cg) =
            agent.PostAndAsyncReply(fun ch -> Consume (topic, cg, ch))
        member _.CommitAsync(topic, cg, offset) =
            agent.PostAndAsyncReply(fun ch -> Commit (topic, cg, offset, ch))
        member _.SnapshotAsync() =
            agent.PostAndAsyncReply Snapshot

    let create log offset cancel = Queue(makeAgent log offset cancel)

使用示例(单元测试场景,SQLite 实现 ILogStore / IOffsetStore,略):

let logStore = SQLiteLogStore("test.db") :> ILogStore
let offsetStore = SQLiteOffsetStore("test.db") :> IOffsetStore
use cts = new System.Threading.CancellationTokenSource()
let queue = ReliableQueue.create logStore offsetStore cts.Token

let msg = { Id = MessageId (Guid.NewGuid())
            Topic = Topic "orders"
            Body = Payload (System.Text.Encoding.UTF8.GetBytes "hello")
            Timestamp = System.DateTimeOffset.UtcNow }

let! off = queue.ProduceAsync(msg)
match off with
| Ok offset -> printfn "produced at %A" offset
| Error e -> printfn "produce failed %A" e

要点讲解

  1. MailboxProcessor 串行处理命令,天然无锁、顺序。
  2. 先写 WAL(Append),再更新内存,崩溃重启可重放。
  3. MessageId 全局唯一,消费端可用“幂等表”去重,实现 Exactly-Once。
  4. 整个核心纯函数化,副作用只在 Persistence 模块,测试时可用内存实现 Fake。

拓展思考

  1. 多节点分区:把 ILogStore 换成 Kafka 生产者,OffsetStore 换 Kafka 消费组协调器,即可水平扩展;F# 端只保留轻量级代理。
  2. 顺序与并行:同一 Topic 可再分 Partition,用 Consistent Hash 把 MessageKey 映射到 Partition,保证分区内顺序,同时提高吞吐。
  3. 零拷贝批量:生产端攒批后用 System.IO.Pipelines 一次刷盘,降低 SQLite 或 RocksDB 的 sync 次数。
  4. 背压与流控:MailboxProcessor 的 PostAndAsyncReply 会阻塞生产者,防止内存暴涨;若对接 gRPC,可结合 System.Threading.Channels 实现异步背压。
  5. 可观测性:用 OpenTelemetry 的 ActivitySource 在 Produce / Consume 埋点,把 TraceId 注入消息头,实现全链路追踪。
  6. 灾难恢复:定期把 SQLite 文件或 RocksDB 的 SST 上传到 OSS / COS,结合 K8s 的 StatefulSet 实现跨可用区重建。
  7. 形式化验证:用 F* 或 Dafny 把“日志先行”“幂等”写成引理,证明崩溃重启后状态一致,面试时可作为亮点提及。