The web version of ABN Signal, at abnsignal.com, has a search box for Australian business names. Behind it, a Go server reads from a PostgreSQL database that holds about 20 million name rows. The server talks to Postgres through a connection pool of only eight connections, and every page shares them: search, the page for a single business, and the hub pages that list recent changes.
In early November 2026 I found, on a local copy of the database, that a burst of searches could take all eight connections. While the searches ran, the other pages waited for a free connection, so a few people typing broad words into the search box could stall pages that had nothing to do with search. Under a local search burst, the 95th-percentile response time of a business page (the time 95% of requests stay under) reached 4.2 seconds. This post explains why each slow search held a connection for so long, and the four changes that fixed it.
A pool shared by every page
A connection pool is a set of database connections that the server opens once and lends to requests. A request borrows a connection, runs its queries and returns it. When all connections are lent out, the next request waits until one comes back.
The pool is kept at eight because the same database also serves the scripts that sync data from the Australian Business Register. Eight connections are plenty when every query takes a few milliseconds. They run out quickly when a few queries take seconds.
Every connection had a statement_timeout of 5 seconds. PostgreSQL aborts any statement that runs longer than this setting. PostgreSQL: statement_timeout It protected the database from runaway queries, but it also meant a slow search could keep a connection for the full 5 seconds before giving it back.
Why some searches were so slow
Search uses PostgreSQL full-text search. Each name is split into words, and a GIN index (an inverted index that maps each word to the rows that contain it) finds the rows that match a query. To make search-as-you-type work, the last word in the query is treated as a prefix: smi should match “Smith”. In a text-search query, :* after a word asks for prefix matching. PostgreSQL: text search queries
Short prefixes match a huge number of rows. I measured these on the local copy:
ma:*matched millions of rows.tru:*matched 704,000 rows and took 212 ms.- For prefix queries such as
qbe:*, the query planner (the part of Postgres that chooses how to run a query) estimated about 400,000 matching rows. With that estimate it chose to read all 20 million rows in order, a sequential scan. Run locally without a timeout,qbe:*took 77 seconds; in production the 5-second timeout would cut it off, after holding a connection the whole time. - The same overestimate also made the planner start parallel workers, extra Postgres processes that split one query between them. Starting them alone cost about 130 ms for a query that returned 63 rows.
So the problem was not one bad query. Any broad or misjudged prefix could hold a connection for up to 5 seconds, and three or four of those at once left the rest of the site waiting.
The fix, in four parts
1. At most three searches at a time
nginx, the web server in front of the app, already limited /search to one request per second per IP address. That does not help when several people search at once, so the app needs its own limit. Search now passes through a limiter with three slots. A search takes a slot without waiting. If all three are taken, it fails immediately with ErrBusy, and the page returns HTTP 503 with Retry-After: 5. Status 503 means the service is temporarily unavailable, and Retry-After tells the client how many seconds to wait before trying again. RFC 9110: 503 Service Unavailable
// internal/search/concurrency-limiter.go
func (l *LimitedSearcher) TryAcquire() (release func(), ok bool) {
select {
case l.slots <- struct{}{}:
return func() { <-l.slots }, true
default:
return nil, false
}
}
func (l *LimitedSearcher) Search(ctx context.Context, q string, limit int) ([]Hit, bool, error) {
release, ok := l.TryAcquire()
if !ok {
return nil, false, ErrBusy
}
defer release()
return l.inner.Search(ctx, q, limit)
}
The slots are a buffered Go channel with capacity 3. Sending into it takes a slot. The default branch of select runs when the send would block, so a fourth search never waits. Failing fast is deliberate. A search that queued behind three slow ones would only reach the database later, still holding an HTTP request open. Search, and the heavy bulk-lookup tools that share its slots, can never hold more than three connections, so at least five remain for other pages.
2. Search-only settings, applied before the query
Search runs in a read-only transaction, a group of statements that Postgres treats as one unit. The first statement sets four values for that transaction only. set_config(name, value, true) changes a setting until the transaction ends. PostgreSQL: set_config
// internal/db/search-queries.go
const searchSessionSQL = `SELECT set_config('enable_seqscan', 'off', true),
set_config('max_parallel_workers_per_gather', '0', true),
set_config('statement_timeout', '1500', true),
set_config('work_mem', '16MB', true)`
enable_seqscan offtells the planner to avoid a sequential scan when another method exists. It cannot forbid one entirely, but here the GIN index is always available. PostgreSQL: planner method settingsmax_parallel_workers_per_gather 0turns off parallel workers for search queries, which removes the start-up cost on small results.statement_timeout 1500lets a broad search hold a connection for 1.5 seconds instead of 5.work_mem 16MBgives each sort or index-bitmap step enough memory to keep exact row positions. With less memory, Postgres keeps only which pages match and has to recheck every row on them. The limit applies per step, not per query, but with three searches at a time memory use stays around 50 MB.
The detail that matters most is where this statement runs. It is tempting to fold the settings into the search query itself, for example in a subquery, to save a round trip (one message from the app to Postgres and the reply). That looks correct and does nothing useful. The planner plans the whole statement before any set_config inside it runs, so the planner settings arrive too late. The statement timer also starts when the statement starts, still with the 5-second value. The settings therefore run as their own statement, before the search, inside the same transaction:
func (p *Pool) inSearchTx(ctx context.Context, fn func(pgx.Tx) error) error {
return pgx.BeginTxFunc(ctx, p.pg, pgx.TxOptions{AccessMode: pgx.ReadOnly}, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, searchSessionSQL); err != nil {
return err
}
return fn(tx)
})
}
That costs four round trips (begin, settings, search, commit) instead of three. Each is under a millisecond on the same machine, a small price for settings that actually apply.
When the 1.5-second timeout fires, Postgres cancels the query with SQLSTATE 57014 (query_canceled). SQLSTATE is the standard five-character error code Postgres returns. PostgreSQL error codes The searcher wraps that error as ErrBusy, so a timed-out search shows the same short “Search is busy, try again in a few seconds” page as a full limiter.
3. Fewer broad prefixes
The query builder now adds :* only when the last word has at least four letters (it was three). It also skips the prefix when the word is the start of a word the search already ignores, such as “Pty”, “Ltd” or “Trust”. Without that rule, trus would become trus:* and pull in every name containing “Trust”, the exact word the search was trying to ignore. A shorter last word is still searched, but as an exact word.
4. A deadline for every request
statement_timeout only limits a query that is already running in Postgres. It does nothing for a request that is still waiting to borrow a connection. A middleware, code that runs around every HTTP handler, now gives every request a Go context that expires after 8 seconds. A context carries a deadline that every function the request calls can check:
ctx, cancel := context.WithTimeout(r.Context(), d)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
pgx, the Go PostgreSQL driver the server uses, stops waiting for a connection when the context expires, and the handler returns a 503 page. Eight seconds is below the Go server’s 15-second write timeout and nginx’s 20-second timeout for waiting on the app, so the app can still send that page itself. Otherwise nginx would cut the connection and return a generic error.
The same change adjusted the pool. It now keeps four connections warm instead of one, closes idle connections after 5 minutes instead of 30 seconds, and recycles each connection after about an hour, with up to 10% random extra time. pgxpool’s MaxConnLifetimeJitter exists to stop every connection from closing at the same moment. pgxpool.Config
How I checked it
Each part has a test that would fail if the fix silently stopped working.
- The timeout really applies. A test opens a search transaction and runs
SELECT pg_sleep(2). It expects error57014after about 1.5 seconds. If the settings were folded back into the same statement, the sleep would finish after 2 seconds and the test would fail. - The plan avoids sequential scans. Inside a search transaction, the test runs
EXPLAINon the real search query withqbes:*and fails if the plan containsSeq Scan on abn_recordsorSeq Scan on abn_other_names. - The limiter fails fast. With one slot held by a blocked search, a second search must return
ErrBusyin under 50 ms, and the slot must be reusable after release. - The deadline reaches the search. A test sends a request through the full server handler chain and checks that the search call receives a context with the 8-second deadline.
After the change, the same local search burst no longer moved the business page’s 95th-percentile time: 8 ms, against 4.2 seconds before.
The first test is the one that matters most. Reading the settings back with current_setting only proves they were set, not that they applied to the query that followed. A query that must be cancelled at 1.5 seconds proves both.
What I would do earlier next time
- Give an expensive endpoint (one URL the server answers, here
/search) its own concurrency limit when it shares a small pool with cheap pages. Size the limit so the cheap pages always have connections left. - Fail fast instead of queueing. A quick 503 with
Retry-Afteris better for everyone than a slow page that times out anyway. - Set per-query planner settings and timeouts as a separate statement before the query, and prove it with a test that sleeps past the new timeout.
- Remember that
statement_timeoutdoes not cover the wait for a connection. A request-level deadline does. - Measure the worst queries, not the typical ones. A planner estimate that is off by a factor of thousands turned a few-millisecond search into a 77-second scan.
Conclusion
When one slow endpoint can stall a whole site, the fix is usually to bound it, not to make it faster everywhere. Cap concurrent searches below the pool size and give search a shorter timeout that really applies. Refuse the broadest prefixes, and put a deadline on the wait for a connection. ABN Signal’s search can still be slow for a broad query, but it can no longer take the other pages down with it.