Eradicating N+1s: The Two-phase Data Load and Render Pattern in Go
Brandur Leach · 2024年5月28日
AI 摘要 AI 生成,可能有误
文章解释了 N+1 查询问题:由于关联关系的延迟加载,渲染一组记录时会为每条记录触发一次额外的数据库查询;文章还综述了多种缓解策略,例如 ActiveRecord 的预加载(eager loading)、Rails 6.1 的严格加载(strict loading),以及 Stripe 创造性地利用 Ruby 纤程(fibers)来批量处理数据库意图。随后,文章描述了作者在现公司如何在 Go 中采用两阶段的“加载-渲染”模式,即在渲染之前通过批量查询加载所有所需数据,该模式已连续两年消除了 N+1 问题。尽管 Go 语言天生冗长且缺乏优秀的 ORM,这一模式依然运转良好。
Author’s note: This is a longer piece that starts off with exposition into the nature of the N+1 query problem. If you’re already well familiar with it, you may want to skip my description of N+1 to a story involving a creative use of Ruby fibers at Stripe to try and plug this hole, or the two-phase load and render that I’ve put in my current company’s Go codebase, a pattern we’ve been using for two years now that’s rid of us N+1s, and for which I’d have trouble citing any deficiency (aside from Go’s normal trouble with verbosity). It works.
Let’s say we have a model Product that can render a public-facing API resource for itself by implementing #render. I’ll be talking about API resources a lot because that’s what I’m used, but keep in mind that this could also be an object that’s used to render an HTML view and all the same concepts apply.
继续阅读全文
为了尊重作者,这里只展示开头几段。你可以去原文阅读,或者在 HorizonReader 里读:划线做笔记、让 AI 帮忙。
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.
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.
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.
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".
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.