Video in progress
The `GET /orders` endpoint has 8 optional filters (status, date, customer, amount...). How do you design the indexes and the query?
You can't put an index on every combination. I find the 2-3 most used filter patterns in real traffic and put composite indexes on them, and I build the query dynamically with only the filters that were given. A "universal" query like (:status IS NULL OR status = :status) confuses the planner.
📖 Answer
A very common anti-pattern:
SELECT * FROM orders
WHERE (:status IS NULL OR status = :status)
AND (:customer IS NULL OR customer_id = :customer)
AND (:from IS NULL OR created_at >= :from)
ORDER BY created_at DESC
LIMIT 50;
With a prepared statement the generic plan is one for all cases, and it usually picks a Seq Scan.
I build the query based on the filters given, with the Criteria API, Specification, jOOQ or QueryDSL:
Specification<Order> spec = Specification.allOf(
eq("status", f.status()),
eq("customerId", f.customerId()),
gte("createdAt", f.from())); // if null, no condition is added
I pick indexes by measurement. From the logs or metrics I see which filter combinations are used most. Usually the picture is like this: 70% of queries come with customer_id, 20% with status + date, and the rest are rare. So:
CREATE INDEX ON orders (customer_id, created_at DESC);
CREATE INDEX ON orders (status, created_at DESC);
The remaining rare combinations run slower with a Bitmap AND or a partial scan, and you can live with that.
You need guardrails too: a mandatory date range (say, no more than 90 days), a mandatory LIMIT and keyset pagination, and statement_timeout. If a very free-form search (text, many attributes) is required, I'd discuss moving it to Elasticsearch.
Sign up to mark studied questions and save your progress.