Making a Postgres query 1k times faster
mattermost.com
mattermost.com
A UNION allows you to use two separate indexes and can speed up queries.
I've used that OR > UNION ALL trick a number of times to vastly improve performance on specific queries. It's crazy how much of an effect it can have.
I wish Postgres would implement a planner optimization to automatically run queries with an OR more efficiently (e.g. use the same plan as with a UNION/ALL where possible).
Found it: https://www.postgresql.org/message-id/flat/7f70bd5a-5d16-e05...
I just did some more digging, and it looks like there has been some more recent discussion in a different thread about the same topic though: https://www.postgresql.org/message-id/flat/567ED6CA.2040504%...
You can really do some complicated pipelining of data cleaning and filtering this way, much faster than resorting to a whole bunch of complicated inline SQL work in the clauses.
[edit] I should add, learn how to read an explain plan, this is vital for understanding and improving your queries.
There have been more recent attempts to improve OR clause performance in another thread: https://www.postgresql.org/message-id/flat/567ED6CA.2040504%...
Of course UNION [ALL] does often yield better performance, yes.
There’s a difference between the two. https://www.postgresql.org/docs/current/sql-expressions.html...:
“The order of evaluation of subexpressions is not defined. In particular, the inputs of an operator or function are not necessarily evaluated left-to-right or in any other fixed order.
Furthermore, if the result of an expression can be determined by evaluating only some parts of it, then other subexpressions might not be evaluated at all. For instance, if one wrote:
SELECT true OR somefunc();
then somefunc() would (probably) not be called at all. The same would be the case if one wrote: SELECT somefunc() OR true;
Note that this is not the same as the left-to-right “short-circuiting” of Boolean operators that is found in some programming languages.”https://www.postgresql.org/docs/current/functions-comparison...:
“For the <, <=, > and >= cases, the row elements are compared left-to-right, stopping as soon as an unequal or null pair of elements is found.”
So, this is using something akin to short-circuiting.
I think that can mean the two give different results in the presence of null values.
⇒ I would guess the optimizer isn’t smart enough to detect when the second, stricter query will be equivalent and faster.
The author filtered with:
CreateAt > $1 OR (CreateAt = $1 AND Id > $2)
That can't use one index for both conditions. Instead, make it faster and simpler: (CreateAt, Id) > ($1, $2)
End of post.1. Always use BUFFERS when running an EXPLAIN. It gives some data that may be crucial for the investigation.
2. Always, always try to get an Index Cond (called Index range scan in MySQL) instead of a Filter.
3. Always, always, always assume PostgreSQL and MySQL will behave differently. Because they do.
The article felt like it was fumbling around when the initial explain pointed right at the issue. I didn’t know this specific trick, so I did learn something I guess.
The query should be CreateAt > $1 OR (CreateAt = $1 (NOT $2 like in your sample) AND Id > $2)
So the idea is here about paginating through posts that might be constantly changing so you can't use a simple offset, as that would give you duplications along the way. So you try to use CreateAt, but it could be possible that CreateAt is equal to another one so you fallback to ID.
But here I stopped reading the blog post, because I now think why not use Id in the first place since it also seems to be auto increment since otherwise you couldn't really rely on it to be a fallback like this? I don't have time to investigate it further, but tldr; that still left me confused - why not use ID in the first place.
https://dba.stackexchange.com/questions/266405/does-ordering...
Or besides that, if there are odds of CreateAt collision, and you are fallbacking to ID, you are still possibly not getting it chronologically?
And also if CreateAt does happen to equal to another record that is exactly the case where Postgres might most likely not have the auto incr chronological.
So still it seems like the edge case it tries to prevent it would still happen at least at similar magnitude of odds.
edit: on second review if live insertions were occurring then this code would have an edge case, however the indexing job has an endtime presumably chosen where they can be sure no more inserts will occur. Given that the choice to use a timestamp probably has to do with the fact that there are 4 different tables being indexed and you would otherwise have to track their IDs individually.
original:
id, timestamp
1 , 1000
2 , 1001
4 , 1002
--------- limit stops here
5 , 1002
3 , 1003
ID only: If we use ID > 4 as our start point for next time and ID 3 was not inserted yet then we will have missed itcreatedAt only: If we use createdAt > 1002 then we will skip ID 5 next batch
OPs strategy: Even if we use createdAt > 1002 and it skips ID 5 it will be caught by createdAt = 1002 AND ID > 4. The Order by createdAt asc, id asc guarantees that if the limit splits 4 and 5 that we see 4 first and thus don't miss 5. I think this does still miss the case where ID 4 is inserted after ID 5 however.
Yeah, and I would think that is very likely to happen given it would be the same timestamp.
So the whole thing still seems like a flawed, and unnecessarily complex solution to me, which should just use one simple unique sortable field to do all of it.
Like my intuitive guess is that maybe the solution could save maximally 20% - 40% of the same edge case, which doesn't seem like a good solution. It is not going to solve the problem. It's just adding complexity that can cause other problems.
So if postgres does the type of caching where it allocates 10 auto incr IDs to each process, which causes sometimes IDs being out of order, then normally it would be just enough to wait after these allocations have performed and index then, you are not going to miss any rows.
I would assume these processes have some form of timeout if there was a case where they couldn't assign one of those IDs, and then this ID would just maybe not exist or if there was a mechanism to reallocate that would work too, but none the less, I think some form of postgres sortable unique id would have to work by itself.
Because it's ">" it might be missing that one record during what I think is pagination.
[edit] CreatedAt timestamp could be something from the client when the post is submitted or tagged from the ingest server and not when they actually are processed and hit the database
And I agree I shouldn't have said "auto increment".
(my guess is time based index offer faster search performance or lower overhead than a string based search index which doesn't understand it is representing encoded time data)
And with fallback they would end up reusing that index anyway.
But here the case should be batch indexing, processing, so it seems like auto incr with a timeout of assignment if those auto incr ranges are cached would still be suitable.
Like as I understand the problem, there is one service (ElasticSearch) that is working on indexing, and it's getting batched rows from postgres, to then index, but make sure at the same time to not miss any in those batches. And it's fine that it doesn't immediately at this second or minute do the indexing, so it should be fine to wait for the IDs to have been allocated.
From article one of them is: 'tpomh9yu1tffmdp6dopobwuc9h'
But the query is trying to page through the most recent posts first.
So a newer post doesn't necessarily have a higher ID or lower ID.
The ID is just there to have a stable tie break between the same timestamps.
If this assumption is correct, then first sorting by the timestamp and then sort the id alphabetically will ensure that the pagination is deterministic.
I guess we could consider some edge cases where we have lots of rows with the same timestamp that is inserted after the ingestion query is run due to latency, but it might be acceptable for this use case.
Thats a way bigger undertaking and decision then just optimizing a single query.
Like killing an ant with a Tsar Bomb.
The true "modern" cool kids solution would of course be to create a service that listens to WAL, inserts it into a Kafka cluster that is connected to a pipe for inserting into Elastic search. Much more fun and resumé friendly than optimizing a query. I bet the author of this blog would get a much larger audience.
Bonus points if the ingestion service was written in Rust and run on a serverless platform
You can switch the uuid generation, wait a little bit and add an.'archive' switch which will use the old and slower query when the date is old.
Should definitely be helpful resource wise for a lot of people
Otherwise it will cost more and more.
Especially for a chat app!
Did not know you could do "tuple" filtering like this
WHERE Posts.CreateAt >= ?1 AND Posts.Id > ?2 (where ?1 and ?2 are the current cursor values)
WHERE Posts.CreateAt > ?1 OR (Posts.CreateAt = ?1 AND Posts.Id < ?2) ORDER BY Posts.CreateAt ASC, Posts.Id DESC
I now wonder if it might be possible to use a negation operator to invert the sorting order, like:
(Posts.Id, -Posts.CreateAt) < (?1, ?2) ORDER BY Posts.CreateAt ASC, Posts.ID DESC
and keep the performance improvement.
Is not the same as:
> CreateAt, Id) > (?1, ?2)
Because it is like that:
> createdAt > ?1 OR (createdAt <= ?1 and Id > ?2)
Or am I wrong?!
Does mm not have the stats table active and check it sometimes for this kid of issues?
Based on the last time I did anything involving databases, I think the easy way to do this is "find a query written by someone like olliej, and then fix the clear and obviously stupid choices" :D
Sure, but if you are going to be self deprecating, at least provide some example content of the hilariously bad queries you have written and how you have been chastised for them.
Step 1: use the index
Step 2: see step 1