Ruby has had support for UUIDv7 since version 3.3 (released in 2023) and PostgreSQL since version 18 (released in 2025). While using version 7 UUIDs has some nice advantages, there are also a few gotchas when it comes to Rails support.
Why UUIDv7
UUIDv4 is entirely random, so every insert lands in a random location within the primary key’s B-tree index. This leads to page splits, cache misses, and index bloat.
UUIDv7 places a 48-bit millisecond Unix timestamp at the front of the ID, making them time-ordered. New rows land at the end of the index, much like a sequential integer.
You still retain the benefits of UUIDs: IDs cannot be enumerated, and they can be generated anywhere without coordinating with the database.
The trade-off is that the ID reveals when the record was created. If that information is sensitive for a given table, UUIDv7 isn’t the right choice.
UUIDv7 and Rails
Let PostgreSQL generate the IDs
create_table :mostly_harmless_planets, id: :uuid, default: -> { "uuidv7()" } do |t|
t.timestamps
end
PostgreSQL 18 ships with a built-in uuidv7() function. Because the default lives in the database, every writer (Rails, raw SQL, bulk inserts) gets the same kind of ID.
If you’re on an older version of PostgreSQL, you could generate the IDs in Ruby, but personally, I’d be a bit wary of that setup.
Make UUID the default key type in generators
With this, new migrations start from id: :uuid instead of relying on someone remembering to add it.
# config/application.rb
config.generators { |g| g.orm :active_record, primary_key_type: :uuid }
What the generator can’t do is add the uuidv7() default. For that, you’ll need a lint rule, ideally backed up by a database constraint.
Enforce version 7 in the database
The default only applies when no ID is provided. Adding a check constraint ensures that no one accidentally inserts v4 IDs, which would disrupt the sort order and potentially cause timestamp extraction issues later.
create_table :mostly_harmless_planets, id: :uuid, default: -> { "uuidv7()" } do |t|
t.timestamps
t.check_constraint "uuid_extract_version(id) = 7", name: "mostly_harmless_planets_id_version_check"
end
This might seem pedantic, but once your code relies on IDs being in creation order, a stray v4 ID is a correctness bug, not a style problem. It’s really easy to end up with an import script, console session, or fixture that inserts the wrong type of UUIDs.
Lint migrations with custom RuboCop cops
The check constraint is excellent for preventing accidental inserts of other UUID versions, but every developer who touches the codebase will still have to remember to add it to every table.
To avoid human — or agentic — fallibility, I use two cops: one requires the uuidv7() default, and the other requires the version check constraint.
The first one finds create_table calls with id: :uuid and adds the default, or replaces one that isn’t uuidv7():
# lib/rubocop/cop/migration/uuid_v7_default.rb
module RuboCop
module Cop
module Migration
class UuidV7Default < Base
extend AutoCorrector
MSG = 'UUID primary keys must use `default: -> { "uuidv7()" }`.'
DEFAULT = '-> { "uuidv7()" }'
RESTRICT_ON_SEND = %i[create_table].freeze
def_node_matcher :uuid_id_pair, <<~PATTERN
(send nil? :create_table _ (hash <$(pair (sym :id) (sym :uuid)) ...>))
PATTERN
def on_send(node)
id_pair = uuid_id_pair(node) or return
default_pair = node.last_argument.pairs.find { |pair| pair.key.value == :default }
return if uuidv7_lambda?(default_pair&.value)
add_offense(default_pair || id_pair) do |corrector|
if default_pair
corrector.replace(default_pair.value, DEFAULT)
else
corrector.insert_after(id_pair, ", default: #{DEFAULT}")
end
end
end
private
def uuidv7_lambda?(node)
node&.block_type? && node.lambda? && node.body&.str_type? && node.body.value == "uuidv7()"
end
end
end
end
end
The second one ensures the check constraint is present inside the create_table block, adding it as the last line if necessary:
# lib/rubocop/cop/migration/uuid_v7_check_constraint.rb
module RuboCop
module Cop
module Migration
class UuidV7CheckConstraint < Base
extend AutoCorrector
MSG = "UUID tables must add `check_constraint \"uuid_extract_version(id) = 7\"`."
RESTRICT_ON_SEND = %i[create_table].freeze
def_node_matcher :uuid_table_name, <<~PATTERN
(send nil? :create_table ({sym str} $_) (hash <(pair (sym :id) (sym :uuid)) ...>))
PATTERN
def_node_search :version_check?, <<~PATTERN
(send _ :check_constraint (str "uuid_extract_version(id) = 7") ...)
PATTERN
def on_send(node)
table = uuid_table_name(node) or return
block = node.block_node
return if block && version_check?(block)
add_offense(node) do |corrector|
next unless block&.arguments&.one? # autocorrect needs the `|t|` argument
indent = " " * (node.source_range.column + 2)
check = %(#{block.first_argument.name}.check_constraint "uuid_extract_version(id) = 7", ) +
%(name: "#{table}_id_version_check")
last = block.body&.begin_type? ? block.body.children.last : block.body
corrector.insert_after(last || block.arguments, "\n#{indent}#{check}")
end
end
end
end
end
end
Configure RuboCop to require them and limit them to migrations:
# .rubocop.yml
require:
- ./lib/rubocop/cop/migration/uuid_v7_default
- ./lib/rubocop/cop/migration/uuid_v7_check_constraint
Migration/UuidV7Default:
Include: ["db/migrate/**/*.rb"]
Migration/UuidV7CheckConstraint:
Include: ["db/migrate/**/*.rb"]
Because Rails autoloads lib/, also tell Zeitwerk to skip the cops. Otherwise eager loading, in production for example, fails trying to load them as application code:
# config/application.rb
config.autoload_lib(ignore: %w[assets tasks rubocop])
Running rubocop -a on a freshly generated migration turns this:
create_table :mostly_harmless_planets, id: :uuid do |t|
t.timestamps
end
into this:
create_table :mostly_harmless_planets, id: :uuid, default: -> { "uuidv7()" } do |t|
t.timestamps
t.check_constraint "uuid_extract_version(id) = 7", name: "mostly_harmless_planets_id_version_check"
end
Both cops only look at create_table, so they won’t catch a primary key that’s changed later with change_column. That’s rare enough that I’m happy leaving it to review.
Fix fixtures
By default, Rails derives fixture IDs from the fixture label as UUIDv5, which the check constraint will reject.
# config/initializers/fixture_uuid_v7.rb
ActiveSupport.on_load(:active_record_fixture_set) do
singleton_class.prepend(Module.new do
def identify(label, column_type = :integer)
column_type == :uuid ? DeterministicUuidV7.generate(label) : super
end
end)
end
The replacement hashes the label into the v7 layout instead, so the same label always gives the same ID:
unix_ts_ms (48) | ver (4) | rand_a (12) | var (2) | rand_b (62)
The version nibble is set to 7 and the variant bits to 10; everything else comes from the hash:
# lib/deterministic_uuid_v7.rb
require "digest"
module DeterministicUuidV7
def self.generate(label)
bytes = Digest::SHA256.digest(label.to_s).bytes.first(16)
bytes[6] = (bytes[6] & 0x0f) | 0x70 # version 7
bytes[8] = (bytes[8] & 0x3f) | 0x80 # variant 10
hex = bytes.pack("C*").unpack1("H*")
[hex[0, 8], hex[8, 4], hex[12, 4], hex[16, 4], hex[20, 12]].join("-")
end
end
This means the “timestamp” in a fixture ID is arbitrary, so fixtures don’t sort in any meaningful order, just like with Rails’ default fixture IDs.
While this is likely out of spec for UUIDv7, it is structurally correct and shouldn’t matter for anything consuming the IDs in tests. I wouldn’t shoehorn deterministic UUIDs into anything outside of a test environment.
Backdate IDs when importing old data
When importing existing data, the imported rows should sort by when they were originally created, rather than when the import happened to run. To achieve this, you need to generate a v7 ID for a specific time:
module UuidV7ForTime
refine SecureRandom.singleton_class do
def uuid_v7_for_time(time)
ts = (time.to_r * 1000).to_i
high = (ts << 16) | (7 << 12) | SecureRandom.random_number(1 << 12)
low = (2 << 62) | SecureRandom.random_number(1 << 62)
hex = format("%016x%016x", high, low)
[hex[0, 8], hex[8, 4], hex[12, 4], hex[16, 4], hex[20, 12]].join("-")
end
end
end
Packaging it as a refinement on SecureRandom means it’s only available where you explicitly ask for it with using UuidV7ForTime, instead of leaking into the global namespace.
What time-ordered IDs buy you
MostlyHarmlessPlanet.order(id: :desc).limit(20) # newest first, no created_at index
MostlyHarmlessPlanet.where("id > ?", last_seen_id) # "everything since", keyset pagination
The primary key index doubles as a creation-order index, so you may be able to drop some created_at indexes entirely.
“Oldest wins” tie-breaks also become order(:id).first, which is deterministic.
Caveats
- Ordering is only millisecond-precise. Within a single millisecond, order is only guaranteed per backend process, not across connections.
- ID order is not commit order: a long-running transaction can commit an “older” ID later.
- Anything that sets created_at manually (tests, seeds, imports) breaks the ID-order assumption unless the ID is backdated as well.
- Tests need valid v7 IDs for “record not found” cases: use
SecureRandom.uuid_v7, notSecureRandom.uuid, or the check constraint will get in the way.