Video in progress
Users can build arbitrary queries through a generic filter API (GraphQL, admin search). How do you protect the database from heavy queries?
Several layers: at the API level a complexity limit and an allowed list of filter/sort fields, mandatory pagination, and building the query only on indexed fields; at the database level, statement_timeout with a separate role, a connection limit, and routing to a replica if possible.
📖 Answer
A free-form query API is a hole through which anyone can send "any SQL" to the database. A single sort=description and limit=100000 can choke the whole cluster.
The API layer:
- Filtering and sorting only on whitelisted fields, each of which has an index. Sorting on a field without an index is forbidden.
- A mandatory
limit(maximum 100) and keyset pagination; nooffset=1000000. - In GraphQL, a query depth and complexity limit, and closing N+1 with a DataLoader. A limit on each nested list.
- A mandatory and bounded date range (say, 1 year).
- Rate limiting per user.
The database layer:
CREATE ROLE search_api LOGIN CONNECTION LIMIT 20;
ALTER ROLE search_api SET statement_timeout = '2s';
ALTER ROLE search_api SET work_mem = '16MB';
ALTER ROLE search_api SET default_transaction_read_only = on;
The search service works with its own pool and its own role, so even if it hits a timeout it doesn't take the main API's connections.
Monitoring: this role's queries in pg_stat_statements, and the number of timeouts (57014). A filter combination that times out a lot is a signal to add an index or remove it from the UI.
If the requirements grow to free-text search, facets and multi-attribute filtering, I propose moving that load to a search system like Elasticsearch/OpenSearch through CDC. An OLTP database isn't built for queries like that.
Sign up to mark studied questions and save your progress.