首页›brandur.org›文章

SortSupport: Sorting in Postgres at Speed

Brandur Leach · 2019年2月4日

AI 摘要 AI 生成,可能有误

The article explains SortSupport, a Postgres optimization that speeds up sorting by storing abbreviated keys—compact digests of larger pass-by-reference values—directly in sort tuples, avoiding slower references back to the heap; this made UUID sorting roughly twice as fast and string-based operations like CREATE INDEX about three times faster. It walks through the implementation using UUIDs as an example, covering how abbreviated keys are built, byteswapped for little-endian architectures, and compared as integers, with full-value 'authoritative comparisons' used as a fallback when abbreviated keys tie. Finally, it describes a safety mechanism that uses HyperLogLog to estimate cardinality and abort abbreviation on low-cardinality data sets where the optimization would actually hurt performance.

Most often, there’s a trade off involved in optimizing software. The cost of better performance is the opportunity cost of the time that it took to write the optimization, and the additional cost of maintenance for code that becomes more complex and more difficult to understand.

Many projects prioritize product development over improving runtime speed. Time is spent building new things instead of making existing things faster. Code is kept simpler and easier to understand so that adding new features and fixing bugs stays easy, even as particular people rotate in and out and institutional knowledge is lost.

But that’s certainly not the case in all domains. Game code is often an interesting read because it comes from an industry where speed is a competitive advantage, and it’s common practice to optimize liberally even at some cost to modularity and maintainability. One technique for that is to inline code in critical sections even to the point of absurdity. CryEngine, open-sourced a few years ago, has a few examples of this, with “tick” functions like this one that are 800+ lines long with 14 levels of indentation.

继续阅读全文

为了尊重作者,这里只展示开头几段。你可以去原文阅读,或者在 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.

The Notifier Pattern for Applications That Use Postgres

AI 摘要The article introduces the 'notifier pattern' for applications using Postgres LISTEN/NOTIFY, in which a single Postgres connection per process manages all topic subscriptions and distributes received notifications to the various components that want them, conserving Postgres's limited connections compared to the naive one-connection-per-topic approach. Key implementation details include buffered channels with non-blocking sends so slow components can't stall the system, reusing a single LISTEN per topic for multiple subscribers, an 'established' channel to confirm subscriptions for testing, interruptible notification waits so new subscriptions can be processed promptly, and crash-and-restart handling for unhealthy connections. The pattern remains compatible with PgBouncer since only this one dedicated connection needs session pooling while the rest of the application can use transaction or statement pooling.

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".