使用 Cloudflare Queues 实现双缓冲
Double Buffering with Cloudflare Queues

原始链接: https://bellone.com/technical/double-buffering-with-cloudflare-queues

我使用双缓冲队列来收集遥测事件,并按 UTC 小时分组。我的管道利用 Cloudflare Workers、Queues、Workflows 和 R2 来捕获、批处理、处理和存储遥测事件,同时最大化 Cloudflare 定价的优势。取模运算用于将负载路由到活跃队列,以及再次用于清空非活跃队列。使用 UTC 以避免夏令时处理。生产者:生产者评估负载的时间戳,将消息路由到活跃队列:消费者:消费者任务每小时半点触发,以清空非活跃队列:消费者任务回溯一小时,以确定当前哪个队列是非活跃且可安全消费的:最后,批次被压缩并使用简单的分区策略写入 R2:这种模式将混乱的遥测流转换为压缩的每小时归档。你得到一个针对下游分析优化的分区、无服务器数据湖,同时将云存储账单保持在极低水平。

一篇 Hacker News 帖子链接到一篇关于使用 Cloudflare Queues 进行遥测双缓冲的文章。作者描述了一种无状态边缘模式,它批处理遥测数据,并几乎将 Cloudflare 写入成本降至零。评论称赞其巧妙,但提出可靠性担忧:错过的 cron 作业或消费者失败可能导致事件误批处理,单个每小时 gzip 文件可能带来数据丢失风险;有评论者建议使用 zstd 压缩。还有关于使用小时奇偶性进行队列选择的代码的争论,包括一个 JavaScript 运算符优先级 bug 和一个更清晰的替代方案。价格讨论指出 Cloudflare R2 对写入、读取和存储收费,并有免费层级;每小时批处理将写入减少到每月约 720 次,使存储成为主要支出。还有用户报告该博客页面出错。
相关文章

原文

I use a double-buffered queue to collect and segment telemetry events into groups bound by UTC hour. My pipeline leverages Cloudflare Workers, Queues, Workflows, and R2 to capture, batch, process, and store telemetry events while maximizing the benefits of Cloudflare's pricing.

Modulo math is used to route the payload to the active queue and again to drain the inactive queue. UTC is used to avoid DST handling.

Producer

The producer evaluates the payload's timestamp to route the message to the active queue:

Consumer

The consumer task triggers every hour on the half-hour to drain the inactive queue:

The consumer task looks back one hour to determine which queue is currently inactive and safe to consume:

Finally, the batch is compressed and written to R2 using a simple partitioning strategy:

This pattern transforms chaotic streams of telemetry into a compressed hourly archive. You get a partitioned, serverless data lake optimized for downstream analytics, while keeping your cloud storage bills incredibly low.

联系我们 contact @ memedata.com