Haskell’s type system and UUID v7’s time-ordering complement each other: newtypes prevent ID mix-ups at compile time, and the embedded timestamp enables cursor pagination without a separate field. See UUID v7 in Haskell for the full guide.

Cabal dependencies

build-depends:
    base        >= 4.14
  , uuid        >= 1.3.16
  , uuid-types  >= 1.0.5
  , postgresql-simple >= 0.7
  , servant-server    >= 0.20

Generate UUID v7 in IO

module UUID where

import Data.UUID (UUID)
import qualified Data.UUID.V7 as UUIDv7
import Data.Time.Clock.POSIX (getPOSIXTime)

-- Generate UUID v7 — timestamp embedded, globally unique
generateId :: IO UUID
generateId = UUIDv7.nextRandom

-- Extract creation time from UUID v7
createdAtMs :: UUID -> Integer
createdAtMs uuid =
  let hex = filter (/= '-') (show uuid)
      prefix = take 12 hex
  in  read ("0x" ++ prefix) :: Integer

Newtype wrappers for domain safety

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

newtype OrderId    = OrderId    UUID deriving (Show, Eq, Ord)
newtype CustomerId = CustomerId UUID deriving (Show, Eq, Ord)

data Order = Order
  { orderId    :: OrderId
  , customerId :: CustomerId
  , total      :: Double
  , status     :: String
  }

createOrder :: CustomerId -> Double -> IO Order
createOrder cid total = do
  oid <- OrderId <$> generateId  -- UUID v7
  pure Order { orderId = oid, customerId = cid, total, status = "pending" }

PostgreSQL cursor pagination

import Database.PostgreSQL.Simple

listOrders :: Connection -> Maybe UUID -> Int -> IO [Order]
listOrders conn cursor limit =
  case cursor of
    Nothing ->
      query conn "SELECT id, customer_id, total FROM orders ORDER BY id LIMIT ?"
            (Only limit)
    Just c  ->
      query conn "SELECT id, customer_id, total FROM orders WHERE id > ? ORDER BY id LIMIT ?"
            (c, limit)

Further reading

External references

Frequently asked questions

How do I generate UUID v7 in Haskell?

Use the uuid Hackage package (version 1.3.16+). Import Data.UUID.V7 (nextRandom) and call nextRandom :: IO UUID. The function returns a standard Data.UUID.UUID value compatible with uuid-types and Persistent. See What is a UUID for the RFC 9562 specification.

How does UUID v7 work with Persistent in Haskell?

Declare your entity with Id UUID to use UUID as the primary key type. In your mkPersist models, use Id UUID default=gen_random_uuid() for PostgreSQL. For client-side generation, call Data.UUID.V7.nextRandom and pass the UUID to insertKey. See UUID in PostgreSQL.

How do UUID v7 newtypes improve type safety in Haskell?

Define newtype OrderId = OrderId UUID and newtype CustomerId = CustomerId UUID. The Haskell compiler rejects passing a CustomerId where an OrderId is expected — no runtime overhead, zero UUID mix-up bugs. UUID v7's time-ordered property is preserved inside the newtype wrapper.