Zig’s philosophy of explicit allocation, comptime evaluation, and zero hidden control flow makes UUID generation a natural fit — there is no magic, just byte manipulation and a CSPRNG call. The implementation below is dependency-free and covers UUID v4 and v7 for use in HTTP servers, CLI tools, and SQLite-backed applications. For a fuller picture of the UUID v7 spec, see UUID versions.

UUID v4 Implementation

const std = @import("std");

/// A UUID is 16 bytes with version and variant bits set per RFC 9562.
pub const Uuid = [16]u8;

/// Generate a UUID v4 — 122 bits of cryptographic randomness.
pub fn uuidV4() Uuid {
    var bytes: Uuid = undefined;
    std.crypto.random.bytes(&bytes);

    // Set version: bits 76-79 of byte 6 = 0100 (version 4)
    bytes[6] = (bytes[6] & 0x0F) | 0x40;

    // Set variant: bits 6-7 of byte 8 = 10 (RFC 4122 / RFC 9562)
    bytes[8] = (bytes[8] & 0x3F) | 0x80;

    return bytes;
}

/// Format a UUID as a 36-character hyphenated string.
pub fn uuidToString(uuid: Uuid, buf: *[36]u8) void {
    const hex = "0123456789abcdef";
    const groups = [_]struct { start: u8, len: u8 }{
        .{ .start = 0, .len = 4 },
        .{ .start = 4, .len = 2 },
        .{ .start = 6, .len = 2 },
        .{ .start = 8, .len = 2 },
        .{ .start = 10, .len = 6 },
    };

    var pos: usize = 0;
    for (groups, 0..) |g, i| {
        if (i != 0) {
            buf[pos] = '-';
            pos += 1;
        }
        for (0..g.len) |j| {
            const byte = uuid[g.start + j];
            buf[pos]     = hex[byte >> 4];
            buf[pos + 1] = hex[byte & 0x0F];
            pos += 2;
        }
    }
}

pub fn main() !void {
    const id = uuidV4();
    var buf: [36]u8 = undefined;
    uuidToString(id, &buf);
    std.debug.print("{s}\n", .{buf});
    // 550e8400-e29b-41d4-a716-446655440000
}

UUID v7 Implementation

/// Generate a UUID v7 — time-ordered, 48-bit ms timestamp + 74 random bits.
pub fn uuidV7() Uuid {
    var bytes: Uuid = undefined;

    // 48-bit Unix millisecond timestamp in big-endian
    const ms: u64 = @intCast(std.time.milliTimestamp());
    bytes[0] = @intCast((ms >> 40) & 0xFF);
    bytes[1] = @intCast((ms >> 32) & 0xFF);
    bytes[2] = @intCast((ms >> 24) & 0xFF);
    bytes[3] = @intCast((ms >> 16) & 0xFF);
    bytes[4] = @intCast((ms >> 8)  & 0xFF);
    bytes[5] = @intCast(ms         & 0xFF);

    // Fill bytes 6-15 with random data
    std.crypto.random.bytes(bytes[6..]);

    // Set version nibble in byte 6: 0111 (version 7)
    bytes[6] = (bytes[6] & 0x0F) | 0x70;

    // Set variant bits in byte 8: 10xxxxxx
    bytes[8] = (bytes[8] & 0x3F) | 0x80;

    return bytes;
}

Parsing and Validation

pub const UuidParseError = error{
    InvalidLength,
    InvalidHyphen,
    InvalidCharacter,
};

/// Parse a hyphenated UUID string into 16 bytes.
pub fn parseUuid(s: []const u8) UuidParseError!Uuid {
    if (s.len != 36) return error.InvalidLength;

    const hyphen_positions = [_]usize{ 8, 13, 18, 23 };
    for (hyphen_positions) |pos| {
        if (s[pos] != '-') return error.InvalidHyphen;
    }

    var bytes: Uuid = undefined;
    var src: usize = 0;
    var dst: usize = 0;

    while (dst < 16) : (dst += 1) {
        if (s[src] == '-') src += 1;
        const hi = hexVal(s[src])     catch return error.InvalidCharacter;
        const lo = hexVal(s[src + 1]) catch return error.InvalidCharacter;
        bytes[dst] = (hi << 4) | lo;
        src += 2;
    }

    return bytes;
}

fn hexVal(c: u8) !u8 {
    return switch (c) {
        '0'...'9' => c - '0',
        'a'...'f' => c - 'a' + 10,
        'A'...'F' => c - 'A' + 10,
        else      => error.InvalidCharacter,
    };
}

/// Extract the Unix millisecond timestamp from a UUID v7.
pub fn uuidV7Timestamp(uuid: Uuid) u64 {
    return (@as(u64, uuid[0]) << 40) |
           (@as(u64, uuid[1]) << 32) |
           (@as(u64, uuid[2]) << 24) |
           (@as(u64, uuid[3]) << 16) |
           (@as(u64, uuid[4]) << 8)  |
           @as(u64, uuid[5]);
}

Comptime UUID Constants

Zig’s comptime lets you validate UUID string constants at compile time — a bad UUID is a compile error, not a runtime panic:

/// Parse a UUID at comptime — compile error if the string is invalid.
pub fn uuidLiteral(comptime s: []const u8) Uuid {
    return parseUuid(s) catch @compileError("Invalid UUID literal: " ++ s);
}

// Valid — compiles fine
const nil_uuid = uuidLiteral("00000000-0000-0000-0000-000000000000");

// Invalid — compile error: "Invalid UUID literal: not-a-uuid"
// const bad = uuidLiteral("not-a-uuid");

This pattern is ideal for namespace UUIDs (see UUID namespaces) used to derive deterministic v5 UUIDs.

SQLite Integration with zig-sqlite

