Crystal compiles to native binaries with Ruby-like syntax and zero-cost abstractions. UUID v7 fits Crystal’s performance-first philosophy — client-side generation with no coordination, time-ordered for B-tree efficiency. See UUID in Crystal for the full guide.
shard.yml dependency
dependencies:
uuid6:
github: crystal-community/uuid6
version: ~> 0.1
db:
github: crystal-lang/crystal-db
version: ~> 0.13
sqlite3:
github: crystal-lang/crystal-sqlite3
version: ~> 0.20
Generate UUID v7
require "uuid6"
id = UUID.v7
puts id.to_s # => "019277ab-3f42-7c1a-8b3d-6e2f1a4c8d0e"
# Extract creation timestamp from UUID v7
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) # => creation time
HTTP API handler with Kemal
require "kemal"
require "uuid6"
require "db"
require "sqlite3"
DB_PATH = "orders.db"
DB.open("sqlite3://#{DB_PATH}") do |db|
db.exec "CREATE TABLE IF NOT EXISTS orders (
id TEXT PRIMARY KEY,
customer_id TEXT NOT NULL,
total REAL NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
)"
end
post "/orders" do |env|
body = env.params.json
id = UUID.v7.to_s
cust_id = body["customer_id"].as_s
total = body["total"].as_f
DB.open("sqlite3://#{DB_PATH}") do |db|
db.exec "INSERT INTO orders (id, customer_id, total) VALUES (?, ?, ?)",
id, cust_id, total
end
env.response.content_type = "application/json"
{ id: id, status: "pending" }.to_json
end
get "/orders" do |env|
cursor = env.params.query["cursor"]?
limit = (env.params.query["limit"]? || "20").to_i
rows = DB.open("sqlite3://#{DB_PATH}") do |db|
if cursor
db.query_all "SELECT id, total, status FROM orders WHERE id > ? ORDER BY id LIMIT ?",
cursor, limit, as: { String, Float64, String }
else
db.query_all "SELECT id, total, status FROM orders ORDER BY id LIMIT ?",
limit, as: { String, Float64, String }
end
end
items = rows.map { |id, total, status| { id: id, total: total, status: status } }
next_cursor = items.size == limit ? items.last[:id] : nil
env.response.content_type = "application/json"
{ items: items, next_cursor: next_cursor }.to_json
end
Kemal.run
Further reading
External references
Frequently asked questions
How do I generate UUID v7 in Crystal?
Use the crystal-uuid6 shard. Add uuid6 (~> 0.1) to your shard.yml and call UUID.v7. The shard returns a UUID struct with .to_s producing the standard hyphenated string. See UUID in Crystal for the full guide.
Can I use UUID v7 as a primary key in Crystal with SQLite?
Yes. Store UUID v7 as TEXT in SQLite. Crystal's db shard and crystal-sqlite3 driver handle string parameters directly. UUID v7's lexicographic order enables WHERE id > cursor ORDER BY id cursor pagination without a separate timestamp column. See UUID in SQLite.
What is the crystal-uuid6 shard?
crystal-uuid6 is a Crystal shard implementing UUID v6 and UUID v7 per RFC 9562. It extends Crystal's standard UUID type with UUID.v6 and UUID.v7 class methods. See What is a UUID for the specification background.