Crystal compiles to native binaries with performance close to C. UUID v7 generation is a pure function call — no global state, no network coordination. The time-ordered prefix improves B-tree index locality in both SQLite and PostgreSQL. See UUID v7 in Crystal for a feature overview.
shard.yml setup
name: my_app
version: 0.1.0
dependencies:
uuid6:
github: crystal-community/uuid6
version: ~> 0.1
db:
github: crystal-lang/crystal-db
version: ~> 0.13
pg:
github: will/crystal-pg
version: ~> 0.28
sqlite3:
github: crystal-lang/crystal-sqlite3
version: ~> 0.20
kemal:
github: kemalcr/kemal
version: ~> 1.4
Generate and inspect UUID v7
require "uuid6"
# Generate UUID v7
id = UUID.v7
puts id.to_s # => "019277ab-3f42-7c1a-8b3d-6e2f1a4c8d0e"
# Extract creation timestamp
def created_at(uuid : UUID) : Time
hex = uuid.to_s.gsub("-", "")[0..11]
ms = hex.to_i64(16)
Time.unix_ms(ms)
end
puts created_at(id).to_s # ISO 8601 creation time
PostgreSQL table and insert
-- PostgreSQL schema
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id UUID NOT NULL,
total NUMERIC(10,2) NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
);
require "pg"
require "uuid6"
DB_URL = ENV["DATABASE_URL"]
def create_order(customer_id : String, total : Float64) : String
id = UUID.v7.to_s
DB.open(DB_URL) do |db|
db.exec(
"INSERT INTO orders (id, customer_id, total) VALUES ($1, $2, $3)",
id, customer_id, total
)
end
id
end
Cursor pagination
def list_orders(cursor : String? = nil, limit : Int32 = 20) : NamedTuple
DB.open(DB_URL) do |db|
rows =
if cursor
db.query_all(
"SELECT id, total, status FROM orders WHERE id > $1 ORDER BY id LIMIT $2",
cursor, limit,
as: {String, Float64, String}
)
else
db.query_all(
"SELECT id, total, status FROM orders ORDER BY id LIMIT $1",
limit,
as: {String, Float64, String}
)
end
items = rows.map { |id, total, status| {id: id, total: total, status: status} }
next_cursor = items.size == limit ? items.last[:id] : nil
{items: items, next_cursor: next_cursor}
end
end
Kemal REST API
require "kemal"
require "uuid6"
require "json"
post "/orders" do |env|
body = env.params.json
id = UUID.v7.to_s
create_order(body["customer_id"].as_s, body["total"].as_f)
env.response.content_type = "application/json"
env.response.status_code = 201
{id: id, status: "pending"}.to_json
end
get "/orders" do |env|
cursor = env.params.query["cursor"]?
limit = (env.params.query["limit"]? || "20").to_i32
result = list_orders(cursor, limit)
env.response.content_type = "application/json"
result.to_json
end
Kemal.run
SQLite alternative
require "sqlite3"
require "uuid6"
SQLITE_PATH = "orders.db"
DB.open("sqlite3://#{SQLITE_PATH}") do |db|
db.exec "CREATE TABLE IF NOT EXISTS orders (
id TEXT PRIMARY KEY,
customer_id TEXT NOT NULL,
total REAL NOT NULL
)"
end
def create_sqlite_order(customer_id : String, total : Float64)
id = UUID.v7.to_s
DB.open("sqlite3://#{SQLITE_PATH}") do |db|
db.exec "INSERT INTO orders VALUES (?, ?, ?)", id, customer_id, total
end
id
end
Further reading
External references
Frequently asked questions
How do I install the crystal-uuid6 shard?
Add uuid6: { github: crystal-community/uuid6, version: "~> 0.1" } to your shard.yml dependencies and run shards install. Then require "uuid6" in your Crystal source. Call UUID.v7 to generate a UUID v7 value and .to_s for the hyphenated string. See UUID v7 in Crystal.
Can I store UUID v7 in PostgreSQL from Crystal?
Yes. Use the pg shard (crystal-lang/crystal-pg). Declare your column as UUID type in PostgreSQL. Pass the UUID v7 string to query parameters: db.exec("INSERT INTO orders (id) VALUES ($1)", uuid.to_s). PostgreSQL validates UUID format and stores it as 16 bytes internally. See UUID in PostgreSQL.
How do I extract the creation time from a UUID v7 in Crystal?
Parse the first 12 hex characters of the UUID v7 string (removing hyphens) as a base-16 integer — this is the Unix millisecond timestamp. In Crystal: ms = uuid.to_s.gsub("-", "")[0..11].to_i64(16) followed by Time.unix_ms(ms). See What is a UUID for the byte layout.