<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Charles Fonseca on Medium]]></title>
        <description><![CDATA[Stories by Charles Fonseca on Medium]]></description>
        <link>https://medium.com/@barddoo?source=rss-34280943c23e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a9EbDzF6sbQQqMO_1vYpVg.jpeg</url>
            <title>Stories by Charles Fonseca on Medium</title>
            <link>https://medium.com/@barddoo?source=rss-34280943c23e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:11:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@barddoo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Redis Clone in Zig-Part 2]]></title>
            <link>https://barddoo.medium.com/building-a-redis-clone-in-zig-part-2-2285354557b2?source=rss-34280943c23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2285354557b2</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Charles Fonseca]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 02:15:33 GMT</pubDate>
            <atom:updated>2025-10-28T02:15:33.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Customizing the Hash Table for Caching Workload</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hZby5Lr5tzCL1iiu.jpeg" /></figure><p>In the previous article, we covered the basics of building a Redis clone in Zig, focusing on the data structures and the core functionality. In this article, we will dive deeper into optimizing our in-memory store by implementing string interning and customizing our hash map for better performance.</p><h3>Hash Table Context</h3><p>If you noticed, this is how the OptimizedHashMap was defined in the previous article:</p><pre>const OptimizedHashMap = std.ArrayHashMapUnmanaged([]const u8, ZedisObject, StringContext, true);</pre><p>Let’s focus on the StringContext part. The default context for HashMaps uses the standard library&#39;s std.hash.Wyhash, which is a great general-purpose hash function, and for equality, it uses std.mem.eql(u8), which is a byte-wise equality check. We can customize this by providing our context struct.</p><h3>Benchmarking</h3><p>During development, I found that the default hash function and equality check were not optimal for our use case. Specifically, we want to optimize for short strings, as Redis often deals with short keys and values. I assumed SIMD (Single Instruction, Multiple Data) was the best way to speed up equality checks, and the answer was a huge <strong>it depends</strong>.</p><h3>Equality Benchmark</h3><p>The obvious choice for equality is to use SIMD instructions for faster comparisons. For which, again, Karl Seguin has a great article on the topic: <a href="https://www.openmymind.net/Using-SIMD-to-Tell-if-the-High-Bit-is-Set/">Using SIMD to Tell if the High Bit is Set</a>. We won’t be checking the high bit, but the same principles apply.</p><p>Our baseline will be the standard library’s std.mem.eql(u8) function. During the benchmark, I found that it&#39;s pretty challenging to beat the standard library; my original SIMD implementation was half the speed of std.mem.eql(u8) for almost all string lengths.</p><p>You can see the benchmark code and results in this <a href="https://gist.github.com/barddoo/e37e62adc7a02fec44e1535767bd1ea8">GitHub Gist</a>. Long story short, for strings shorter than 45 bytes, std.mem.eql(u8) is the fastest option. For strings between 45 and 128 bytes, a 16-byte SIMD using XOR is the fastest; it reaches an average of 850 million operations per second on my M4 MacBook Pro.</p><p>Here’s the final implementation of the SIMD equality function:</p><pre>pub fn simdStringEql(a: []const u8, b: []const u8) bool {<br>    // Fast path<br>    if (a.len != b.len) return false;<br>    if (a.len == 0) return true;<br><br>    // Check for pointer equality first, this is a fast path for interned strings<br>    if (a.ptr == b.ptr) return true;<br><br>    // For strings &lt; 45 bytes, std.mem.eql is faster due to:<br>    // - Highly optimized LLVM intrinsics<br>    // - Lower overhead for small comparisons<br>    // - Better branch prediction<br>    // Most Redis keys fall into this category<br>    if (a.len &lt; 45) {<br>        return std.mem.eql(u8, a, b);<br>    }<br><br>    // For longer strings (≥45 bytes), use explicit SIMD vectorization<br>    // Fixed 16-byte vectors for consistent performance across platforms<br>    const vec_len = 16;<br>    const Vec = @Vector(vec_len, u8);<br>    var i: usize = 0;<br><br>    // Process 16-byte chunks with SIMD using XOR technique<br>    // XOR is slightly more efficient than equality comparison + reduce<br>    while (i + vec_len &lt;= a.len) : (i += vec_len) {<br>        const va: Vec = a[i..][0..vec_len].*;<br>        const vb: Vec = b[i..][0..vec_len].*;<br>        const xor_result = va ^ vb;<br><br>        // If XOR result is all zeros, the vectors are equal<br>        // Check if any byte is non-zero (which means difference)<br>        if (@reduce(.Or, xor_result != @as(Vec, @splat(0)))) {<br>            return false;<br>        }<br>    }<br><br>    // Handle remaining bytes efficiently with std.mem.eql<br>    // This is faster than a scalar loop for the tail<br>    return std.mem.eql(u8, a[i..], b[i..]);<br>}</pre><h3>Hash Function Benchmark</h3><p>I also wanted to benchmark different hash functions to see which one performs best for our use case. The standard library provides several hash functions, including Wyhash, CityHash64, Murmur3, and others. I added a few more to the benchmark, including Murmur2, XxHash (32 and 64), Adler32, and Blake3 (cryptographic). I implemented a simple FNV-1a hash function for comparison as well. You can see the benchmark code and results in this <a href="https://gist.github.com/barddoo/0a245d52a4a67bf937bb56e41bf77427">GitHub Gist</a>. Long story short, CityHash64 outperforms Wyhash slightly, reaching an average of 490 million operations per second versus Wyhash’s 460 million on my laptop.</p><h3>Intern Strings</h3><p>The idea is to store only one copy of each unique string value, and all references to that string point to the same memory location. This is a common technique used in many programming languages and systems to optimize memory usage and speed up string comparisons. That’s why in the equality function above, we first check if the pointers are the same, if (a.ptr == b.ptr) return true. If they are, we can immediately return true without further comparison; we get O(1) complexity for almost all string comparisons.</p><pre>pub const Store = struct {<br>    base_allocator: std.mem.Allocator,<br>    allocator: std.mem.Allocator,<br>    map: OptimizedHashMap,<br><br>    ...<br>    <br>    // Map of interned strings<br>    interned_strings: std.StringHashMapUnmanaged([]const u8),<br><br>    fn internString(self: *Store, str: []const u8) ![]const u8 {<br>        assert(str.len &gt; 0);<br>        const gop = try self.interned_strings.getOrPut(self.base_allocator, str);<br>        if (!gop.found_existing) {<br>            const owned_str = try self.dupeString(str);<br>            gop.key_ptr.* = owned_str;<br>            gop.value_ptr.* = owned_str;<br>        }<br>        return gop.value_ptr.*;<br>    }<br><br>    pub fn set(self: *Store, key: []const u8, value: []const u8) !void {<br>        assert(key.len &gt; 0);<br>        // Check if we need to resize before adding new entries<br>        try self.maybeResize();<br><br>        const interned_key = try self.internString(key);<br>        const gop = try self.map.getOrPut(self.base_allocator, interned_key);<br><br>        // Free old value if key existed<br>        if (gop.found_existing) {<br>            switch (gop.value_ptr.value) {<br>                .string =&gt; |str| {<br>                    if (str.len &gt; 0) self.smartFree(str);<br>                },<br>                .int =&gt; {},<br>                .short_string =&gt; {},<br>            }<br>        }<br>        // Key is already interned, no need to duplicate again<br>        gop.key_ptr.* = interned_key;<br><br>        // Build the new object with allocated values<br>        var new_object = object;<br>        switch (object.value) {<br>            .string =&gt; |str| {<br>                const value_copy = try self.dupeString(str);<br>                new_object.value = .{ .string = value_copy };<br>            },<br>            .int =&gt; {}, // No allocation needed<br>            .short_string =&gt; {}, // No allocation needed - stored inline<br>        }<br><br>        // Update the entry<br>        gop.value_ptr.* = new_object;<br>    }</pre><p>By doing this, we ensure that all identical strings share the same memory, which saves space and speeds up comparisons. To summarize, the struct now includes a map to keep track of all unique interned strings. We added the variant to the union in the Store to keep small strings inline, and we updated the hash map context to use our optimized hash function and equality check. This is a great foundation for building a high-performance in-memory cache.</p><h3>Learn More</h3><ul><li><a href="https://github.com/barddoo/zedis">Zedis GitHub Repository</a></li><li><a href="https://www.openmymind.net/Using-SIMD-to-Tell-if-the-High-Bit-is-Set/">Using SIMD to Tell if the High Bit is Set</a></li></ul><p><em>Originally published at </em><a href="https://charlesfonseca.substack.com/p/building-a-redis-clone-in-zigpart-c84"><em>https://charlesfonseca.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2285354557b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Redis Clone in Zig — Part 1]]></title>
            <link>https://barddoo.medium.com/building-a-redis-clone-in-zig-part-1-bcbd4e0e699a?source=rss-34280943c23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcbd4e0e699a</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Charles Fonseca]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 22:39:01 GMT</pubDate>
            <atom:updated>2025-10-13T12:45:47.326Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Redis Clone in Zig — Part 1</h3><p>I’ve been writing web applications for years, mostly high-level stuff with frameworks that abstract away the messy details. You know the type: ORMs, HTTP servers, JSON serialization-all the conveniences of modern backend development. But I’ve always been curious about what happens beneath those abstractions. How does a database actually work? What does efficient memory management look like? So a few months ago, I decided to learn Zig by rebuilding Redis from scratch.</p><h3>Why Redis?</h3><p>Redis is deceptively simple from the outside: it’s an in-memory key-value store with a straightforward text protocol. But underneath, it’s a masterclass in systems programming-memory management, data structures, network I/O, and concurrency all wrapped up in one project. Perfect for someone trying to bridge the gap between web development and systems programming. Also, almost every company I’ve worked for used it in some way.</p><p>The whole promise of Zig is explicit control-memory, error handling, and resources. There’s no garbage collector to save you, no exceptions to bubble up unhandled. If you want to allocate memory, you have to say exactly how, and more importantly, you have to free it yourself. This is precisely what Redis needs: tight control over memory for performance and predictability.</p><p>Redis uses RESP (REdis Serialization Protocol), a simple text-based format. A command like SET mykey myvalue arrives as:</p><pre>*3\r\n<br>$3\r\n<br>SET\r\n<br>$5\r\n<br>mykey\r\n<br>$7\r\n<br>myvalue\r\n</pre><p>The *3 means &quot;array of 3 elements.&quot; Each $N is a bulk string of N bytes. It&#39;s verbose but easy to parse.</p><p>Here’s a simplified parser:</p><pre>fn parseCommand(reader: anytype) ![][]const u8 {<br>    var args = std.ArrayList([]const u8).init(allocator);<br><br>    // Read first byte to determine type<br>    const type_byte = try reader.readByte();<br>    if (type_byte != ‘*’) return error.InvalidProtocol;<br><br>    // Read number of arguments<br>    const count = try readInteger(reader);<br><br>    for (0..count) |_| {<br>        // Each arg starts with $<br>        const dollar = try reader.readByte();<br>        if (dollar != ‘$’) return error.InvalidProtocol;<br><br>        // Length of this arg<br>        const len = try readInteger(reader);<br><br>        // Read the actual bytes<br>        const arg = try allocator.alloc(u8, len);<br>        _ = try reader.readAll(arg);<br>        try args.append(arg);<br><br>        // Consume \r\n<br>        _ = try reader.readByte();<br>        _ = try reader.readByte();<br>    }<br>    return args.toOwnedSlice();<br>}</pre><h3>Memory Management: The Hard Part</h3><p>Coming from garbage-collected languages, the hardest adjustment was thinking about ownership. In Zig, when you allocate memory, you own it. You’re responsible for freeing it. There’s no runtime to clean up after you.</p><p>Here’s a simple key-value store:</p><pre>const Store = struct {<br>    map: std.StringHashMap([]const u8),<br>    allocator: std.mem.Allocator,<br><br>    pub fn init(allocator: std.mem.Allocator) Store {<br>        return .{<br>            .map = std.StringHashMap([]const u8).init(allocator),<br>            .allocator = allocator,<br>        };<br>    }<br><br>    pub fn set(self: *Store, key: []const u8, value: []const u8) !void {<br>        // Duplicate the key and value so we own them<br>        const owned_key = try self.allocator.dupe(u8, key);<br>        const owned_value = try self.allocator.dupe(u8, value);<br><br>        // If key exists, free old value<br>        if (self.map.get(key)) |old_value| {<br>            self.allocator.free(old_value);<br>        }<br><br>        try self.map.put(owned_key, owned_value);<br>    }<br><br>    pub fn deinit(self: *Store) void {<br>        var iter = self.map.iterator();<br>        while (iter.next()) |entry| {<br>            self.allocator.free(entry.key_ptr.*);<br>            self.allocator.free(entry.value_ptr.*);<br>        }<br>        self.map.deinit();<br>    }<br>};</pre><p>This is a great start, but there are some improvements to be made. Most of the keys and values in a typical caching system are small, so SSO (Small String Optimization) can help reduce allocations.</p><pre>pub const ShortString = struct {<br>    data: [23]u8, // Inline storage<br>    len: u8, // Actual length<br><br>    pub fn fromSlice(str: []const u8) ShortString {<br>        var ss: ShortString = .{ .data = undefined, .len = @intCast(str.len) };<br>        @memcpy(ss.data[0..str.len], str);<br>        // Zero remaining bytes for consistent hashing<br>        @memset(ss.data[str.len..], 0);<br>        return ss;<br>    }<br><br>    pub fn asSlice(self: *const ShortString) []const u8 {<br>        return self.data[0..self.len];<br>    }<br>};</pre><p>This ShortString struct can hold strings up to 23 bytes inline, avoiding heap allocations for small keys/values. Usually, a CPU cache line is 64 bytes, allowing room for multiple instances to fit in a single cache line. I still need to evaluate the performance difference between 23 bytes and 15 bytes, but this is a good starting point.</p><h3>Hash Tables</h3><p>Zig’s standard library provides a StringHashMap, which is a good starting point. However, we need to ensure that our keys and values are properly managed in terms of memory ownership. For that, we can use StringHashMapUnmanaged, which allows us to define custom allocators and manage memory more explicitly.</p><p>To go further, we can create an optimized hash map tailored for our use case. We must be able to store integers, short strings, larger strings, and later, more complex types like lists and hashes. Let’s take a look at how we can define this:</p><pre>pub const ValueType = enum(u8) {<br>    string = 0,<br>    int,<br>    list,<br>    short_string,<br>};<br><br>pub const ZedisValue = union(ValueType) {<br>    string: []const u8,<br>    int: i64,<br>    list: ZedisList,<br>    // Showed before<br>    short_string: ShortString,<br>};<br><br>pub const ZedisObject = struct {<br>    value: ZedisValue,<br>    expiration_time: i64,<br>    // Plan to add more fields in the future<br>};<br><br>const OptimizedHashMap = std.ArrayHashMapUnmanaged([]const u8, ZedisObject, StringContext, true);</pre><p>This will improve performance by reducing allocations for small strings and integers, which are common in Redis workloads. Additionally, we can process KEYS and SCAN commands more efficiently by iterating over the hash map directly, since the underlying structure is an array.</p><h3>Memory Pool</h3><p>Karl Seguin has already written a <a href="https://www.openmymind.net/Zig-MemoryPool-Allocator/">fantastic article about it</a>; for a more in-depth understanding, see that. In summary, it keeps track of previously destroyed objects so that the same address in memory can be used again, making it an excellent choice for objects that are allocated and released frequently.</p><p>It performs especially well with caching system workloads like rate limiters, session stores, user metrics, etc. With that optimization, the SET command is O(1) rather than O(n) in terms of string allocation; just beware that if the memory pool doesn’t have an address available, it will call the syscall alloc.</p><p><a href="https://github.com/barddoo/zedis">Zedis</a> on GitHub.</p><p><em>Originally published at </em><a href="https://charlesfonseca.substack.com/">https://charlesfonseca.substack.com</a> <em>on October 8, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcbd4e0e699a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>