90 points · by shayonj · 2y ago · 54 comments
In my experience on large tables that are “busy”, sometimes indexes need to be added manually first from a utility session, perhaps inside tmux/screen that's detached from while they are created. This could take hours for large tables. Then once done, and the index is valid, an Active Record migration can be sent out using “if_not_exists: true” to make sure it’s applied everywhere.
Your point that it could be misused unintentionally due to not knowing an index is INVALID is a good one, and I feel it should be part of how it works by default in Active Record. Had you considered trying to propose that to rails/rails? I would certainly support that PR (may be able to collaborate) and could add more examples and validation.
I've suggested some proposals to Rails here and would love to propose a PR based on the solution that makes the most sense, too.
That all said, still would be cool to make this the default in Active Record. Nice idea!
I have a job that runs nightly or weekly and performs a concurrent reindex on tables, which nicely covers cases like this.
Given that lock timeouts are very much "rescuable," I'm also thinking about addressing the problem right at the start (when adding migrations) by implementing retries. This approach at least would eliminate the need for any follow-up steps by developers and reduce additional cognitive load.
The ideal goal being "The system just works"™ :D
Maybe idempotency was a design goal.
-- migrate-2024-08-12-foo.sql
create table [..]
alter table [..]
insert into migrations values ('migrate-2024-08-12-foo');
And the create works, but the alter fails. And then you try to run it again and now the create fails because you have half a migration. Herp derp.And you often can't split those two statements either: that would be "half a migration" that won't work with the code.
As far as I know there isn't really a good solution for this. It can be quite a pain.
In PostgreSQL and SQLite this is not an issue as you can run all the above in a transaction. You indeed rarely need "if not exists" there.
Depending on what the timeout is (connection timeout, transaction timeout etc) the DDL operation _may_ still be running. But the migration "process" has failed. So you end up having to slightly modify the attempted migration to account for the fact the thing already exists.
It's an increasingly rare occurrence, probably a few times a year. Like anything the more we do it, the better we get at pulling left and preventing issues in the first place.
What terrifies me though is the CONCURRENTLY, which indicates automated DB migrations doing stuff outside of transaction boundaries. This stuff should be rare, to the point it is applied manually under supervision. Any step outside the transaction boundary can fail and needs a recovery plan. And you can't automate it because part of the recovery plan might be to fix the networking glitch to see if your statement failed, succeeded but failed to report success, or is ongoing with an uncertain future. And if you have multiple migration steps, that is multiple intermediate database states that you probably haven't tested your app against (say, timeouts because you dropped a necessary index before creating a new one, hopefully one that doesn't take several hours to build).
Why isn't index creation done the same way?
The docs explain the mechanics further: https://www.postgresql.org/docs/current/sql-createindex.html...
If you don't care about visibility until the end and just want nested atomicity, you can use savepoints as a kind of nested transaction, but they won't be visible to other sessions until the top level transaction is committed.
CREATE INDEX CONCURRENTLY has steps where it needs to make changes visible and wait until no transactions are open from before that point, so it can't use savepoints.
The subtransactions are exposed to SQL as savepoints but my point still holds.
I am not sure what would be needed to implement concurrent index build but subtransactions would not help.
Your transaction isolation mode defines how they compose.
Unless you are asking something different.
So you can interleave writes and (partially complete) indexing.
If you want transactional index creation, just omit CONCURRENTLY.
This argument doesn't make much sense. What's the usefulness of a partially created index? The entire rest of the article is working hard to explain how this invalid index is 100% useless and should be dropped!
So this seems like a bug in PostgreSQL to me.
REINDEX INDEX CONCURRENTLY
^ it can be rebuilt.I'm honestly not sure if this is saving anything except re-defining (i.e. the literal "create index" statement), but they seem definitely not 100% useless despite being invalid. Maybe 99% useless, but "drop it in the background" doesn't seem particularly better either - leaving intermediate state for an admin to tackle by hand seems reasonable.
And how do you clean up after an aborted index build?
[1]: https://www.postgresql.org/docs/current/sql-reindex.html
However, for application developers - unless you are familiar with the internals, this comes off as a big surprise.
Would love to learn more from folks who are more familiar with the internals.
A classic example is a massive table on production, but an empty table on dev. Dev gets migrated fine, but prod fails for reasons. You now need to resolve it.
Also, we have a convention (not enforced) that we let PostgreSQL name the relation (e.g PK, UQ, Index et al) for us.
So we don't do:-
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_test_data ON test_table (data);
We do:-
CREATE INDEX CONCURRENTLY ON schema_name.table_name (column_name);
Huh? So what's the point of having PostgreSQL pick the name for you? I assumed it would be so that it picked a new name if one with that name already existed (and my objection is that you're then just storing up trouble for when the time comes to drop the index), is that not it?
In general, it's not something that happens. But that is how we've resolved it in the past.
Broken indexes are intentionally left because indexing can be a long operation on a big db, so you may regret not just repairing them..
Let's delete and recreate indexes all the time, just in case because they might be left over..
Hope we don't encounter the reason they left broken indexes and wait a few hours for a rebuild?
(I.e. I could imagine a customer upgrading from a version that already backported an index to the new major version where it was added and deciding there's a performance regression.)
Furthermore, failed concurrent index or re-index will leave invalid cursors behind that are not usable but incur the update costs. Of course, they consume the disk space.
Use with caution.
SELECT indrelid::regclass tbl, indexrelid::regclass idx FROM pg_index WHERE NOT indisvalid;
And then sends that to Slack or whatever if it returns a result.