Home›brandur.org›Article

Postgres: Boundless `text` and Back Again

Brandur Leach · Sep 10, 2021

AI summary AI-generated, may contain mistakes

Although common Postgres wisdom says unbounded text is preferable to varchar(n) since length constraints offer no performance benefit, the author recounts how at Stripe the lack of length checks on API text fields let legitimate users send enormous payloads that couldn't later be restricted without breaking backwards compatibility (a manifestation of Hyrum's law). He now recommends using varchar columns with liberal, standardized length tiers (e.g., 200, 2000, and 20000 characters) as a database-level backstop against wildly invalid data, while still validating lengths in application code with proper error handling. He also notes that Postgres can relax varchar constraints without an expensive table rewrite, and suggests encoding these tiers as SQL domains for consistency.

One of the major revelations for almost every new user to Postgres is that there’s no technical advantage of specifying columns as varchar(n) compared to just using bound-less text. Not only is the text type provided as a convenience (it’s not in the SQL standard), but using it compared to constrained character types like char and varchar carries no performance penalty. From the Postgres docs on character type (and note that character varying is the same thing as varchar):

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.

For many of us this is a huge unburdening, as we’re used to micromanaging length limits in other systems. Having worked in large MySQL and Oracle systems, I was in the habit of not just figuring out what column to add, but also how long it needed to be – should this be a varchar(50) or varchar(100)? 500? (Or none of the above?) With Postgres, you just stop worrying and slap text on everything. It’s freeing.

Keep reading

Out of respect for the author only the opening is shown here. Read the rest on the original site, or in HorizonReader with highlights, notes and AI help.

More from brandur.org

The Minimum Viable Unit of Saleable Software

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