首页›brandur.org›文章

The Notifier Pattern for Applications That Use Postgres

Brandur Leach · 2024年5月6日

AI 摘要 AI 生成,可能有误

本文介绍了适用于使用 Postgres LISTEN/NOTIFY 的应用程序的“通知器模式”(notifier pattern):每个进程仅用一个 Postgres 连接来管理所有主题订阅,并将收到的通知分发给需要它们的各个组件,与朴素的每个主题一个连接的做法相比,节省了 Postgres 有限的连接资源。关键实现细节包括:使用带缓冲的通道并进行非阻塞发送,使慢速组件不会拖垮整个系统;多个订阅者复用同一主题的单个 LISTEN;用“established”通道来确认订阅以便测试;可中断的通知等待,以便及时处理新订阅;以及针对不健康连接的崩溃重启处理。该模式仍与 PgBouncer 兼容,因为只有这一个专用连接需要会话级连接池,而应用程序的其余部分可以使用事务级或语句级连接池。

Listen/notify in Postgres is an incredible feature that makes itself useful in all kinds of situations. I’ve been using it a long time, started taking it for granted long ago, and was somewhat shocked recently looking into MySQL and SQLite to learn that even in 2024, no equivalent exists.

In a basic sense, listen/notify is such a simple concept that it needs little explanation. Clients subscribe on topics and other clients can send on topics, passing a message to each subscribed client. The idea takes only three seconds to demonstrate using nothing more than a psql shell:

But despite listen/notify’s relative simplicity, when it comes to applications built on top of Postgres, it’s common to use it less than optimally, eating through scarce Postgres connections and with little regard to failure cases.

继续阅读全文

为了尊重作者,这里只展示开头几段。你可以去原文阅读,或者在 HorizonReader 里读:划线做笔记、让 AI 帮忙。

更多来自 brandur.org

The Minimum Viable Unit of Saleable Software

AI 摘要The author, who recently left Stainless to run River (a job queue for Go and Postgres) as a business, addresses skepticism about selling software in the age of LLMs by arguing that building internal replacements with AI is cheaper than before but still not free. Using cost math with examples like a $400/mo Jira subscription (not worth rebuilding) versus $25k/mo of Salesforce seats (worth building), he proposes a 'zone of viability' where software with enough novelty and reasonable pricing remains cheaper to buy than to build. He hopes River, with its advanced Pro features and sublinear team-based pricing starting at $125/mo, sits above the 'minimum viable unit of saleable software' and remains a sustainable business.

The Second Wave of the API-first Economy

AI 摘要The article recounts the 'first wave' of open APIs in the early 2010s, exemplified by Facebook, Twitter, and GitHub, followed by an 'API winter' when companies restricted access due to monetization pressures, abuse, and competitive risks. The author predicts a 'second wave' driven by powerful LLM agents acting on users' behalf, which will make APIs a key competitive factor across services like banks, retailers, and social platforms. Unlike the first wave, these APIs will mirror first-party product capabilities for individual users' agents, with simpler security models and stricter rate limiting rather than enabling third-party apps.

Eradicating N+1s: The Two-phase Data Load and Render Pattern in Go

AI 摘要The article explains the N+1 query problem, in which rendering a collection of records triggers an extra database query per record due to lazy loading of associations, and it surveys mitigation strategies such as ActiveRecord eager loading, Rails 6.1's strict loading, and Stripe's creative use of Ruby fibers to batch database intents. It then describes how the author adopted a two-phase load-and-render pattern in Go at their current company, which loads all required data in batched queries before rendering and has eliminated N+1s for two years. The pattern works well despite Go's inherent verbosity and lack of a good ORM.

Web APIs: Enriched DX By Disallowing Unknown Fields

AI 摘要The article explains how Go's DisallowUnknownFields JSON decoder option improves developer experience for web APIs by returning an error when a request contains fields that don't exist in the target struct, catching mistakes like sending "expires" instead of "expires_in". It also covers practical caveats, such as safely enabling the check on existing APIs through logging probes and grandfathering known bad fields, deprecating old fields carefully, and providing escape hatches for endpoints like webhook receivers. Finally, it notes the pattern is portable to other languages and can be enhanced with Levenshtein distance suggestions, e.g., telling users who send "expires" that they probably meant "expires_in".

River: a Fast, Robust Job Queue for Go + Postgres

AI 摘要The author introduces River, a new open-source job queue for Go built on Postgres and the pgx driver, now available in beta. He explains why transactional, database-backed job queues avoid a host of distributed systems problems, and argues that past troubles with Postgres queues (like those at Heroku) are now mitigated by modern advances such as Go generics and goroutine concurrency, Postgres features like SKIP LOCKED and index optimizations, and a minimized single-dependency stack. River offers strongly-typed jobs, batch insertion, unique and periodic jobs, and solid performance, processing around 10,000 trivial jobs per second on a laptop.