Don't rely on IF NOT EXISTS for concurrent index creation in PostgreSQL
shayon.dev
shayon.dev
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
Lock Timeout Retries [experimental] https://github.com/ankane/strong_migrations
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.
We design migrations in such a way so that new schemas/data never conflict with already running (old) code. And new code is activated only after all migrations completed successfully. So in practice half completed migrations is rarely an issue for us.
But yeah, it requires more boilerplate. However, there's fewer surprises, compared to IF NOT EXISTS.
drop index old;
create index new [..];
There's tons of examples like this where things can kind-of work with enough effort, but also not really – if the query takes 5 minutes without that index it's just going to timeout, so not that different from having broken code, and not much you can do about that too. You really want those two combined to be atomic.And in cases of "create table new; drop table old" using the old table is often 1) a major hassle, and 2) often doesn't actually work all that well as it's not a tested path.
Either way, it seems MariaDB does support transactions for all of this if you disable "autocommit mode", judging from their docs? I haven't used MySQL/MariaDB in quite a few years, but I've never seen migrations for them done well without tons of hassle and it's a major reason I've typically recommended PostgreSQL. It's just eliminates an entire class of common headaches and errors.
create index new [..]
drop index old;
At every point, there's always an index to use. We usually have to split releases into several "subreleases":Release #1
(automatic migration step)
- alter the table
- add a new index which uses new columns (etc.)
(code release step)
- new code goes live and starts using the new index
Release #2 (we call it "post release") - remove the old unused index
Automation, CI/CD help here. Yeah, it's somewhat error prone, but you usually get used to it. Not saying it's perfect, but manageable.In any case, you can never make both SQL migration and code release atomic (if you use rolling updates with zero downtime) so you already have to split into such subreleases anyway.
Of course; I'm just saying this is why people want idempotency and use "if not exists", especially in MariaDB/MySQL land.
No, DDL cannot be used in a transaction in any version of MySQL or MariaDB.
> I've typically recommended PostgreSQL. It's just eliminates an entire class of common headaches and errors
That's fair, but it does create new headaches, for example the notion of an invalid index (as described in the post) simply does not exist in MySQL or MariaDB. Index creation does not block concurrent writes, and won't fail mid-stream due to a lock conflict with old row purging (equivalent to PG's vacuum). And if a DDL statement somehow does fail, e.g. due to an ill-timed host crash, it is fully cleaned up -- DDL is atomic, just not transactional.
One way to avoid the "half a migration" problem you mentioned up-thread is to use declarative schema management, which doesn't require tracking completion state of "migrations" at all: https://www.skeema.io/blog/2019/01/18/declarative/
I have actually never seen people adopt those. And the "enterprise" tools people tend to circle around seem to create more failure modes than it helps solving. But I imagine somebody uses them somewhere.
Without those tools, you can break your migration around the failure point and mark the first half as complete. You should have some way to mark them, because you always need some channel for "free" management of a database.
Anyway, transactional DDL is great.
You have a started and finished columns and/or a state column on your migrations table;
Insert into migrations; Run migration foo; Update migrations set finished = now, state = finished where migration = foo;
Then your deploy tool refuses to run (and reports an error) when there are any non-finished migrations found.
Honestly if your migrations need `if not exist` regularly for basic stuff like creating tables or whatnot something is wrong - it implies you can't rely on other migrations having been performed at which point you have no reasonable way to expect that the end result will be correct.
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.
SET statement_timeout = '1h';
CREATE INDEX...
Or if you have a DDL user (which is smart; your app user should not be allowed to execute DDL), you can use `ALTER ROLE` for them to have whatever defaults you'd like.MySQL has a similar variable, `max_execution_time`.
Most people copy and paste a previous migration and then amend it to their previous needs. So if the previous migration set the statement timeout to 1h, and the new migration is doing something we want to stop/prohibit like ADD COLUMN DEFAULT (which takes a lock) or SET NOT NULL on a huge table (which again can cause a lock). We want to prevent locking and prefer the migration to fail earlier and hit the default statement timeout. At which point a conversation occurs how best to do the DDL without effecting prod.
In terms of DDL DML users; we have it split into three-
DDL (Migrations) DML (Data only, e.g. correcting data) AppTier user (which is DML + a few more things)
The rise of RDS et al. has utterly killed the majority of people’s knowledge of RDBMS, if they had it to start with. It’s a shame. Also a solid and enjoyable career for me, so I suppose it’s not all bad.
I pick and choose my battles and where possible enforce certain rules (e.g. you have to have `timestamp with time zone` etc etc) at build time.
I personally find learning about stuff fun! It's why I've grown as an engineer and now have the capability to debug past the code stack into the database.
You have to pick and choose your battles, those engineers who shown interest (what is an index and why do we need it type of questions) I take my time to educate and move the critical mass/inertia in the right direction.
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...
Your transaction isolation mode defines how they compose.
Unless you are asking something different.
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.
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.
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.
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.
And how do you clean up after an aborted index build?
[1]: https://www.postgresql.org/docs/current/sql-reindex.html
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.
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?
I would snapshot the entire production schema every month or two with pg_dump and back port it into the dev tree, precisely to catch any unintended drift such as differences in naming, triggers, indexes etc. that fell between the cracks.
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.