zig-sqlite wraps the SQLite C library for Zig. Store UUID v7 as TEXT:

const sqlite = @import("sqlite");

const db = try sqlite.Db.init(.{
    .mode = sqlite.Db.Mode{ .File = "app.db" },
    .open_flags = .{ .write = true, .create = true },
});

// Create table
try db.exec(
    \\CREATE TABLE IF NOT EXISTS tasks (
    \\  id        TEXT NOT NULL PRIMARY KEY,
    \\  title     TEXT NOT NULL,
    \\  completed INTEGER NOT NULL DEFAULT 0
    \\)
, .{}, .{});

// Insert with UUID v7 primary key
const id = uuidV7();
var id_str: [36]u8 = undefined;
uuidToString(id, &id_str);

try db.exec(
    "INSERT INTO tasks (id, title) VALUES (?, ?)",
    .{},
    .{ id_str, "Buy groceries" },
);

// Query — ORDER BY id = chronological (UUID v7 lexicographic sort)
const Task = struct { id: []const u8, title: []const u8 };
var stmt = try db.prepare("SELECT id, title FROM tasks ORDER BY id");
defer stmt.deinit();

var iter = try stmt.iterator(Task, .{});
while (try iter.nextAlloc(allocator, .{})) |task| {
    defer allocator.free(task.id);
    defer allocator.free(task.title);
    std.debug.print("{s}: {s}\n", .{ task.id, task.title });
}

HTTP Server with std.http

Zig’s standard library includes an HTTP server (1.0+). Use UUID v7 as request IDs:

const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    const address = try std.net.Address.parseIp("127.0.0.1", 8080);
    var server = try address.listen(.{ .reuse_address = true });
    defer server.deinit();

    std.debug.print("Listening on http://127.0.0.1:8080\n", .{});

    while (true) {
        var connection = try server.accept();
        defer connection.stream.close();

        var read_buffer: [8192]u8 = undefined;
        var http_server = std.http.Server.init(connection, &read_buffer);
        var request = try http_server.receiveHead();

        // UUID v7 request ID for structured logging
        const request_id = uuidV7();
        var request_id_str: [36]u8 = undefined;
        uuidToString(request_id, &request_id_str);

        std.log.info("request_id={s} method={s} path={s}", .{
            request_id_str,
            @tagName(request.head.method),
            request.head.target,
        });

        try request.respond("Hello, Zig!\n", .{
            .extra_headers = &.{
                .{ .name = "X-Request-Id", .value = &request_id_str },
            },
        });

        _ = allocator; // suppress unused warning
    }
}

UUID v5 — Deterministic Namespaced UUIDs

UUID v5 produces a deterministic UUID from a namespace UUID and a name string using SHA-1. Useful for stable identifiers derived from content:

const std = @import("std");

/// DNS namespace UUID per RFC 9562 Appendix C.
pub const dns_namespace = uuidLiteral("6ba7b810-9dad-11d1-80b4-00c04fd430c8");

/// Generate a UUID v5 from a namespace and name.
pub fn uuidV5(namespace: Uuid, name: []const u8) Uuid {
    var hasher = std.crypto.hash.Sha1.init(.{});
    hasher.update(&namespace);
    hasher.update(name);
    var hash: [20]u8 = undefined;
    hasher.final(&hash);

    var result: Uuid = undefined;
    @memcpy(&result, hash[0..16]);

    // Set version: 0101 (version 5)
    result[6] = (result[6] & 0x0F) | 0x50;

    // Set variant: 10xxxxxx
    result[8] = (result[8] & 0x3F) | 0x80;

    return result;
}

// Deterministic — always the same UUID for the same input
const user_uuid = uuidV5(dns_namespace, "alice@example.com");

Choosing v4 vs v7 in Zig

Use caseVersion
SQLite primary keyv7 — ORDER BY id = chronological
HTTP request correlation IDv7 — timestamp embeds request time
Content-addressed identifierv5 — deterministic from namespace + name
External API tokenv4 — creation time not disclosed
Fuzz test seed identifierv4 — random, no time correlation

Further Reading

External References

Frequently asked questions

Is there a UUID package for Zig?

There is no official UUID package in the Zig standard library. UUID v4 and v7 are simple enough to implement directly with std.crypto.random — see the implementation below. The community package uuid-zig provides a pre-built implementation if you prefer a dependency.

How do I generate a UUID v4 in Zig?

Fill 16 bytes with std.crypto.random.bytes(), then set the version nibble (bits 76-79 of byte 6) to 0x40 and the variant bits (bits 6-7 of byte 8) to 0x80. The resulting 16 bytes conform to RFC 9562 UUID v4. See the uuidV4() function in this guide for the exact bit manipulation.

How do I generate a UUID v7 in Zig?

Read the current timestamp with std.time.milliTimestamp(), place the 48-bit millisecond value in the first 6 bytes, set the version nibble to 0x70, fill the remaining 74 bits with std.crypto.random, and set the variant bits to 0x80. UUID v7 strings sort lexicographically in chronological order, making them ideal for SQLite primary keys in Zig applications.

Does Zig's std.crypto.random provide cryptographic-quality randomness?

Yes. std.crypto.random uses the OS CSPRNG — getrandom() on Linux, arc4random_buf() on macOS/BSD, and BCryptGenRandom on Windows. It is safe for UUID v4 generation. The Zig standard library documentation describes the implementation for each platform.

Should I use TEXT or BLOB to store UUIDs in SQLite from Zig?

Use TEXT for UUID v7 — SQLite sorts TEXT lexicographically and UUID v7 lexicographic order equals chronological order. Use BLOB (16 bytes) when storage size is critical; the zig-sqlite binding can bind raw byte slices directly. See UUID in databases for a comparison of storage strategies.