Skip to content

DNS Configuration Example ​

Demonstrates DNS configuration in HTTPX: cache sizing, TTL tuning, negative caching, address-family preferences, and reusable Client integration.

Client-Wide DNS Configuration ​

DNS cache settings that apply across all requests are configured on Client.init:

zig
const std = @import("std");
const httpx = @import("httpx");

pub fn main() !void {
    var gpa: std.heap.DebugAllocator(.{}) = .init;
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();
    const io = std.Io.Threaded.global_single_threaded.io();

    // 1. Configure client with custom DNS cache settings
    var client = httpx.Client.init(allocator, io, .{
        .dnsCache = .{
            .enable = true,
            .ttlMs = 30_000,          // 30 seconds positive TTL
            .negativeTtlMs = 2_000,  // 2 seconds negative TTL (failed queries)
            .maxEntries = 512,        // Maximum LRU entries
        },
    });
    defer client.deinit();

    // 2. Dual-stack lookup using client defaults (.{})
    var addrs = try client.resolve("httpbun.com", .{ .port = 443 });
    defer addrs.deinit();

    std.debug.print("Resolved {d} address(es):\n", .{addrs.len()});
    for (addrs.items) |addr| {
        std.debug.print("  {f}:{d}\n", .{ addr, addr.port });
    }

    // 3. Per-lookup address family override
    var v4_only = try client.resolve("httpbun.com", .{
        .port = 443,
        .family = .ipv4,
        .useCache = true,
    });
    defer v4_only.deinit();

    std.debug.print("\nIPv4 addresses:\n", .{});
    for (v4_only.items) |addr| {
        std.debug.print("  {f}:{d}\n", .{ addr, addr.port });
    }
}

Configuration Reference ​

OptionTypeDefaultDescription
.dnsCache.enabledbooltrueEnables thread-safe in-memory resolution caching
.dnsCache.ttlMsi6460_000 (60s)Cache lifetime for successful resolutions
.dnsCache.negativeTtlMsi645_000 (5s)Cache lifetime for failed host resolutions
.dnsCache.maxEntriesu321024Maximum bounded entries before eviction

Per-Lookup Options (ResolveOptions) ​

OptionTypeDefaultDescription
.familyAddressFamilyPreference.any.any (dual-stack), .ipv4, or .ipv6
.useCachebooltrueWhether to consult/populate the client's cache
.timeoutMs?u64nullOptional lookup timeout override
.portu16443Port stamped onto every returned address

Passing .{} uses HTTPX defaults.

Released under the MIT License.