Skip to content

Rake task to reindex an index

The initial iteration will be to implement a Rake task which takes a single index name as its argument, and recreates the matching index. At a high level this means:

  1. Concurrently create a new index with temporary name matching the existing index definition.
  2. Use with_lock_retries to swap the names of the new and original index in a transaction, as renaming an index takes an ACCESS EXCLUSIVE lock on the index (at least in PG 11).
  3. Drop the original index.

Couple error cases that should be handled:

  • Disallow the rake task to operate on PRIMARY KEY or UNIQUE indexes.
  • Currently, if with_lock_retries exhausts all configured attempts to acquire the lock, it sets the lock_timeout to 0 and proceeds, to ensure the migration completes. Since a reindex is a non-critical operation, instead cleanup the temporary index and fail the rake task if the lock cannot be acquired.
Edited by Joshua Lambert