<?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 Ali Hussein Safar on Medium]]></title>
        <description><![CDATA[Stories by Ali Hussein Safar on Medium]]></description>
        <link>https://medium.com/@ahsifer?source=rss-67610f37affb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JbeW8UP8zFjOV0FvZRojqw.jpeg</url>
            <title>Stories by Ali Hussein Safar on Medium</title>
            <link>https://medium.com/@ahsifer?source=rss-67610f37affb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:52:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahsifer/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 1M/sec Log Ingestion Pipeline with Grafana Loki: Design, Bottlenecks, and Optimization]]></title>
            <link>https://medium.com/@ahsifer/building-a-1m-sec-log-ingestion-pipeline-with-grafana-loki-design-bottlenecks-and-optimization-60a1551ccc1f?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/60a1551ccc1f</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[grafana-loki]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 12:51:42 GMT</pubDate>
            <atom:updated>2026-03-21T23:47:14.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a 1M/sec Log Ingestion Pipeline with Grafana Loki: Design, Bottlenecks, and Optimizations</h3><p>At scale, log ingestion becomes a critical concern. Every technical team relies heavily on log messages to troubleshoot, investigate, and understand their service behaviour, even when systems appear stable.</p><p>Despite the volume of logs, selecting the right log aggregation system is critical, as it must guarantee reliable data delivery while maintaining predictable behavior and resource utilization under high load. Based on the log format and the analysis of query patterns, the selected system needs to provide the following:</p><p><strong>1. Support schema-less ingestion</strong></p><p>Each service produces logs with a different format, with 80+ services, maintaining a custom schema per service quickly becomes unmanageable:</p><ul><li>Schema migrations become operational overhead.</li><li>Query logic becomes tightly coupled to schema structure.</li></ul><p>In practice, even something as simple as searching for all log entries across services with the same <strong>trace_id</strong> can become complicated. If each service writes to a different table with a different schema, a single investigation may require querying multiple tables. This forces engineers to jump between dashboards to follow a single trace.</p><p><strong>2. Custom Indexing Requirements</strong></p><p>All log messages are produced in JSON format and include a minimal set of common fields:</p><ul><li>timestamp</li><li>service_name</li><li>trace_id</li></ul><p>Engineers rarely search entire log bodies blindly. They filter by service, narrow by time window, and most likely use a trace_id. Indexing the entire log payload would significantly increase storage overhead and index size, especially at a high ingestion rate.</p><p>Instead, the system must support selective indexing of high-value fields rather than indexing the entire log payload.</p><p><strong>3. Object Storage (S3) as Permanent Storage</strong></p><p>With moderate retention, data volume quickly grows into terabytes. Keeping all of it on hot local storage significantly increases cost and operational complexity. Therefore, the storage layer must:</p><ul><li>Handle continuous high write throughput.</li><li>Scale without requiring manual capacity planning every few weeks.</li><li>Separate storage operations from the log aggregation system.</li></ul><p>Logs can be stored in S3 without relying on local disk space. Compute nodes can scale independently, while storage expands as needed.</p><p>According to these requirements, multiple log aggregation systems were tested, but Grafana Loki stood out as it aligned well with our log ingestion pipelines.</p><h4>Grafana Loki</h4><p>Unlike other storage backends, <a href="https://grafana.com/oss/loki/"><strong>Loki</strong></a> does not index entire log messages, but it indexes a set of labels associated with each log message.</p><p>This design significantly reduces indexing size and overhead while keeping log messages stored in chunks in memory. Each chunk stores logs for a unique set of labels and is flushed to the S3 storage when one of the following criteria is met:</p><ol><li><em>chunk_target_size</em>.</li><li><em>max_chunk_age</em>.</li><li><em>chunk_idle_period</em>.</li></ol><p>In our case, trace_id cannot be used as a label because it would create an unbounded number of chunks in memory. Also, quoting from Loki docs:</p><blockquote>If you are dynamically setting labels, never use a label which can have unbounded or infinite values. This will always result in big problems for Loki.</blockquote><p>This forced us to rethink how trace-based searches should be handled.</p><p>And this is where the Puller service comes into play.</p><h3>The Puller Service</h3><p>Selecting trace_id as a label was not an option. A trace ID is effectively unbounded, and using it as a label would create an infinite number of chunks in memory, eventually degrading Loki’s performance.</p><p>This problem had to be solved before logs reached Loki. Therefore, we decided to build our own service in Go, which we call the Puller service. Its role is simple: pull log messages from Kafka, parse them, enrich them with additional context, assign labels, batch them properly, and then push them to Loki.</p><p>In practice, doing this at <strong>1 million</strong> log messages per second is not a simple task at all.</p><p>Based on the service name, the Puller service needs to cache extra metadata that needs to be added to every log message. Because this operation occurs at very high throughput, the design was inspired by how <strong>Redis</strong> achieves very high throughput using a single-threaded model that avoids complex locking and keeps execution simple and deterministic. But unlike Redis, we adopted a different approach. Instead of using a single shared hash map protected by locks where Goroutines (Go’s lightweight threading mechanism) would constantly compete with each other, we designed the Puller service using an actor-based sharding model.</p><p>Each Goroutine has its own in-memory hash map. No shared state. No global locks. No contention between actors.</p><p>Messages are routed by the Kafka consumer Goroutines to the shard based on the hash of the service_name. Once a message reaches its shard, extra context is pulled from external databases (e.g., Redis, PG) and added as new fields to the log message, and cached in the local HashMap.</p><p>Routing logs to shards based on the service_name increased the cache hit rate to <strong>92%</strong> and drastically reduced load on external databases. The following flowchart demonstrates the processing flow inside the Puller service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOJJHcwdbpJYTthGTPu2QA.png" /></figure><p>Instead of labeling logs with the trace_id, we derive a bucket number from it by computing the hash of the trace ID and extracting only the first 8 bits. <strong>These 8 bits form the bucket label</strong>, yielding 2⁸ = 256 possible buckets.</p><p>By doing this, we transform an unbounded identifier into a fixed, predictable label space. The maximum cardinality is now capped at 256, which is well within safe limits for our ingestion rate and provides a good balance between distribution and memory overhead. It keeps chunk counts predictable while maintaining efficient trace lookups.</p><p>With service_name and bucket selected as labels, the upper bound of unique streams becomes:</p><pre>num(services) × num(buckets) = 80 × 256 = 20,480</pre><p>On the read path, we have faced another challenge: engineers cannot figure out how to extract the bucket number from the trace_id<strong> </strong>to use in search queries. The solution was to add an HTTP endpoint to the Puller service that returns the bucket number for the requested trace_id.</p><p>Then, in Grafana dashboards, we used the <strong>Infinity</strong> <strong>plugin</strong> to query the Puller service for the bucket number associated with a given trace_id. For instance, filtering log messages with <em>trace_id=9f4c2e8b7a1d4c6f8e2a1b3c5d7f9e10</em> would generate the following query to Loki:</p><pre>{bucket=&quot;132&quot;}|=&quot;9f4c2e8b7a1d4c6f8e2a1b3c5d7f9e10&quot; |=&quot;Extra Filter&quot;</pre><p>Or on dashboards with a service name filter:</p><pre>{service_name=&quot;gateway&quot;,bucket=&quot;132&quot;}|=&quot;9f4c2e8b7a1d4c6f8e2a1b3c5d7f9e10&quot; |=&quot;Extra Filter&quot;</pre><p>Here is the bucket calculation code:</p><pre>package bucket<br>import (<br> &quot;hash/fnv&quot;<br>)<br>const bucketMask = 0xFF // 8 bits = 256 buckets<br>func TraceBucket(trace_id string) uint16 {<br>        h := fnv.New64a()<br>        h.Write([]byte(trace_id))<br>        return uint16(h.Sum64() &amp; bucketMask)<br>}<br></pre><p>We made sure that the bucket calculation code does not require memory allocation, as it resides on the hot processing path:</p><pre>go test -bench=. -benchmem<br>goos: linux<br>goarch: amd64<br>pkg: bucket<br>cpu: 11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz<br>BenchmarkTraceBucket_Single-16    178304347  6.851 ns/op  0 B/op  0 allocs/op<br>BenchmarkTraceBucket_Dynamic-16   36006696   34.76 ns/op  7 B/op  0 allocs/op<br>BenchmarkTraceBucket_Parallel-16  49505485   24.79 ns/op  7 B/op  0 allocs/op<br>PASS<br>ok   bucket 4.445s</pre><h4>Pipeline Architecture</h4><p>For the pipeline architecture, we made several tough design decisions starting from a fundamental question:</p><p><strong>How do we route millions of log messages per second into the cluster without introducing bottlenecks or single points of failure?</strong></p><p>Our initial approach was to introduce HAProxy<strong> </strong>as a centralized load balancer. While it worked functionally, it quickly became clear that this design would not scale to our ingestion rate. At very high traffic volume, a single load balancer:</p><ul><li>Becomes a throughput bottleneck.</li><li>Introduces additional latency.</li><li>Represents a clear single point of failure.</li></ul><p>Even in an active–standby configuration, the scaling model remained vertical rather than horizontal.</p><p>To workaround this limitation, we moved away from application-layer load balancing and adopted a network-level load-balancing approach using <strong>OSPF with ECMP (Equal-Cost Multi-Path routing)</strong>.</p><p>Instead of routing traffic through a single proxy, we advertise the same IP address on all Rsyslog instances. Traffic is then distributed by the network layer itself.</p><p>This design provides:</p><ul><li>Active–active high availability.</li><li>Horizontal scalability by simply adding more Rsyslog nodes.</li></ul><p><strong>Rsyslog&#39;s</strong> role in the pipeline is to:</p><ul><li>Receive log messages from all services.</li><li>Batch and enable <strong>Snappy</strong> compression.</li><li>Distribute messages evenly across Kafka partitions</li></ul><p>Also, we added extra configuration to mitigate Kafka failures or short network interruptions by enabling:</p><ul><li>High-capacity in-memory queues for fast processing.</li><li>Disk-assisted queues are used when in-memory queues get filled.</li><li>Automatic retry with infinite resume attempts.</li></ul><p>In other words, Rsyslog acts as a shock absorber between the network layer and Kafka.</p><p>The following flowchart shows the entire pipeline architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMD0WN7exa1dS9yBRghq3w.png" /></figure><h4>Setup Resources</h4><p>Both the Puller service and Loki are running on a Kubernetes cluster with 8 nodes, and each has the following resources:</p><ul><li>16 CPU Cores (<strong>Intel® Xeon® Silver 4309Y @ 2.80GHz</strong>)</li><li>48 GB Memory</li></ul><p>Rsyslog running on 3 separate nodes with:</p><ul><li>6 CPU Cores</li><li>4 GB Memory</li><li>80 GB for disk-assisted queues.</li></ul><h4>Production Results</h4><p>Over multiple weeks of continuous production load and tuning, the system sustained peak ingestion near <strong>1.1 million log messages per second</strong> without observable backpressure, chunk instability, or storage bottlenecks.</p><p>The dashboards below summarize throughput stability, ingestion latency, compression efficiency, and object storage performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sst4fHH8UghMAUnFGL3IUw.png" /></figure><p>Loki latency remains in the millisecond range (≈5–6 ms average), indicating that distributors and ingesters are not experiencing backpressure.</p><p>Compression ratio remains stable at <strong>~3.6x</strong>, confirming efficient chunk sizing and consistent log structure. More importantly, the majority of chunk flushes occur due to full chunk size, not idle timeout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZsFPZ7rqyT8TDF6MSg21g.png" /></figure><h4>Performance Optimizations</h4><p>This section will explain extra optimization techniques used to achieve greater performance:</p><ol><li><strong>Node-Aware Routing Strategy</strong></li></ol><p>Since each Kubernetes node runs one Puller pod and one Distributor pod, we tuned the Puller service to prefer forwarding batches to the Distributor running on the same node to reduce cross-node traffic.</p><p>When the Puller service starts, it resolves the Distributor <strong>headless</strong> service provided by the Loki Helm chart via CoreDNS pods to obtain Distributor pods’ IP addresses, then queries the Kubernetes API server to determine which Distributor pod resides on the same node. Traffic is routed locally whenever possible and only redirected to other nodes if the local Distributor becomes unavailable.</p><p>2. <strong>Hash Distribution and Shard Imbalance</strong></p><p>The Puller service uses a Goroutine called the message distributor that hashes the<strong> </strong>service_name and forwards messages to the actor shards based on the hash result.</p><p>However, we operate with only 80 distinct services. With low-cardinality inputs, hashing alone does not guarantee uniform distribution. Under peak hours, some shards became overloaded while others remained underutilized.</p><p>The solution was to introduce a dynamic rebalancing mechanism.</p><p>Instead of relying solely on the hash result, we maintain an internal map:</p><pre>map(service_name)=*shard</pre><p>Each shard also maintains a message counter tracking the number of processed log messages, and then a background Goroutine runs every five minutes to evaluate shard load distribution.</p><p>If an imbalance is detected, the system updates the service-to-shard mapping by adjusting the pointer in the hash map to a shard with less traffic. This transparently redirects traffic for selected services to less-loaded shards. The following image shows the load distribution across shards after implementing the balancing technique:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onQBcWHX-pH6KJV_XSbSqA.png" /><figcaption>Single Puller Pod Load Distribution Across Shards</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6E3AkVpBGZgVntgw3lLkAQ.png" /><figcaption>Single Puller Pod Load Distribution Across Shards [5m]</figcaption></figure><p>3. <strong>Network Queue Bottleneck</strong></p><p>During peak hours, we observed that one CPU core was consistently running at ~90% utilization, while the remaining cores were less utilized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMY6iFXBWEoUlDZKTbUVdw.png" /></figure><p>The root cause was not application-level contention, but network configuration. The virtual NIC was configured with only a single RX and TX queue. As a result, all network interrupts were bound to a single interrupt line.</p><p>Because there was only one RX/TX queue, the irqbalance service had no opportunity to distribute interrupt handling across multiple CPU cores. All interrupt requests were effectively pinned to a single core, which became saturated under high packet rates.</p><p>The fix was straightforward: increase the number of RX/TX queues to 16, matching the number of CPU cores per node.</p><p>Once multi-queue support was enabled, interrupt handling was distributed across cores, CPU utilization normalized, and the bottleneck disappeared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpOR3C_VuQ3H7WiixCq_rg.png" /></figure><p>4. <strong>Kafka</strong> <strong>Consumer Group Lag</strong></p><p>During peak hours, we observed uneven consumption across Puller pods. Some consumers were consistently lagging behind on specific partitions, while others remained underutilized.</p><p>The topic contains <strong>48 partitions</strong>, and we operate <strong>8 Puller pods</strong>, meaning each pod is assigned 6 partitions. Traffic volume across partitions was relatively even. However, certain Kubernetes nodes were more heavily loaded than others. Since each Puller pod runs on a specific node, any node-level CPU pressure directly affects the consumer instance running on it.</p><p>Kafka’s traditional consumer model assigns each partition exclusively to a single consumer. As a result, performance differences at the node level translated directly into lag on the partitions owned by slower consumers, even though partition traffic itself was balanced.</p><p>This resulted in:</p><ul><li>Noticeable lag on selected partitions during peak hours.</li><li>Uneven CPU utilization across Puller pods.</li></ul><p>To address this limitation, we upgraded Kafka to version 4.2 and enabled shared groups introduced by <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-932%3A+Queues+for+Kafka">KIP-932</a>, which reached GA (General Availability) in this release.</p><p>Shared groups introduce queue-like semantics into Kafka. Instead of binding partitions exclusively to individual consumers, records can be consumed by a pool of consumers acting as a shared processing group.</p><p>Consumers are no longer constrained to a fixed subset of partitions. Work distribution becomes dynamic at the record level rather than the partition ownership level. Load spreads more evenly across Puller pods, lag stabilizes across the topic, and CPU utilization becomes significantly more balanced.</p><p>This eliminated partition-level bottlenecks and substantially improved processing predictability under sustained high throughput.</p><h4>Summary</h4><p>Building a high-traffic log ingestion pipeline at this scale was not a trivial task. It required deliberate design decisions at every layer, from network routing and buffering strategies to shard distribution, cardinality control, and storage architecture.</p><p>Each optimization solved a specific bottleneck. Together, they formed a system that behaves predictably under extreme load.</p><p>Under peak traffic approaching one million log messages per second:</p><ul><li>Queries consistently return results in under <strong>5 seconds</strong>.</li><li>Newly ingested log messages become searchable in less than <strong>10 seconds</strong>.</li></ul><p>These results were not achieved by simply throwing more hardware at the problem. They came from making the right architectural decisions and tuning each layer carefully.</p><p>If you found this article helpful, feel free to clap and share it with others who might benefit from it.</p><p>I’m always happy to connect with engineers working on high-scale distributed systems — you can reach me on <a href="http://www.linkedin.com/in/ahsifer"><strong>LinkedIn</strong></a>.</p><h4>Resources</h4><p><a href="https://grafana.com/oss/loki/">Grafana Loki OSS | Log aggregation system</a></p><p><a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-932%3A+Queues+for+Kafka">https://cwiki.apache.org/confluence/display/KAFKA/KIP-932%3A+Queues+for+Kafka</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60a1551ccc1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Redis Internals: Persistence, Memory Management, and Asynchronous I/O]]></title>
            <link>https://medium.com/@ahsifer/demystifying-redis-internals-persistence-memory-management-and-asynchronous-i-o-05b33afa7f70?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/05b33afa7f70</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 09:09:57 GMT</pubDate>
            <atom:updated>2025-09-24T12:10:37.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*haLkstjaBi9q21biJVKmiQ.png" /></figure><p>This article will help you understand Redis concepts that are often overlooked, providing a deeper insight into its internal workings. The following topics will be explained:</p><ol><li><strong>HOW REDIS WORKS.</strong></li><li><strong>SNAPSHOTTING and KERNEL TRANSPARENT HUGEPAGE</strong></li><li><strong>APPEND ONLY</strong></li><li><strong>REPLICATION</strong></li><li><strong>MEMORY MANAGEMENT</strong></li><li><strong>THREADED I/O</strong></li><li><strong>HOW REDIS WORKS.</strong></li></ol><p><em>Redis</em> is an open-source, in-memory data structure store that can be used as a database, cache, or message broker. It is designed for extremely low latency (often under 1 ms) and high throughput, capable of handling hundreds of thousands of requests per second on typical hardware.</p><p>Internally, <em>Redis</em> utilizes multiple processes for specific background tasks, including I/O, persistence, and cluster communication. However, command execution against in-memory data structures (sets, lists, hashes, etc.) is handled by a single dedicated thread. This execution model ensures that operations are processed sequentially, which eliminates the need for complex locking mechanisms. As a result, <em>Redis</em> avoids many concurrency problems that affect other databases, such as race conditions, deadlocks, and synchronization issues.</p><p>2. <strong>SNAPSHOTTING and KERNEL transparent hugepage</strong></p><p><em>Redis</em> Snapshotting (RDB snapshot) is the simplest form of persistence. It is performed at regular intervals when specific conditions are met by taking an exact copy of the data from memory and dumping it to the disk. This operation is performed by a new process created by <em>Redis</em> using the fork() system call. This newly created process will be responsible for dumping the in-memory content to the disk.</p><p>In general, when a process uses the fork() system call, the Linux Kernel will create another process that shares the exact memory pages with the caller process, and these shared pages will be converted to read-only mode. Accordingly, when one of these two processes modifies one of the memory pages, the kernel will create a copy of the page into a different memory location and apply the modifications to it. This ensures that the other process will still access the data in memory without modifications; this operation is known as copy-on-write (COW).</p><p>In the case of <em>Redis</em>, this approach allows the new forked <em>Redis</em> process to have a snapshot of the data in memory. At the same time, any write operation done by the main <em>Redis</em> process will lead to creating a new memory page (each memory page size is 4KB), and this can be one of the unavoidable latency sources in <em>Redis</em> when enabling RDB snapshotting. Besides that, if all memory pages get modified during snapshotting, <em>Redis’s</em> memory usage will be doubled. Therefore, when the snapshot process starts, the kernel will check if there is enough available memory. Accordingly, if there is no enough available memory, the operating system will fail the <em>Redis</em> fork() system call, and the entire snapshot operation will fail. The solution is to allow the Linux kernel to create the other process even if there is no enough memory by enabling the vm.overcommit_memory=1 in the Linux kernel:</p><pre>echo &quot;vm.overcommit_memory=1&quot; &gt;&gt; /etc/sysctl.conf<br>sysctl -p</pre><p>Suppose <strong>transparent hugepages (THP)</strong> are enabled in the kernel. In that case, COW operations become more expensive and lead to increased latency because, when enabled, the Linux kernel will dynamically change the page size for the <em>Redis</em> process. For instance, if the Kernel decided to change the page size from the default, which is 4 KB, to 2 MB, then every single write operation during the COW will lead to rewriting a 2 MB page of data into a new location in memory. That is why it is highly recommended to disable the Linux transparent hugepages feature on <em>Redis</em> nodes:</p><pre>echo never &gt; /sys/kernel/mm/transparent_hugepage/enabled<br>echo never &gt; /sys/kernel/mm/transparent_hugepage/defrag</pre><blockquote>Note: The previous configuration is not persistent across restarts and a different approach should be followed.</blockquote><p>The following flowchart describes the process briefly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HX0zuE6hJ9Ri3BqxLNX5SA.png" /></figure><p>Also, after reading the <em>Redis</em> configuration docs, I recommend setting the following configuration parameters:</p><pre>#After 3600 seconds (an hour) if at least 1 change was performed create a new RDB<br>#After 300 seconds (5 minutes) if at least 100 changes were performed create a new RDB<br>#After 60 seconds if at least 1000 changes were performed create a new RDB<br>save 3600 1 300 100 60 1000<br># By default, Redis will stop accepting writes if RDB snapshots are enabled and the last<br># RDB snapshot operation was failed. In my opinion it is critical to disable this<br># configuration parameter (mostly in caching setups) because any issue with the storage or network error when<br># writing data to remote NFS then Redis will stop accepting writes.<br>stop-writes-on-bgsave-error no<br># By default, Redis will compress the backup RDB file, and this will increase CPU usage<br># especially when the RDB file value is huge. Also, the decompression will increase the<br># startup duration.<br>rdbcompression no<br># By default, Redis will calculate the CRC64 checksum and place it at the end of the RDB<br># file. This makes the format more resistant to corruption but there is a performance<br># hit to pay (around 10%) when saving and loading RDB files, so you can disable it<br># for maximum performances.<br>rdbchecksum no</pre><p>3. <strong>APPEND ONLY</strong></p><p>The Append Only File, commonly referred to as AOF, is the main <em>Redis</em> persistence option. The way it works is extremely simple: every time a write operation that modifies the dataset in memory is performed, the operation gets logged into a file. The log is produced in the same format used by clients to communicate with <em>Redis</em>, so it can be even piped via netcat to another instance or easily parsed if needed. Even though there are interesting cases where users mistakenly run the <strong>FLUSHALL</strong> command, users can recover the deleted data by only removing the <strong>FLUSHALL</strong> command from the end of the append-only file and restarting <em>Redis</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7Lo4I2kse1sAuI02OP4Wg.png" /></figure><p>To understand the performance impact of writing every command that modifies the data to the disk, a deep understanding of how the data is written to the storage is required:</p><ol><li>A client application sends a write command (like UPDATE or INSERT) to the database server.</li><li>The database server receives the data and stores it temporarily in its own memory. At this point, the database has acknowledged the write request, but the data isn’t yet persistent.</li><li>The database process asks the operating system (OS) to write the data to disk using the <strong>write()</strong> system call. The OS copies this data from the database’s memory into a <strong>kernel buffer</strong>, also known as the page cache. This is a crucial step for performance, as the OS can now manage the write to the physical disk asynchronously.</li><li>The OS later flushes the data from the kernel buffer to the disk controller. The controller, which has its own cache (often called a write-back cache), temporarily stores the data.</li><li>Finally, the disk controller writes the data from its cache to the physical storage medium, such as a magnetic platter or a solid-state drive (SSD). Only after this final step is the data considered truly durable and persistent.</li></ol><p>Each of these steps introduces potential delays, and <em>Redis’s</em> AOF persistence behavior depends on how frequently it forces the data from memory to actual disk storage. Internally, when a write command arrives, <em>Redis</em> first appends it to the AOF buffer in memory. Then uses thewrite() system call to copy the data from <em>Redis’s</em> process space into the kernel’s page cache. This step does <strong>not</strong> guarantee that the data is on disk; it only ensures the data is now managed by the OS. To force the data to be written to the storage device, <em>Redis</em> calls the fsync() system call, which forces the Kernel to write the data to the underlying disk controller.</p><p><em>Redis</em> provides three appendfsync policies to control how often fsync() is called:</p><ol><li><strong><em>always</em></strong> <br>After every command that modifies data, <em>Redis</em> immediately calls both write() and fsync(). This guarantees maximum durability but adds the latency of a full disk flush to each write operation.</li><li><strong><em>everysec</em><br></strong><em>Redis</em> calls write() on every command but defers fsync() to a background thread, which runs once per second. This is the default mode, offering a good trade-off between durability and performance, with a worst-case loss of up to one second of data when the server crashes. Furthermore, <em>Redis</em> will wait up to two seconds for the fsync() to complete. If the flush to disk is too slow, for instance, when using remote storage such as NFS, and the fsync() still hasn’t finished after two seconds, <em>Redis</em> will fall back to a blocking write() in the main thread. This will stall all client requests until the fsync() finishes.</li><li><strong><em>no</em><br></strong><em>Redis</em> calls write() for each command, but never explicitly callsfsync(), relying entirely on the operating system to decide when to flush data. By default, the Linux Kernel will flush data to the disk controller every 30 seconds. This gives the best performance but the weakest durability. This policy is recommended in caching scenarios with high performance and low latency requirements. The following Linux Kernel parameters can be tuned to achieve the desired outcome</li></ol><pre>/proc/sys/vm/dirty_background_ratio<br>/proc/sys/vm/dirty_ratio<br>/proc/sys/vm/dirty_expire_centisecs<br>/proc/sys/vm/dirty_writeback_centisecs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsTcG88-IQAEmf_jISyzAw.png" /></figure><p>While AOF generally provides stronger guarantees against data loss compared to RDB snapshots, its reliance on frequent write() and fsync() calls can limit throughput, especially on slow disks or when it appendfsync is set to always. However, to avoid unbounded AOF file growth, <em>Redis</em> periodically performs an <strong>AOF rewrite</strong>, generating a smaller, equivalent file with the minimal set of commands to rebuild the current dataset. This rewrite runs in a background process created viafork()which is also subject to the same <strong>copy-on-write (COW)</strong> and memory overhead considerations as RDB snapshotting. Accordingly, I recommend that the append-only configuration of <em>Redis</em> be set to the following:</p><pre># Enable append-only file<br>appendonly yes<br># Choose appendfsync mode (use no for caching, everysec for services that require a level of durability, and always for high consistency gaurantees)<br># appendfsync always<br># appendfsync everysec<br>appendfsync no<br># Disable the fsync() systemcall when Redis is creating the RDB snapshot or rewritting the AOF<br># This configuration can only be valid when appenonly is everysec or always<br>no-appendfsync-on-rewrite yes<br># For any reason the AOF got corrupted or truncated, then Redis will not start. However, when<br># enabling the following configuration parameter, Redis will load as much as possible of the<br># append-only file<br>aof-load-truncated yes</pre><p>4- REPLICATION</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzyzH4VzzYwQEmfKoRpA4A.png" /></figure><p>To provide load distribution of reads across multiple nodes, <em>Redis</em> introduced asynchronous replication by streaming all write commands to all replica nodes. However, there are two replication modes in <em>Redis</em>:</p><ol><li><strong>Full Replication</strong>: In this mode, the <em>Redis</em> master will use the <strong>fsync()</strong> system call to create another <em>Redis</em> process that is responsible for writing the RDB file to the disk, and then will send this file to all the replica nodes. However, this process introduces the same overhead as the snapshotting process. Also, for better performance, a diskless replication can be enabled, where <em>Redis</em> will stream the data directly to the replica.</li><li><strong>Partial Replication</strong>: As the number of replicas increases, the latency and overhead of full replication also grow. To address this issue, <em>Redis</em> introduced partial replication. The master node maintains a <strong>backlog</strong> buffer that stores the most recent write commands, while each replica tracks an offset indicating how much of the <strong>backlog</strong> it has already received. When a replica reconnects, the master only sends the missing writes based on the replica’s offset. If the offset number is outside the backlog offset range (beginning and starting offsets), the master will rollback to full replication.</li></ol><p>From the perspective of the <strong>CAP</strong> theorem, <em>Redis</em> does not guarantee consistency across replicas. Because of the asynchronous replication, clients cannot be sure if the written data to the master is replicated to the other replicas or not. However, clients can use the <strong>WAIT</strong> command to wait for a specific number of replica instances to acknowledge the write. It does not turn a set of <em>Redis</em> instances into a consistent system with strong consistency guarantees because acknowledged writes can still be lost during a failover.</p><blockquote>Note: Redis replication does not provide high availability guarantees because when the master fails, replicas cannot be converted to the master automatically. Therefore, most of the time, Redis Sentinel or a cluster is used to achieve high availability.</blockquote><p>The following configuration directives can be changed to the following in the <em>Redis</em> default configuration file</p><pre># Set the master node for the replication.<br>replicaof &lt;masterip&gt; &lt;masterport&gt;<br><br># Allow the replica to serve stale data when the connection between the master and the replica<br># is lost, or the maximum lag between master and slave is reached.<br>replica-serve-stale-data yes<br><br># You can configure a replica instance to accept writes or not. Writing against<br># A replica instance can be useful to store some ephemeral data. However, the written <br># data on a replica will be deleted after resync with the master. Also, it may cause <br># problems if clients are writing to the replica because of a misconfiguration.<br>replica-read-only yes<br><br># When Redis does a full disk replication, the data is written from the memory to a file on the<br># disk. This approach can introduce huge latency if the disk is slow. Therefore, the Redis team introduced <br># diskless replication. When enabled, the Redis master creates a new process that directly <br># writes the RDB file to replica sockets, without touching the disk at all. Diskless replication works better<br># in environments with slow disks and fast (large bandwidth) networks<br>repl-diskless-sync yes<br><br># When diskless replication is enabled, it is possible to configure the delay the server waits <br># to spawn the child that transfers the RDB via socket to the replicas. This is important <br># since once the transfer starts, it is not possible to serve new replicas arriving, which will <br># be queued for the next RDB transfer, so the server waits a delay to let more replicas arrive.<br># Since most of our clusters have one master and one slave, setting this configuration value to 0 is a must.<br>repl-diskless-sync-delay 0<br><br># When diskless replication is enabled with a delay, it is possible to let the replication start <br># before the maximum delay is reached if the maximum number of replicas expected has connected.<br># Since most of our clusters have one master and one slave, setting this configuration value to 1 is a must.<br>repl-diskless-sync-max-replicas 1<br><br># Set the replication backlog size.<br>repl-backlog-size 100mb<br><br># How long should the replica keep saving the backlog buffer after no replicas are connected for a long period?<br>repl-backlog-ttl 3600<br><br># Replica ignore disk write errors controls the behavior of a replica when it is<br># unable to persist a write command received from its master to disk. By default,<br># This configuration is set to no and will crash the replica in this condition.<br># This config can be toggled to &#39;yes,&#39; which will just<br># log a warning and execute the write command it got from the master.<br>replica-ignore-disk-write-errors yes</pre><p>5- <strong>MEMORY MANAGEMENT</strong><br>In <em>Redis</em>, memory management refers to the process of managing key eviction from the memory when the maximum memory is reached. The maxmemory configuration directive can be used to specify the maximum memory that <em>Redis</em> is allowed to use. As shown below:</p><pre>maxmemory 10g</pre><p>When the maximum memory is reached, <em>Redis</em> will enforce the configured eviction policy. In general, <em>Redis</em> has implemented three eviction algorithms:</p><p><strong>1- Least Recently Used (LRU)</strong><br>The LRU (Least Recently Used) eviction policy operates on the principle that data recently accessed will be accessed frequently in the near future. This algorithm can be applied in a wide range of applications due to its balance between performance and memory usage, and more importantly, its predicted behavior. <em>Redis’s</em> implementation of the LRU is commonly referred to as approximated LRU due to its internal implementation, which focuses on latency and performance over accuracy. When LRU is enabled, <em>Redis</em> will add 24 bits to every single key for storing the last access time, and it will be updated every time the key is accessed. Furthermore, when the maximum memory is reached, <em>Redis</em> will spawn a new thread that is only responsible for picking a group of candidates (maxmemory-samples) from the keyspace to be evicted. The candidate with the lowest access time will be added to a sorted list based on the access time, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*emj8rOeqJHKfXYAtp6Sfkw.png" /></figure><p>When a client writes a new key, Redis will remove an element on the far right of the list. This LRU implementation approach provides great performance and very close results to the theoretical LRU implementations, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*sZ-tPPBZgAKJQq3lOPDn2Q.png" /><figcaption><a href="https://redis.io/docs/latest/develop/reference/eviction/">SRC</a></figcaption></figure><p>The number of sampled candidates on every iteration from the keyspace can be configured using the following directive:</p><pre>maxmemory-samples 5</pre><blockquote>As the number of maxmemory-samples increases, the results will be closer to the theoretical LRU at the expense of increased latency. Also, the maximum number of elements that can be inserted into the sorted list is 16, and it is hard-coded by the Redis team.</blockquote><p><strong>2- Least Frequently Used (LFU):</strong><br>Unlike LRU, LFU prioritizes the frequently accessed items over the newly requested ones. This algorithm can be applied in scenarios where data popularity is more important than trendiness. In this mode, the 24 bits are used to store the number of accesses, and the list will be sorted based on the access counter.</p><p><strong>3- Random: randomly evict items.</strong></p><p>Based on the previously provided algorithms, the eviction policy can be configured as follows:</p><pre># volatile-lru -&gt; Evict using approximated LRU, only keys with an expire set.<br># allkeys-lru -&gt; Evict any key using approximated LRU.<br># volatile-lfu -&gt; Evict using approximated LFU, only keys with an expire set.<br># allkeys-lfu -&gt; Evict any key using approximated LFU.<br># volatile-random -&gt; Remove a random key having an expire set.<br># allkeys-random -&gt; Remove a random key, any key.<br># volatile-ttl -&gt; Remove the key with the nearest expire time (minor TTL)<br># noeviction -&gt; (the default) Don&#39;t evict anything, just return an error on write operations.</pre><blockquote>The default Redis configuration of the maxmemory is set to zero, and no eviction policy is set.</blockquote><p>6. <strong>MULTITHREADED I/O</strong></p><p><em>Redis</em> has improved its multithreading capabilities by introducing a new asynchronous I/O threading implementation. Since version 6.0, <em>Redis</em> has supported I/O threads to handle tasks such as socket reads, writes, and command parsing. When enabled, clients can be assigned to specific I/O threads by the main thread. After queries are read and parsed, the I/O threads notify the main thread, which processes the queries and generates responses, while the I/O threads handle writing the replies back to clients. This feature can be enabled with the following configuration parameter:</p><pre>io-threads 3</pre><blockquote>It is recommended to run <em>Redis</em> with IO threads on a machine with 4 or more cores and set the number of IO threads less than the number of available cores. For instance, if a machine has only 8 CPU cores, then set the IO threads to 7 and let the eighth core be reserved for the main Redis thread, which is responsible for command execution.</blockquote><p><strong>Resources</strong></p><p>1- <a href="https://redis.io/docs/latest/develop/reference/eviction/">https://redis.io/docs/latest/develop/reference/eviction/</a></p><p>2- <a href="https://antirez.com/news/109">https://antirez.com/news/109</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05b33afa7f70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving Beyond Static Admission Controllers: Kyverno for Policy Management in Kubernetes]]></title>
            <link>https://medium.com/@ahsifer/moving-beyond-static-admission-controllers-kyverno-for-policy-management-in-kubernetes-d7e18649ea83?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7e18649ea83</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kyverno]]></category>
            <category><![CDATA[openshift]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 19:29:14 GMT</pubDate>
            <atom:updated>2025-08-30T19:29:14.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/417/0*nU-OTDenDVEC3Vz3.png" /></figure><h3>Introduction</h3><p>In Kubernetes, when the API server receives a request to create, update, or delete a resource (such as a Deployment, Pod, or Service), it passes through several processing stages before the object is created and stored in the etcd storage, and these stages are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TKUKsjDTFa6VPiX2ZCdFg.png" /></figure><ol><li><strong>Authentication</strong>: Allows only authenticated users to interact with the API server (commonly implemented using client certificates, bearer tokens, or OpenID Connect).</li><li><strong>Authorization</strong>: Checks whether the authenticated user has enough permissions to perform the requested operation (commonly enforced using RBAC).</li><li><strong>Mutating Admission</strong>: In this stage, the API server sends the object that the user wants to create to all configured mutating admission webhooks sequentially. Each webhook can modify the object before passing it to the next webhook. By the end of this stage, the object may include additional fields, default values, or injected configurations. Furthermore, a Webhook is a Kubernetes resource that defines <strong>when</strong> the API server should send requests, <strong>which</strong> resources it applies to, and <strong>where</strong> those requests should be sent. Usually, to a pod running in the cluster, or sometimes, the changes are made by the API server itself. By default, Kubernetes comes with a group of built-in mutating Webhooks, for instance, AlwaysPullImages(modifies every new Pod to force the image pull policy to Always, to ensure images are not cached and used by unauthorized users), DefaultStorageClass(sets the name of the default storage class if pod requests PVC and storage class name is not provided), etc.</li><li><strong>Object Schema Validation</strong>: In this stage, the API server validates the object against its <strong>OpenAPI schema</strong>. Also, ensure that the JSON and YAML are in the correct format and data type.</li><li><strong>Validating Admission</strong>: Calls any validating Webhooks that match the request. Unlike the <strong>Mutating Admission</strong>, the Webhooks in this stage are called in parallel, and they do not mutate the object; instead, they validate the request against a set of policies. If any of them reject the request, the request fails. An example of a validation admission Webhook is when the defined resource limit for a pod in the deployment exceeds the limits for the namespace or denies resource creation in a non-existent namespace.</li></ol><blockquote><em>Note: Webhooks in both the Mutating Admission and Validating Admission are used to send requests to the backend controller pods for mutations and validations.</em></blockquote><p>The default mutation and validation webhooks in Kubernetes are static by design, making them unsuitable for dynamic, automated workflows. As a result of this limitation, an automated policy engine like Kyverno has been created, which offers greater flexibility, dynamic policy enforcement, and streamlined automation capabilities.</p><h3>Kyverno</h3><h4>Introduction</h4><p><strong>Kyverno</strong> is a cloud-native policy engine built specifically for Kubernetes. It enables platform and operation teams to enforce security, compliance, and automation best practices directly within the cluster. Unlike Kubernetes’ built-in static admission controllers, Kyverno acts as a <em>dynamic</em> admission controller, capable of performing resource mutation, validation, and generation at runtime.</p><h4>How does Kyverno work?</h4><p>As discussed earlier, Kyverno works by adding Webhooks to the admission and validation stages; these Webhooks point to pods running in the Kyverno namespace. According to the rules defined in the Webhooks, Kubernetes will start sending requests to the Kyverno pods. The following figure describes the request workflow after Kyverno is installed in the Kubernetes cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJRcEUXYx_XnTNomNwhbVA.png" /></figure><p>From the previous figure, the Kyverno engine consists of the following components:</p><ol><li>Admission Controller: Handles real-time validation, mutation, and policy enforcement for incoming requests from the Kubernetes API server.</li><li>Webhook Controller: Manages lifecycle and configuration of admission webhooks.</li><li>Cleanup Controller: Deletes resources according to defined cleanup policies.</li><li>Report Controllers: Aggregates policy violation data into PolicyReports/ClusterPolicyReports.</li><li>Background Controller: Enforces policies on existing resources that were created before the policy existed.</li></ol><h3>Policy Types</h3><p>Kyverno comes with a group of policy types that can be used to create polices:</p><p><strong>1- Validation Policy</strong>: This type of policy is used for creating policies that validate resources. For instance, a policy that ensures users will never use images with the tag latest:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: validate-image-tag<br>spec:<br>  background: true # allow this validation to scan the previously created pods and check for violations<br>  rules:<br>    - name: validate-image-tag<br>      match:<br>        any: #consider this rule is valid if any of the following conditions are met (also, there is all)<br>        - resources:<br>            kinds:<br>            - Pod #this condition will match all pods related operations, including creation, update, and delete<br>      validate:<br>        failureAction: Enforce #if the condition is met, then fail the operation (also, can be set to audit so that it can be used to check who is violating specific rules)<br>        message: &quot;Cannot use image with tag latest (always use production-ready image tag)&quot;<br>        pattern:<br>          spec:<br>            Containers:<br>              - image: &quot;!*:latest&quot;</pre><p>Then, when a user wants to create a pod with the image latest, the following errors will be shown:</p><pre>Error from server: error when creating &quot;deployment.yaml&quot;: admission webhook &quot;validate.kyverno.svc-fail&quot; denied the request: <br>resource Deployment/default/nginx-latest-test was blocked due to the following policies <br>validate-image-tag:<br>  autogen-validate-image-tag: &#39;validation error: Cannot use image with tag latest<br>    (always use production-ready image tag). rule autogen-validate-image-tag<br>    failed at path /spec/template/spec/containers/&#39;</pre><p>Also, the cluster admin can monitor violations using the following command:</p><pre>kubectl get policyreport -o wide<br>NAME                                   KIND   NAME       PASS   FAIL   WARN   ERROR   SKIP   AGE<br>42a83919-015d-4915-8395-96246fe386af   Pod    nginx      0      1      0      0       0      1m</pre><p>2- <strong>Mutation Policy</strong>: This type of policy is used for creating policies that mutate resources. For instance, a mutation policy that adds the name of the user to all the newly created or updated resources using the annotation:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: add-username-label<br>spec:<br>  background: false<br>  rules:<br>    - name: add-creator-username<br>      match:<br>        resources:<br>          kinds:<br>            - &quot;*&quot;<br>      mutate:<br>        patchStrategicMerge:<br>          metadata:<br>            annotations:<br>              created-by: &quot;{{ request.userInfo.username }}&quot;</pre><p>3- <strong>Generation Policy</strong>: This type of policy is used for creating policies that generate resources. For instance, a Generation policy that sets the resource quota on every newly created namespace:</p><pre>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: generate-resourcequota<br>spec:<br>  rules:<br>    - name: generate-quota<br>      match:<br>        any:<br>          - resources:<br>              kinds:<br>                - Namespace<br>      generate:<br>        apiVersion: v1<br>        kind: ResourceQuota<br>        name: default-quota<br>        namespace: &quot;{{request.object.metadata.name}}&quot;<br>        synchronize: true<br>        data:<br>          spec:<br>            hard:<br>              requests.cpu: &quot;2&quot;<br>              requests.memory: 2Gi<br>              limits.cpu: &quot;4&quot;<br>              limits.memory: 4Gi</pre><p><strong>4- Cleanup Policy</strong>: This policy will delete resources based on a schedule. For instance, we can create a pod with TTL. Therefore, permission for Kyverno to delete pods must be given:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  labels:<br>    app.kubernetes.io/component: cleanup-controller<br>    app.kubernetes.io/instance: kyverno<br>    app.kubernetes.io/part-of: kyverno<br>  name: kyverno:cleanup-pods<br>rules:<br>  - apiGroups:<br>      - &quot;&quot;<br>    resources:<br>      - pods<br>    verbs:<br>      - get<br>      - watch<br>      - list<br>      - delete</pre><p>And a deployment can be changed to the following:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  labels:<br>    cleanup.kyverno.io/ttl: 1m<br>  name: foo<br>spec:<br>  containers:<br>    - args:<br>        - sleep<br>        - 1d<br>      image: busybox:1.35<br>      name: foo</pre><h4><strong>Installation</strong></h4><p>The following commands can be used to install Kyverno in a production cluster with a high availability setup:</p><pre>helm repo add kyverno https://kyverno.github.io/kyverno/ <br>helm repo update<br>helm install kyverno kyverno/kyverno -n kyverno --create-namespace \<br>--set admissionController.replicas=3 \<br>--set backgroundController.replicas=2 \<br>--set cleanupController.replicas=2 \<br>--set reportsController.replicas=2 \<br>--set enablePolicyException=true</pre><p>The created pods should be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MLuI_pVJHTd5Xi-gb8VjA.png" /></figure><p>Also, the Kyverno team provides a group of already-created policies that can be installed in the cluster to make the cluster adhere to the pod security standards provided by the CNCF (similar to the policies provided by OpenShift):</p><pre>helm install kyverno-policies kyverno/kyverno-policies -n kyverno --set validationFailureAction=Enforce --set podSecurityStandard=restricted</pre><p>After enforcing the restricted mode, a simple nginx deployment should be changed to be as follows:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-nonroot<br>  labels:<br>    app: nginx<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      securityContext:<br>        runAsNonRoot: true<br>        runAsUser: 1000<br>        runAsGroup: 2000<br>        fsGroup: 2000<br>        seccompProfile:<br>          type: RuntimeDefault<br>      containers:<br>        - name: nginx<br>          image: nginx:1.29<br>          ports:<br>            - containerPort: 80<br>          securityContext:<br>            allowPrivilegeEscalation: false<br>            capabilities:<br>              drop: [&quot;ALL&quot;]<br>            readOnlyRootFilesystem: true<br>            runAsNonRoot: true</pre><h4><strong>Caveats</strong></h4><ul><li>It is recommended to select which resources the policy will apply to. This will ensure the policy is enforced only on relevant objects and avoid unnecessary processing of unrelated resources. Accordingly, it is advisable to avoid using a wildcard (*) for matching policies.</li><li>As Kyverno examines every single operation twice (during mutation and validation/admission stages), this can generate significant traffic and CPU load on the Kyverno pods. Therefore, it is recommended to install Kyverno in <strong>high availability mode</strong> as shown earlier, especially in large production clusters.</li><li>Always test new policies in <strong>audit mode</strong> first before enforcing them in production to avoid service disruptions.</li><li>Since Kyverno works in the mutation and validation admission stages, which come after the authentication and authorization stage, Kyverno cannot be used as an RBAC engine.</li><li>If Kyverno pods are down or unreachable, then the default behaviour of the API server is to consider all operations failed, which will lead to the following:<br>1- Unable to create, update, or delete Pods, Deployments, Services, etc.<br>2- Failed Horizontal Pod Autoscaling operation (if it creates/deletes pods via the API).<br>3- Operators and controllers will be unable to create/update objects.</li></ul><h4><strong>Conclusion</strong></h4><p>In summary, while Kubernetes’ built-in admission controllers provide essential security and control, their static nature limits their use in dynamic, automated environments. Kyverno addresses this limitation by acting as a dynamic policy engine that empowers teams to enforce security, compliance, and best practices at runtime. By leveraging Kyverno’s powerful Validate, Mutate, Generate, and Cleanup policies, organizations can create a more secure, consistent, and automated Kubernetes environment that scales with their needs.</p><h4>Resources</h4><ol><li><a href="https://kyverno.io/">https://kyverno.io</a></li><li><a href="https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/">https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7e18649ea83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iptables vs. GoXDP: The Ultimate Packet Filtering Benchmark Setup and Results]]></title>
            <link>https://medium.com/@ahsifer/iptables-vs-goxdp-the-ultimate-packet-filtering-benchmark-setup-and-results-4846ef6ae482?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4846ef6ae482</guid>
            <category><![CDATA[xdp]]></category>
            <category><![CDATA[ebpf]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[firewall]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 21:28:38 GMT</pubDate>
            <atom:updated>2025-08-30T18:27:09.331Z</atom:updated>
            <content:encoded><![CDATA[<h3>iptables vs. XDP: The Ultimate Packet Filtering Benchmark Setup and Results</h3><p>The Linux netfilter module enables user-space applications to register the processing rules applied to the packets by the Linux kernel network stack. This enables efficient network forwarding and filtering. Iptables is one of the most common firewall tools used to filter packets that utilize the Linux Netfilter for packet processing. However, the big limitation in the iptables architecture is the matching process of the packets. For instance, if the INPUT chain of the filter table has 5K rules in this case every single packet will be checked against these rules until the first match is found and this introduces unnecessary processing by the CPU because of a huge number of rules that likely most of them will not match until the first match found. Even after the performance gain of using ipset, it cannot cope with the huge number of packets received in DDoS attacks. Therefore, the solution is to build firewall tools using Linux XDP (like <a href="https://medium.com/@ahsifer/introducing-goxdp-utilizing-the-power-of-xdp-for-advanced-linux-firewall-07de694310da">GoXDP</a> or xdp-filters). This blog will describe the benchmark environment setup and the results of the Linux firewall tools (iptables and <a href="https://medium.com/@ahsifer/introducing-goxdp-utilizing-the-power-of-xdp-for-advanced-linux-firewall-07de694310da">GoXDP</a>) to determine the maximum number of packets that can be dropped per second when CPU utilization reaches 100%.</p><h4><strong>Environment Setup</strong></h4><p>The benchmark environment will consist of 3 physical servers each one of them with the following resources</p><p>1- Single CPU socket Intel(R) Xeon(R) Silver 4210 CPU @ 2.20GHz 10 Cores 20 Threads (Hyper-Threading is enabled).<br>2- Two Intel Ethernet 10Gb 2P X520 adapters configured as a bond interface (maximum traffic is 20Gb).<br>3- Single DDR4 Memory 32GB 2666 MHz.</p><p>The following figure describes the network connectivity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3GWJjxWYQ9kgh5XwE8x9A.jpeg" /></figure><p>The figure describes a typical setup where services and firewall are running on node 1 and DDoS traffic is generated by multiple sources in this case node 2,3 will generate DDoS UDP traffic.</p><h3>Implementation</h3><p>To create enough traffic so that the CPU utilization of node 1 reaches 100%, a large number of nodes is required to generate enough traffic and since there are only two nodes that will generate the traffic and mimic a DDoS attack, it is more reasonable to get the number of dropped packets per second when the CPU utilization of only single core reaches 100%. Moreover, this can be achieved using Receive Side Scaling (RSS) and Intel Ethernet Flow Director.</p><h4>Receive Side Scaling (RSS)</h4><p>When the network card receives a packet, it will be forwarded to one of the Rx queues to be transferred to the memory using Direct Memory Access (DMA) and then processed by the corresponding CPU core. RSS is a technique that is responsible for determining which Rx queue the packet will be forwarded to. RSS is implemented by using a hash table that resides in the NIC’s hardware and the key of the hash function (Toeplitz hash function) which consists of the request source IP address, destination IP address, source port, and destination port. According to the result of the hash function, the packet will be forwarded to one of the Rx queues. Following this approach, the NIC can approximately distribute the traffic evenly to the RX queues and allow it to scale linearly by only increasing the number of RX queues. Some advanced network cards support RSS filters, allowing to write rules to direct traffic to specific Rx queues. <strong>Intel Ethernet Flow Director </strong>is a feature that is supported by<strong> </strong>most advanced Intel NICs which uses RSS filters to steer packets to Rx queues based on predefined rules. For instance, packets with a specific source IP address can be forwarded to a specific Rx queue.</p><h3>Configuration</h3><p>The following steps will describe the required configuration of node 1:</p><p>1- Check if the <strong>Intel Ethernet Flow Director </strong>is enabled using the following command:</p><pre>[root@netfilter1 ~]# ethtool --show-features ens2f0 | grep ntuple<br>ntuple-filters: on<br>[root@netfilter1 ~]# ethtool --show-features ens2f1 | grep ntuple<br>ntuple-filters: on</pre><blockquote>Note: If the ntuple-filters feature is followed by <em>off</em> or <em>on</em>, Intel Ethernet FD is supported by the network adapter. However, if the ntuple-filters feature is followed by <em>off [fixed]</em>, then Intel Ethernet FD is not supported. The following command can be used to enable it:</blockquote><pre>ethtool --features &lt;ifName&gt; ntuple-filters on</pre><p>2- Redirect all the UDP packets from node 2,3 to Rx queue number 1:</p><pre>[root@netfilter1 ~]# ethtool --config-ntuple ens2f0  flow-type udp4 src-ip 100.2.2.5 action 1<br>Added rule with ID 2045<br>[root@netfilter1 ~]# ethtool --config-ntuple ens2f0  flow-type udp4 src-ip 100.2.2.6 action 1<br>Added rule with ID 2044<br>[root@netfilter1 ~]# ethtool --config-ntuple ens2f1  flow-type udp4 src-ip 100.2.2.5 action 1<br>Added rule with ID 2045<br>[root@netfilter1 ~]# ethtool --config-ntuple ens2f1  flow-type udp4 src-ip 100.2.2.6 action 1<br>Added rule with ID 2044</pre><p>Making sure that rules are correctly added for both network interfaces</p><pre>[root@netfilter1 ~]# ethtool --show-ntuple ens2f0<br>20 RX rings available<br>Total 2 rules<br>Filter: 2044<br> Rule Type: UDP over IPv4<br> Src IP addr: 100.2.2.6 mask: 0.0.0.0<br> Dest IP addr: 0.0.0.0 mask: 255.255.255.255<br> TOS: 0x0 mask: 0xff<br> Src port: 0 mask: 0xffff<br> Dest port: 0 mask: 0xffff<br> VLAN EtherType: 0x0 mask: 0xffff<br> VLAN: 0x0 mask: 0xffff<br> User-defined: 0x0 mask: 0xffffffffffffffff<br> Action: Direct to queue 1<br><br>Filter: 2045<br> Rule Type: UDP over IPv4<br> Src IP addr: 100.2.2.5 mask: 0.0.0.0<br> Dest IP addr: 0.0.0.0 mask: 255.255.255.255<br> TOS: 0x0 mask: 0xff<br> Src port: 0 mask: 0xffff<br> Dest port: 0 mask: 0xffff<br> VLAN EtherType: 0x0 mask: 0xffff<br> VLAN: 0x0 mask: 0xffff<br> User-defined: 0x0 mask: 0xffffffffffffffff<br> Action: Direct to queue 1</pre><p>3- Stop the IRQ balance service to manually specify which CPU core handles the Rx queue 1 packets.</p><pre>systemctl stop irqbalance.service</pre><p>4- The <a href="https://gist.github.com/SaveTheRbtz/8875474">set_irq_affinity.sh</a> script can be used to map each Rx queue to the corresponding CPU core automatically:</p><pre>./set_irq_affinity.sh all ens2f0<br>./set_irq_affinity.sh all ens2f1</pre><p>The set_irq_affinity script will make sure that every single CPU core will process the packets from a single Rx queue of the network card. This means CPU core 1 will respond to the interrupt requests from the Rx queue 1 of both network cards (ens2f0,ens2f1). Therefore, to ensure the configuration is correct, The following command can be used to get the interrupt numbers of the network card queues</p><pre>[root@netfilter1 ~]# cat /proc/interrupts | grep &#39;ens2f.-TxRx&#39; | awk &#39;{ print $1,$NF }&#39;<br>61: ens2f0-TxRx-0<br>62: ens2f0-TxRx-1<br>63: ens2f0-TxRx-2<br>64: ens2f0-TxRx-3<br>65: ens2f0-TxRx-4<br>66: ens2f0-TxRx-5<br>67: ens2f0-TxRx-6<br>68: ens2f0-TxRx-7<br>69: ens2f0-TxRx-8<br>70: ens2f0-TxRx-9<br>71: ens2f0-TxRx-10<br>72: ens2f0-TxRx-11<br>73: ens2f0-TxRx-12<br>74: ens2f0-TxRx-13<br>75: ens2f0-TxRx-14<br>76: ens2f0-TxRx-15<br>77: ens2f0-TxRx-16<br>78: ens2f0-TxRx-17<br>79: ens2f0-TxRx-18<br>80: ens2f0-TxRx-19<br>83: ens2f1-TxRx-0<br>84: ens2f1-TxRx-1<br>85: ens2f1-TxRx-2<br>86: ens2f1-TxRx-3<br>87: ens2f1-TxRx-4<br>88: ens2f1-TxRx-5<br>89: ens2f1-TxRx-6<br>90: ens2f1-TxRx-7<br>91: ens2f1-TxRx-8<br>92: ens2f1-TxRx-9<br>93: ens2f1-TxRx-10<br>94: ens2f1-TxRx-11<br>95: ens2f1-TxRx-12<br>96: ens2f1-TxRx-13<br>97: ens2f1-TxRx-14<br>98: ens2f1-TxRx-15<br>99: ens2f1-TxRx-16<br>100: ens2f1-TxRx-17<br>101: ens2f1-TxRx-18<br>102: ens2f1-TxRx-19</pre><p>Since interrupts start from 61 to 102, the following command is used to get the SMP affinity of the interrupts:</p><pre>[root@netfilter1 ~]# for i in {61..102}; do cat /proc/irq/$i/smp_affinity;done<br>00001<br>00002<br>00004<br>00008<br>00010<br>00020<br>00040<br>00080<br>00100<br>00200<br>00400<br>00800<br>01000<br>02000<br>04000<br>08000<br>10000<br>20000<br>40000<br>80000<br>fffff //this can be ignored because interrupt 81 it does not belogs to the network card<br>cat: /proc/irq/82/smp_affinity: No such file or directory //this can be ignored<br>00001<br>00002<br>00004<br>00008<br>00010<br>00020<br>00040<br>00080<br>00100<br>00200<br>00400<br>00800<br>01000<br>02000<br>04000<br>08000<br>10000<br>20000<br>40000<br>80000</pre><p>From the output of the command, the SMP affinity (interrupt 62 and 84) of the Rx queue 1 of both interfaces have the value of 00002 and when converted to binary will yield “0000 0000 0000 0000 0010” which means that CPU core 1 will be responsible for handling the interrupts of Rx queue 1 of both interfaces (ens2f0,ens2f1).</p><blockquote>It is crucial to mention that the same CPU core that is responsible for handling the interrupt requests of the Rx queue, will be used to process the packet in the Linux kernel’s network stack.</blockquote><p>For node 2,3 there is no special configuration is required, just the hping3 command needs to be installed and used as follows:</p><pre>timeout 30 hping3 --flood --destport 53 --udp 100.2.2.4</pre><h3>Results</h3><p>The following table includes the benchmark results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yK_yhoJnpJefUDCOHHsfmQ.png" /></figure><p>The iptables input chain could not cope with the huge number of received packets even if there are only two rules in the input chain. Accordingly, over 9 million packets were overwritten at the network card Rx queue or the receive ring buffer. On the other hand, <a href="https://medium.com/@ahsifer/introducing-goxdp-utilizing-the-power-of-xdp-for-advanced-linux-firewall-07de694310da">GoXDP</a> with native mode could achieve high performance with only 15% CPU utilization during the benchmark which can be ideal for DDoS mitigation systems.</p><h3>Conclusion</h3><p>Linux iptables can be ideal for packet processing and filtering but it can achieve poor performance on heavy load, especially in case of DDoS attacks. Therefore, Linux XDP introduces a new approach for packet filtering by processing packets at the network card’s driver (native mode) and before <strong>sk_buff</strong> is created which provides huge performance gain.</p><h3>Resources</h3><p><a href="https://github.com/ahsifer/goxdp">https://github.com/ahsifer/goxdp</a><br><a href="https://www.kernel.org/doc/Documentation/networking/scaling.txt">https://www.kernel.org/doc/Documentation/networking/scaling.txt</a><br><a href="https://www.intel.com/content/www/us/en/developer/articles/training/setting-up-intel-ethernet-flow-director.html">https://www.intel.com/content/www/us/en/developer/articles/training/setting-up-intel-ethernet-flow-director.html</a><br><a href="https://www.tigera.io/learn/guides/ebpf/ebpf-xdp/">https://www.tigera.io/learn/guides/ebpf/ebpf-xdp/</a><br><a href="https://www.flaticon.com/free-icon/hub_984448?related_id=984448">https://www.flaticon.com</a><br><a href="https://medium.com/@ahsifer/introducing-goxdp-utilizing-the-power-of-xdp-for-advanced-linux-firewall-07de694310da">https://medium.com/@ahsifer/introducing-goxdp-utilizing-the-power-of-xdp-for-advanced-linux-firewall-07de694310da</a></p><p>Thank you for reading my article. I hope you find it informative and helpful. If you enjoy the article and would like to support my work, follow me or you can buy me a coffee at <a href="https://www.buymeacoffee.com/ahsifer">https://www.buymeacoffee.com/ahsifer.</a> Your support is greatly appreciated</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4846ef6ae482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing GoXDP: Utilizing the Power of XDP for Advanced Linux Firewall]]></title>
            <link>https://medium.com/@ahsifer/introducing-goxdp-utilizing-the-power-of-xdp-for-advanced-linux-firewall-07de694310da?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/07de694310da</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ebpf]]></category>
            <category><![CDATA[xdp]]></category>
            <category><![CDATA[firewall]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 21:23:17 GMT</pubDate>
            <atom:updated>2024-03-23T21:45:44.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cgG4i-a3XyDX-oeZE5Atg.png" /></figure><p><a href="https://github.com/ahsifer/goxdp"><strong>GoXDP</strong></a> is a simple and powerful XDP filter with kernel-space code built with C and user-space code built with Golang that utilizes the power of the longest prefix matching (LPM) algorithm to drop packets from specific subnets and IP addresses with predefined timeouts. Also, interacting with GoXDP can be through the RestfulAPI or the CLI client commands. GoXDP introduces the following features:</p><ul><li>A CLI tool for interacting with GoXDP service used for various operations including (attaching or detaching XDP code to/from the network interface, blocking IP address, showing statistics, etc)</li><li>A Rest API interface to interact with GoXDP to ease the automation processes.</li><li>Blocking single IP addresses or subnets with timeout.</li><li>Statistics about the number of blocked packets per IP address.</li></ul><h3>Installation</h3><p>Download the GoXDP binary from the GitHub repository from this <a href="https://github.com/ahsifer/goxdp/releases/tag/v2.1.0">link</a> then run the GoXDP service using the following command:</p><pre>goxdp server -privateIP=127.0.0.1</pre><p>Or using docker:</p><pre>  docker run -d --network host --name goxdp --privileged --restart always ahsifer/goxdp:2.1 server -privateIP=127.0.0.1</pre><blockquote>Note: the -privateIP parameter is the IP address that GoXDP will listen to that is used by the CLI tool and RestAPI http requests.</blockquote><h3>GoXDP Operations</h3><p>1- Load XDP code to the interfaces</p><pre>[root@netfilter1 ~]# goxdp client --action=load --interfaces=ens2f0 --mode=skb<br>XDP Program loaded successfully<br>[root@netfilter1 ~]# goxdp client --action=load --interfaces=ens2f1 --mode=skb<br>XDP Program loaded successfully</pre><p>2- Blocking IP address or subnet with or without timeout</p><p>The following command will block the 100.2.2.0/24 forever.</p><pre>[root@netfilter1 ~]# goxdp client --action=block --src=100.2.2.0/24<br>src is blocked successfully</pre><blockquote>Note: /32 prefix can be used in case of blocking single IP address.</blockquote><p>To block an IP address or subnet with a timeout (500 seconds)</p><pre>[root@netfilter1 ~]# goxdp client --action=block --src=100.2.2.0/24 --timeout=500<br>src is blocked successfully</pre><p>3- Show the status of the blocked IP addresses and subnets:</p><pre>[root@netfilter1 ~]# goxdp client -action=status<br>Loaded Interfaces are:<br> 1- ens2f0<br> 2- ens2f1<br><br>Blocked IP address are:<br> 1- 100.2.2.0/24<br><br>Filtered IP addresses&#39; timeouts:<br> IP Address             Timeout             Remaining Time<br> 1- 100.2.2.0/24   2024-03-24 13:57:07          497s<br><br>Filtered IP addresses&#39; status:<br> IP Address     Rx_count   Bytes_dropped<br> 1- 100.2.2.6   15173232   849700992<br> 2- 100.2.2.5   16808693   941286808</pre><p>4- Unblock the IP address or subnet</p><pre>[root@netfilter1 ~]# goxdp client --action=allow --src=100.2.2.0/24<br>src is allowed successfully</pre><p>5- Unload the XDP code from the interface</p><pre>[root@netfilter1 ~]# goxdp client --action=unload --interfaces=ens2f1<br>XDP Program unloaded successfully to ens2f1<br>[root@netfilter1 ~]# goxdp client --action=unload --interfaces=ens2f0<br>XDP Program unloaded successfully to ens2f0</pre><p>Also, all the previous operations can be done using Rest API requests. Please consider visiting the <a href="http://github.com/ahsifer/goxdp">GitHub</a> repository for the full documentation.</p><h3>Conclusion</h3><p>GoXDP provides the capability of blocking IP addresses and subnets with timeouts. Utilizing the power of Linux XDP by attaching the eBPF code to the network card’s driver and dropping the packets, makes it an ideal solution in DDoS mitigation systems.</p><h3>Further reading</h3><p><a href="https://medium.com/@ahsifer/iptables-vs-goxdp-the-ultimate-packet-filtering-benchmark-setup-and-results-4846ef6ae482">iptables vs. GoXDP: The Ultimate Packet Filtering Benchmark Setup and Results</a></p><h3>Resources</h3><ul><li><a href="https://github.com/ahsifer/goxdp">GitHub - ahsifer/goxdp: This repository includes the source code of GoXDP firewall</a></li><li><a href="https://blog.cloudflare.com/l4drop-xdp-ebpf-based-ddos-mitigations/">L4Drop: XDP DDoS Mitigations</a></li><li><a href="https://github.com/cilium/ebpf">GitHub - cilium/ebpf: ebpf-go is a pure-Go library to read, modify and load eBPF programs and attach them to various hooks in the Linux kernel.</a></li></ul><p>Thank you for reading my article on GoXDP. I hope you find it informative and helpful. If you enjoy the article and would like to support my work, follow me or you can buy me a coffee at <a href="https://www.buymeacoffee.com/ahsifer">https://www.buymeacoffee.com/ahsifer.</a> Your support is greatly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07de694310da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seaweedfs Containerized Cluster Deployment with Fuse Mount Client]]></title>
            <link>https://medium.com/@ahsifer/seaweedfs-containerized-cluster-deployment-with-fuse-mount-client-1a19b5a3b713?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a19b5a3b713</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[distributed-storage]]></category>
            <category><![CDATA[system-administration]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Sat, 28 Oct 2023 17:13:02 GMT</pubDate>
            <atom:updated>2023-12-26T21:29:15.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*7OUY-1f2GxvNu4Fl.png" /></figure><p>SeaweedFS is a distributed storage system for blobs, objects, and files with predictable low latency with O(1) disk seek (Single disk read operation required to read the requested data from the storage).</p><p>I’ve covered the basics of Seaweedfs in my previous <a href="https://medium.com/@ahsifer/seaweedfs-25640728775c">article</a>, so here I’ll go into more detail about how to set up a full seaweedfs cluster.</p><p><strong>Cluster Setup</strong></p><p>The proposed cluster consists of 10 nodes (Virtual Machines each single one with 4 CPU cores and 4GB RAM):</p><ol><li>3 master servers for high availability (10.4.4.11,10.4.4.25,10.4.4.38).</li><li>3 volume servers and each server has a 100 GB disk for data. (10.4.4.40,10.4.4.61,10.4.4.64).</li><li>3 filer servers (10.4.4.66,10.4.4.77,10.4.4.73).</li><li>1 client server (10.4.4.75).</li></ol><p>The following diagram describes cluster components and their connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8jwMbXkXRz8e3rcEvIaAw.png" /></figure><p><strong>Setup Master Servers</strong></p><p>The following docker run command can be used to start the master service</p><pre>docker run -d --name seaweed-master --network host --restart always -v /mnt/metadata:/mnt/metadata:rw --entrypoint /usr/bin/weed chrislusf/seaweedfs:3.55 -logtostderr=true master -mdir=/mnt/metadata -peers=10.4.4.11:9333,10.4.4.25:9333,10.4.4.38:9333 -ip=10.4.4.11 -port=9333 -volumeSizeLimitMB=4096 -metricsPort=9999 -volumePreallocate</pre><blockquote>Note: The same command can be used to set up the remaining two masters only the -ip parameter needs to be changed.</blockquote><p>The following table describes the parameters used when creating a new master service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3pRLl0wzLtUh7lYbYFHrA.png" /></figure><blockquote>Note: Please consider using data <a href="https://github.com/seaweedfs/seaweedfs/wiki/Replication">replication</a> as seaweedfs supports it.</blockquote><p><strong>Setup Volume Servers</strong></p><p>The following docker run command is used to start the volume service.</p><pre>docker run -d --name seaweed-volume --network host --restart always -v /mnt/weed:/mnt/weed:rw --entrypoint /usr/bin/weed chrislusf/seaweedfs:3.55 -logtostderr=true volume -mserver=10.4.4.11:9333,10.4.4.25:9333,10.4.4.38:9333 -ip=10.4.4.40 -port=8080 -dir=/mnt/weed/data -dir.idx=/mnt/weed/metadata -idleTimeout=60 -index=memory -max=0 -readMode=proxy -metricsPort=9999 -hasSlowRead=true -readBufferSizeMB=64 -concurrentDownloadLimitMB=10000 –concurrentUploadLimitMB=10000</pre><blockquote>Note: The same command is used to set up the other two volume servers with different -ip parameters.</blockquote><p>The following table describes the parameters used when creating a new volume service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfbvktZH2dYbwe9Ip9BSog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lRmuiCY6I570TfIDVNCIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCVco15_EvMu5MdGuRB1pQ.png" /></figure><p>The web page of one of the masters (like <a href="http://10.4.4.11:9333/">http://10.4.4.11:9333</a>) should be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xem7npT9Vtt5UHpTfP0nWA.png" /></figure><p><strong>Setup Filer Servers</strong></p><p>Create a filer store configuration file at /etc/seaweedfs/filer.toml with the following data</p><pre>[leveldb2]<br>enabled = true<br>dir = &quot;/mnt/weed/metadata&quot;</pre><p>The following docker run command can be used to set up the filer servers</p><pre>docker run -d --name seaweed-filer --network host --restart always -v /mnt/weed/metadata:/mnt/weed/metadata:rw -v /etc/seaweedfs:/etc/seaweedfs:rw --entrypoint /usr/bin/weed chrislusf/seaweedfs:3.55 -logtostderr=true filer -master=10.4.4.11:9333,10.4.4.25:9333,10.4.4.38:9333 -ip=10.4.4.66 -port=8888 -ui.deleteDir=false -maxMB=4 -metricsPort=9999 -concurrentUploadLimitMB=10000 -downloadMaxMBps=100</pre><blockquote>Note: The same command with a different -ip parameter is used to setup the other filer nodes.</blockquote><blockquote>Note: When the filer container start it will read the filer.toml configuration file and will store levelDB files in /mnt/weed/metadata.</blockquote><p>The following table describes the parameters used when creating a new filer service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVeenz-K5lQRlJgP_n0rHQ.png" /></figure><p>Then we need to create a new folder named <em>data</em> in the filer service by opening the web page of any filer nodes like <a href="http://10.4.4.66:8888/">http://10.4.4.66:8888/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS1jU6F6nBnZecXmrDJ0-A.png" /></figure><p><strong>Setup Client Fuse Mount</strong></p><p>To set up Fuse Mount, the <em>weed</em> binary should be downloaded from this <a href="https://github.com/seaweedfs/seaweedfs/releases">link</a> and transferred to<em> /usr/sbin</em> directory then one of the following commands is used to mount the cluster.</p><p>Mounting the cluster using the weed mount command</p><pre>weed mount -filer=10.4.4.66:8888,10.4.4.77:8888,10.4.4.73:8888 -filer.path=/data -dir=/mnt/weedcluster -cacheCapacityMB=4000 -cacheDir=/tmp -chunkSizeLimitMB=4 -volumeServerAccess=direct</pre><p>Or using the Linux mount command</p><pre>mount -t fuse./usr/sbin/weed fuse /mnt/weedcluster -o &quot;filer=&#39;10.4.4.66:8888,10.4.4.77:8888,10.4.4.73:8888&#39;,filer.path=/data,cacheCapacityMB=4000,cacheDir=/tmp,chunkSizeLimitMB=4,volumeServerAccess=direct&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hyyYPWvuyj-_sTI8s844-g.png" /></figure><p>It is preferred to use the weed mount command rather than using Linux mount because the weed mount is designed to be prone to errors so it will try to reconnect to the filer servers if there is any error or connectivity issues. Therefore, a Systemd service can be created for the weed mount command as shown below</p><ol><li>Create /etc/systemd/system/seaweedfs-mount.service file with the following contents</li></ol><pre>[Unit]<br>Description=SeaweedFS FUSE Mount Service<br>After=network-online.target<br>[Service]<br>Type=simple<br>ExecStart=/usr/sbin/weed mount -filer=10.4.4.66:8888,10.4.4.77:8888,10.4.4.73:8888 -filer.path=/data -dir=/mnt/weedcluster -cacheCapacityMB=4000 -cacheDir=/tmp -chunkSizeLimitMB=4 -volumeServerAccess=direct<br>Restart=on-failure<br>RestartSec=5s<br>[Install]<br>WantedBy=multi-user.target</pre><p>2. Tell systemd to reread configuration files using the following command</p><pre>systemctl daemon-reload</pre><p>3. Enable and start the Seaweedfs mount service using the following command</p><pre>systemctl enable seaweedfs-mount.service --now</pre><p>Running the following command will show the mounted directory</p><pre>df -Th | grep fuse<br>10.4.4.66:8888+10.4.4.77:8888+10.4.4.73:8888:/data fuse.seaweedfs  298G  0G  298G   0% /mnt/weedcluster</pre><p><strong>Benchmark Results</strong></p><p>Running the following command from the client node (10.4.4.75)</p><pre>[root@ahsifer ~]# weed benchmark -c 256 -size 1024 -master=10.4.4.11:9333<br>This is SeaweedFS version 30GB 3.55 7eafa3420b8e5ae83c8873cddd03ded90a0fc921 linux amd64<br>.<br>------------ Writing Benchmark ----------<br>Completed 45392 of 1048576 requests, 4.3% 45391.0/s 45.7MB/s<br>Completed 94652 of 1048576 requests, 9.0% 49260.6/s 49.6MB/s<br>Completed 145662 of 1048576 requests, 13.9% 51009.6/s 51.3MB/s<br>Completed 195739 of 1048576 requests, 18.7% 50077.8/s 50.4MB/s<br>Completed 245994 of 1048576 requests, 23.5% 50254.9/s 50.6MB/s<br>Completed 296150 of 1048576 requests, 28.2% 49958.9/s 50.3MB/s<br>Completed 347678 of 1048576 requests, 33.2% 51732.1/s 52.1MB/s<br>Completed 398312 of 1048576 requests, 38.0% 50634.1/s 51.0MB/s<br>Completed 449784 of 1048576 requests, 42.9% 51470.9/s 51.8MB/s<br>Completed 499079 of 1048576 requests, 47.6% 49295.5/s 49.6MB/s<br>Completed 547636 of 1048576 requests, 52.2% 48556.4/s 48.9MB/s<br>Completed 597110 of 1048576 requests, 56.9% 49475.1/s 49.8MB/s<br>Completed 647122 of 1048576 requests, 61.7% 50012.0/s 50.3MB/s<br>Completed 698203 of 1048576 requests, 66.6% 51080.0/s 51.4MB/s<br>Completed 748406 of 1048576 requests, 71.4% 50204.0/s 50.5MB/s<br>Completed 798056 of 1048576 requests, 76.1% 49648.7/s 50.0MB/s<br>Completed 847004 of 1048576 requests, 80.8% 48949.2/s 49.3MB/s<br>Completed 897190 of 1048576 requests, 85.6% 50185.8/s 50.5MB/s<br>Completed 946844 of 1048576 requests, 90.3% 49654.2/s 50.0MB/s<br>Completed 996512 of 1048576 requests, 95.0% 49667.7/s 50.0MB/s<br>Completed 1046786 of 1048576 requests, 99.8% 50273.8/s 50.6MB/s<br><br>Concurrency Level:      256<br>Time taken for tests:   21.037 seconds<br>Completed requests:      1048576<br>Failed requests:        0<br>Total transferred:      1106754341 bytes<br>Requests per second:    49844.67 [#/sec]<br>Transfer rate:          51377.16 [Kbytes/sec]<br><br>Connection Times (ms)<br>              min      avg        max      std<br>Total:        0.5      4.6       21.2      2.5<br><br>Percentage of the requests served within a certain time (ms)<br>   50%      3.7 ms<br>   66%      4.8 ms<br>   75%      6.2 ms<br>   80%      7.0 ms<br>   90%      8.4 ms<br>   95%      9.4 ms<br>   98%     10.8 ms<br>   99%     12.0 ms<br>  100%     21.2 ms<br><br>------------ Randomly Reading Benchmark ----------<br>Completed 112666 of 1048576 requests, 10.7% 112666.0/s 113.4MB/s<br>Completed 240413 of 1048576 requests, 22.9% 127746.8/s 128.6MB/s<br>Completed 369598 of 1048576 requests, 35.2% 129181.5/s 130.0MB/s<br>Completed 501998 of 1048576 requests, 47.9% 132401.1/s 133.3MB/s<br>Completed 634054 of 1048576 requests, 60.5% 132058.1/s 132.9MB/s<br>Completed 763654 of 1048576 requests, 72.8% 129599.8/s 130.5MB/s<br>Completed 892888 of 1048576 requests, 85.2% 129234.7/s 130.1MB/s<br>Completed 1022279 of 1048576 requests, 97.5% 129389.8/s 130.2MB/s<br><br>Concurrency Level:      256<br>Time taken for tests:   8.194 seconds<br>Completed requests:      1048576<br>Failed requests:        0<br>Total transferred:      1106767881 bytes<br>Requests per second:    127962.11 [#/sec]<br>Transfer rate:          131897.95 [Kbytes/sec]<br><br>Connection Times (ms)<br>              min      avg        max      std<br>Total:        0.0      1.3       20.6      1.5<br><br>Percentage of the requests served within a certain time (ms)<br>   50%      0.9 ms<br>   66%      1.1 ms<br>   75%      1.3 ms<br>   80%      1.5 ms<br>   90%      2.0 ms<br>   95%      3.3 ms<br>   98%      6.6 ms<br>   99%      9.4 ms<br>  100%     20.6 ms</pre><p>Then consider deleting the benchmark collection using the following curl command</p><pre>curl -X GET http://10.4.4.11:9333/col/delete?collection=benchmark</pre><blockquote>Note: Increasing the number of the concurrent connections to 256, it seems the client node was reaching 100% CPU utilization during the weed benchmark command and this definitely has effecet on read and write performance.</blockquote><p>Benchmark results using the FIO command</p><ol><li>Random write</li></ol><pre>[root@ahsifer ~]# fio --name=rand-write   --rw=randwrite --filename=/mnt/weedcluster/randwrite.bin  --refill_buffers --bs=4K --size=100M  --numjobs=16  -group_reporting -direct=1 -ioengine=libaio<br>rand-write: (g=0): rw=randwrite, bs=(R) 4096B-4096B, (W) 4096B-4096B, (T) 4096B-4096B, ioengine=libaio, iodepth=1<br>...<br>fio-3.19<br>Starting 16 processes<br>Jobs: 2 (f=2): [_(4),f(1),w(1),_(10)][97.1%][w=13.0MiB/s][w=3335 IOPS][eta 00m:01s]                   <br>rand-write: (groupid=0, jobs=16): err= 0: pid=80837: Sat Oct 28 17:32:49 2023<br>  write: IOPS=12.7k, BW=49.7MiB/s (52.1MB/s)(1600MiB/32202msec); 0 zone resets<br>    slat (usec): min=30, max=753328, avg=1135.12, stdev=6120.48<br>    clat (nsec): min=284, max=28972, avg=491.55, stdev=363.44<br>     lat (usec): min=30, max=753332, avg=1135.81, stdev=6120.66<br>    clat percentiles (nsec):<br>     |  1.00th=[  302],  5.00th=[  306], 10.00th=[  310], 20.00th=[  318],<br>     | 30.00th=[  322], 40.00th=[  330], 50.00th=[  342], 60.00th=[  358],<br>     | 70.00th=[  410], 80.00th=[  628], 90.00th=[  892], 95.00th=[ 1272],<br>     | 99.00th=[ 1720], 99.50th=[ 1880], 99.90th=[ 2512], 99.95th=[ 5216],<br>     | 99.99th=[ 8512]<br>   bw (  KiB/s): min=11851, max=127387, per=100.00%, avg=56670.71, stdev=1381.39, samples=911<br>   iops        : min= 2961, max=31846, avg=14167.47, stdev=345.35, samples=911<br>  lat (nsec)   : 500=75.17%, 750=10.76%, 1000=5.76%<br>  lat (usec)   : 2=8.01%, 4=0.23%, 10=0.06%, 20=0.01%, 50=0.01%<br>  cpu          : usr=0.15%, sys=1.38%, ctx=1227450, majf=1, minf=177<br>  IO depths    : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, &gt;=64=0.0%<br>     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     issued rwts: total=0,409600,0,0 short=0,0,0,0 dropped=0,0,0,0<br>     latency   : target=0, window=0, percentile=100.00%, depth=1<br><br>Run status group 0 (all jobs):<br>  WRITE: bw=49.7MiB/s (52.1MB/s), 49.7MiB/s-49.7MiB/s (52.1MB/s-52.1MB/s), io=1600MiB (1678MB), run=32202-32202msec</pre><p>2. Random Read</p><pre>[root@ahsifer ~]# fio --name=rand-read   --rw=randread --filename=/mnt/weedcluster/randwrite.bin  --refill_buffers --bs=4K --size=100M  --numjobs=16  -group_reporting -direct=1 -ioengine=libaio<br>rand-read: (g=0): rw=randread, bs=(R) 4096B-4096B, (W) 4096B-4096B, (T) 4096B-4096B, ioengine=libaio, iodepth=1<br>...<br>fio-3.19<br>Starting 16 processes<br>Jobs: 16 (f=16): [r(16)][100.0%][r=91.4MiB/s][r=23.4k IOPS][eta 00m:00s]<br>rand-read: (groupid=0, jobs=16): err= 0: pid=80859: Sat Oct 28 17:34:23 2023<br>  read: IOPS=21.9k, BW=85.5MiB/s (89.7MB/s)(1600MiB/18711msec)<br>    slat (usec): min=20, max=30271, avg=724.39, stdev=400.12<br>    clat (nsec): min=300, max=92859, avg=983.62, stdev=1534.41<br>     lat (usec): min=21, max=30279, avg=725.89, stdev=400.13<br>    clat percentiles (nsec):<br>     |  1.00th=[  434],  5.00th=[  540], 10.00th=[  572], 20.00th=[  620],<br>     | 30.00th=[  668], 40.00th=[  724], 50.00th=[  836], 60.00th=[ 1020],<br>     | 70.00th=[ 1112], 80.00th=[ 1176], 90.00th=[ 1256], 95.00th=[ 1352],<br>     | 99.00th=[ 1656], 99.50th=[ 5792], 99.90th=[26752], 99.95th=[35072],<br>     | 99.99th=[56576]<br>   bw (  KiB/s): min=37224, max=99088, per=100.00%, avg=88103.73, stdev=917.40, samples=584<br>   iops        : min= 9306, max=24772, avg=22025.81, stdev=229.37, samples=584<br>  lat (nsec)   : 500=2.84%, 750=39.94%, 1000=15.88%<br>  lat (usec)   : 2=40.71%, 4=0.05%, 10=0.29%, 20=0.10%, 50=0.16%<br>  lat (usec)   : 100=0.02%<br>  cpu          : usr=0.42%, sys=0.96%, ctx=409744, majf=0, minf=232<br>  IO depths    : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, &gt;=64=0.0%<br>     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     issued rwts: total=409600,0,0,0 short=0,0,0,0 dropped=0,0,0,0<br>     latency   : target=0, window=0, percentile=100.00%, depth=1<br><br>Run status group 0 (all jobs):<br>   READ: bw=85.5MiB/s (89.7MB/s), 85.5MiB/s-85.5MiB/s (89.7MB/s-89.7MB/s), io=1600MiB (1678MB), run=18711-18711msec</pre><p>3. Sequential write</p><pre>[root@ahsifer ~]# fio --name=write   --rw=write --filename=/mnt/weedcluster/write.bin  --refill_buffers --bs=4K --size=100M  --numjobs=16  -group_reporting -direct=1 -ioengine=libaio<br>write: (g=0): rw=write, bs=(R) 4096B-4096B, (W) 4096B-4096B, (T) 4096B-4096B, ioengine=libaio, iodepth=1<br>...<br>fio-3.19<br>Starting 16 processes<br>Jobs: 4 (f=4): [_(3),W(1),_(4),W(1),_(4),W(2),_(1)][95.2%][w=77.2MiB/s][w=19.8k IOPS][eta 00m:01s]<br>write: (groupid=0, jobs=16): err= 0: pid=80882: Sat Oct 28 17:36:00 2023<br>  write: IOPS=21.4k, BW=83.7MiB/s (87.7MB/s)(1600MiB/19123msec); 0 zone resets<br>    slat (usec): min=28, max=114344, avg=716.80, stdev=1728.02<br>    clat (nsec): min=275, max=13066, avg=426.90, stdev=310.55<br>     lat (usec): min=28, max=114348, avg=717.41, stdev=1728.32<br>    clat percentiles (nsec):<br>     |  1.00th=[  290],  5.00th=[  298], 10.00th=[  298], 20.00th=[  302],<br>     | 30.00th=[  306], 40.00th=[  310], 50.00th=[  318], 60.00th=[  326],<br>     | 70.00th=[  346], 80.00th=[  446], 90.00th=[  716], 95.00th=[  980],<br>     | 99.00th=[ 1656], 99.50th=[ 1832], 99.90th=[ 2384], 99.95th=[ 4896],<br>     | 99.99th=[ 8032]<br>   bw (  KiB/s): min=35736, max=179200, per=100.00%, avg=87328.58, stdev=1919.70, samples=574<br>   iops        : min= 8934, max=44800, avg=21831.97, stdev=479.92, samples=574<br>  lat (nsec)   : 500=82.32%, 750=8.77%, 1000=4.13%<br>  lat (usec)   : 2=4.52%, 4=0.20%, 10=0.06%, 20=0.01%<br>  cpu          : usr=0.23%, sys=2.05%, ctx=1228093, majf=0, minf=201<br>  IO depths    : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, &gt;=64=0.0%<br>     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     issued rwts: total=0,409600,0,0 short=0,0,0,0 dropped=0,0,0,0<br>     latency   : target=0, window=0, percentile=100.00%, depth=1<br><br>Run status group 0 (all jobs):<br>  WRITE: bw=83.7MiB/s (87.7MB/s), 83.7MiB/s-83.7MiB/s (87.7MB/s-87.7MB/s), io=1600MiB (1678MB), run=19123-19123msec</pre><p>4. Sequential Read</p><pre>[root@ahsifer ~]# fio --name=read   --rw=read --filename=/mnt/weedcluster/write.bin  --refill_buffers --bs=4K --size=100M  --numjobs=16  -group_reporting -direct=1 -ioengine=libaio<br>read: (g=0): rw=read, bs=(R) 4096B-4096B, (W) 4096B-4096B, (T) 4096B-4096B, ioengine=libaio, iodepth=1<br>...<br>fio-3.19<br>Starting 16 processes<br>Jobs: 16 (f=16): [R(16)][100.0%][r=104MiB/s][r=26.5k IOPS][eta 00m:00s]<br>read: (groupid=0, jobs=16): err= 0: pid=80904: Sat Oct 28 17:36:32 2023<br>  read: IOPS=27.6k, BW=108MiB/s (113MB/s)(1600MiB/14826msec)<br>    slat (usec): min=6, max=71628, avg=576.24, stdev=533.11<br>    clat (nsec): min=256, max=76049, avg=884.42, stdev=1304.26<br>     lat (usec): min=6, max=71632, avg=577.60, stdev=533.14<br>    clat percentiles (nsec):<br>     |  1.00th=[  450],  5.00th=[  548], 10.00th=[  588], 20.00th=[  628],<br>     | 30.00th=[  668], 40.00th=[  708], 50.00th=[  756], 60.00th=[  820],<br>     | 70.00th=[  892], 80.00th=[  996], 90.00th=[ 1144], 95.00th=[ 1256],<br>     | 99.00th=[ 1592], 99.50th=[ 5472], 99.90th=[23168], 99.95th=[31872],<br>     | 99.99th=[48896]<br>   bw (  KiB/s): min=44072, max=158336, per=100.00%, avg=111112.62, stdev=1455.72, samples=464<br>   iops        : min=11018, max=39584, avg=27778.00, stdev=363.93, samples=464<br>  lat (nsec)   : 500=2.54%, 750=45.51%, 1000=32.35%<br>  lat (usec)   : 2=19.01%, 4=0.04%, 10=0.34%, 20=0.08%, 50=0.12%<br>  lat (usec)   : 100=0.01%<br>  cpu          : usr=0.46%, sys=1.13%, ctx=409754, majf=0, minf=236<br>  IO depths    : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, &gt;=64=0.0%<br>     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, &gt;=64=0.0%<br>     issued rwts: total=409600,0,0,0 short=0,0,0,0 dropped=0,0,0,0<br>     latency   : target=0, window=0, percentile=100.00%, depth=1<br><br>Run status group 0 (all jobs):<br>   READ: bw=108MiB/s (113MB/s), 108MiB/s-108MiB/s (113MB/s-113MB/s), io=1600MiB (1678MB), run=14826-14826msec</pre><p>Benchmark results are different from one setup to another because they depend on different criteria:</p><ul><li>Network bandwidth and latency: The speed at which data can be transferred over the network between the client and the volume servers which have a significant impact on read and write performance.</li><li>Storage device performance: The performance of the storage devices used in the volume servers, such as hard drives, SSDs, or NVMe drives, will also affect read and write speed.</li><li>Data distribution: The way in which data is distributed across the nodes in the distributed storage system can also impact read and write performance. For example, increasing the number of volume servers increases read and write speed especially when splitting large files into chunks and storing them in different volumes simultaneously. Also, the uneven distribution of files in the volume servers will have an impact on read and write performance.</li><li>Resources utilization: Memory and CPU utilization of cluster nodes can have a severe effect on performance. therefore, it is recommended to monitor the nodes (using Zabbix) and increase resources as required.</li></ul><h4>Summary</h4><p>A SeaweedFS cluster with 3 masters, 3 filers, and 3 volume servers is a highly scalable, available, and performant file storage solution. It can be used to store and serve a variety of file types, including images, videos, audio files, and documents. The cluster is well-suited for applications that require high throughput and low latency.</p><h4>Resources</h4><p><a href="https://github.com/seaweedfs/seaweedfs/wiki">https://github.com/seaweedfs/seaweedfs/wiki</a>.</p><p>Thank you for reading my article on SeaweedFS. I hope you find it informative and helpful. If you enjoy the article and would like to support my work, follow me or you can buy me a coffee at <a href="https://www.buymeacoffee.com/ahsifer">https://www.buymeacoffee.com/ahsifer.</a> Your support is greatly appreciated</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a19b5a3b713" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seaweedfs Distributed Storage Part 3: Features.]]></title>
            <link>https://medium.com/@ahsifer/seaweedfs-distributed-storage-part-3-features-b720b00479ca?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b720b00479ca</guid>
            <category><![CDATA[object-storage]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[distributed-storage]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 00:09:53 GMT</pubDate>
            <atom:updated>2023-09-08T00:19:25.007Z</atom:updated>
            <content:encoded><![CDATA[<p>Seaweedfs supports a wide range of interesting features:</p><ol><li><strong>Adding volume server on the fly: </strong>To increase cluster storage, a new volume server can be added effortlessly and instantaneously can be used to store new files. Also, adding more volume servers increases read and write speed.</li><li><strong>Master Failover:</strong> The master servers are coordinated by Raft protocol, to elect a leader. The leader takes over all the work of managing the volumes. All other master servers just simply forward requests to the leader. If the leader dies, another leader will be elected then all the volume servers will send their heartbeat together with their volumes’ metadata to the new leader. The new leader will take full responsibility. During the transition, there could be moments when the new leader has partial information about all volume servers. This just means those yet-to-heartbeat volume servers will not be writable temporarily.</li><li><strong>Garbage collection:</strong> A deleted file’s disk space won’t be immediately recovered if your system has recently had a lot of deletions. Volume disk utilization is monitored by a background vacuum job. The vacuum job will make the volume read-only, create a new volume with only existing files.</li><li><strong>Replication:</strong> In Seaweedfs replication is donated by the defaultReplication=ZYX parameter which is used when setting up the master servers. The three digits “ZYX” are used to define how replication is done in the cluster. Therefore, Z represents data center level replication, Y represents rack level replication, and X represents volume server level replication as shown in the following:<br>XYZ=000 then no replication, just store one copy in the cluster.<br>XYZ=001 then replicate once on the same rack.<br>XYZ=010 then replicate once on a different rack in the same data center.<br>XYZ=100 then replicate once on a different data center.<br>XYZ=200 replicate twice on two other different data centers..<br>XYZ=110 then replicate once on a different rack in the same datacenter.<br>Note: The maximum allowed value for XYZ is 999.</li><li><strong>Erasure Coding: </strong>Erasure coding is a method used to protect data against loss or corruption. It involves creating redundant pieces of data, known as parity from the original data. This redundancy allows for the recovery of lost or corrupted data by using the redundant pieces along with the remaining healthy data. In Seaweedfs, the erasure coding operation is donated by RS(K,N) formula where “K” is the number of shards that the volume will be split into and “N” is the number of parity shards. For instance, the default implemented EC in seaweedfs is RS(10,4). Therefore, a 30 GB data volume will be encoded into 14 EC shards, each shard is of size 3 GB (30 /10). Seaweedfs will try to store the shards in the volume so that it will provide the following:<br>- If the number of servers is less than 4, EC can protect against hard drive failures. <br>- If the number of servers is equal to 4, EC can protect against server failures. <br>- If the number of racks is greater than 4, EC can protect against rack failures.</li><li><strong>Store file with a TTL: </strong>Seaweedfs supports file expiration by defining TTL value after writing data to the cluster and this will make it considerable in case of content caching. However, after writing, the file content will be returned as usual if read before the TTL expiry. But if read after the TTL expiry, the file will be reported as missing, and then returns file is not found.</li><li><strong>Data Encryption:</strong> Seaweedfs can encrypt data on the volume servers with generated keys stored in the filer store. Furthermore, every file is encrypted with a different key. When reading an encrypted file the filer service will fetch the file from the volume and then decrypt and deliver the file to the client.</li><li><strong>Cloud Drive:</strong> This feature can provide the ability to mount an S3 bucket to the Seaweedfs file system (using filer service) and access the remote files through SeaweedFS. Effectively, SeaweedFS caches the files from the cloud. According to the cache size, all S3 bucket files can be cached with eviction when the cache is full. With the write-back caching mechanism all writes are done to the cache and the cache will upload or update files in the S3 bucket asynchronously. Since uploading to Amazon S3 is free, users can only pay for the storage they use. Therefore, this will lead to have the benefit of extremely fast access to the local SeaweedFS cluster and Near-Real-Time Backup to Amazon S3 with zero-cost upload network traffic.</li><li><strong>Storage Classification:</strong> Since stored data has three types: hot, warm, and cold, it would be cost-efficient to place data accordingly.SeaweedFS supports storage classification, where you can place data to customizable disk types, and provides ways to move data to different tiers.<br>=&gt; NVME =&gt; SSD =&gt; HDD =&gt; Cloud<br>=&gt; Critical=&gt; Hot =&gt;Warm =&gt; Cold<br>Seaweedfs implements this feature using volume server tagging for instance, when a new volume server is created, a –disk argument can be passed to set the disk tag as shown in the following command</li></ol><pre>weed volume -disk=ssd -port=8080 -dir=/dir/</pre><p>Then client can use fuse mount to only mount the volumes with a tag of SSD or HDD. Therefore, critical services can use the SSD volumes, and fewer critical can use the HDD volumes.</p><p>9.<strong> Tiered Storage with Cloud Tier:</strong> This feature will allow seaweedFS to move full-volume files to the cloud storage provider because cloud storage is an ideal place to store warm data. Its storage is scalable, and the cost is usually low compared to on-premises storage servers. Usually, uploading to the cloud is free which makes it ideal for cold data.</p><p>10.<strong> Images Resizing:</strong> Seaweedfs provides the ability to scale images to different resolutions as shown in the following requests to the volume server</p><pre>curl http://VolumeServerIP:8080/3/01637037d6.jpg?height=200&amp;width=200<br>curl http://VolumeServerIP:8080/3/01637037d6.jpg?height=200&amp;width=200&amp;mode=fit<br>curl http://VolumeServerIP:8080/3/01637037d6.jpg?height=200&amp;width=200&amp;mode=fill</pre><h4>Conclusion</h4><p>SeaweedFS is a distributed file system that is designed to be scalable, and easy to use. It is based on the idea of storing files in chunks that are distributed across a cluster of servers. This makes it very scalable, as more servers can be added to the cluster to increase capacity. SeaweedFS is also fault-tolerant, as it can continue to operate even if some of the servers in the cluster fail.</p><p><a href="https://medium.com/@ahsifer/seaweedfs-25640728775c">Part 1: Introduction.</a><br><a href="https://medium.com/@ahsifer/seaweedfs-distributed-storage-part-2-reading-and-writing-files-process-8c60da1a674b">Part 2: Reading and Writing Files’ Process.</a></p><h4>Resources</h4><p><a href="https://github.com/seaweedfs/seaweedfs/wiki">https://github.com/seaweedfs/seaweedfs/wiki</a>.<br><a href="https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf">https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf</a>.</p><p>Thank you for reading my article on SeaweedFS. I hope you find it informative and helpful. If you enjoy the article and would like to support my work, follow me or you can buy me a coffee at <a href="https://www.buymeacoffee.com/ahsifer">https://www.buymeacoffee.com/ahsifer.</a> Your support is greatly appreciated</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b720b00479ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seaweedfs Distributed Storage Part 2: Reading and Writing Files’ Process.]]></title>
            <link>https://medium.com/@ahsifer/seaweedfs-distributed-storage-part-2-reading-and-writing-files-process-8c60da1a674b?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c60da1a674b</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[object-storage]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[distributed-storage]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 00:06:47 GMT</pubDate>
            <atom:updated>2023-09-08T00:19:58.739Z</atom:updated>
            <content:encoded><![CDATA[<p>In Seaweedfs, two different approaches can be followed to read or write files to the cluster:</p><h4>A- Writing and Reading Files to Seaweedfs without using the Filer Service</h4><p>To write a file, the following steps need to be followed:</p><ol><li>client needs to ask the master server to know which volume server can be used to store the file as shown in the following API request to the master server.</li></ol><pre>curl http://MasterIP:9333/dir/assign<br>Response: {&quot;fid&quot;:&quot;7,016bad1bc0&quot;,&quot;url&quot;:&quot;VolumerServerIP:8080&quot;}</pre><p>2. Then client can upload the file using the following request with the file to this volume server</p><pre>Curl -F file=@/file.txt http://VolumeServerIP:8080/7,016bad1bc0</pre><ol><li>Once the file is uploaded successfully, the client needs to store the uploaded file name, volume ID, and file ID (In our case it would be file.txt, 7, 016bad1bc0) in the database so that it could be available for future read requests.</li></ol><p>The following steps can be used to access the stored file in the cluster.</p><ol><li>Client needs to query the database to fetch volume ID, file ID for the requested file. In our example, the returned data for file.txt should be (7,016bad1bc0) where 7 is volume ID and 016bad1bc0 is file ID.</li><li>Client will need to send a get request to the master node to know in which volume server volume 7 exists because volumes might be migrated between volume servers.</li></ol><pre>curl http://MasterIP:9333/dir/lookup?volumeId=7<br>Response: {&quot;volumeId&quot;:&quot;7&quot;,&quot;locations&quot;:[{&quot;url&quot;:&quot;VolumeServerIP:8080&quot;}]}</pre><ol><li>Then a final get request to the volume to fetch the file</li></ol><pre>curl http://VolumeServerIP:8080/7,016bad1bc0</pre><p>To ease the process of storing and retrieving files in the cluster seaweed team has created two services which are file and filer store.</p><h4>B- Writing and Reading Files to Seaweedfs using the Filer Service</h4><p>As mentioned before the filer service provides different entry points to the cluster one of them is the filer Web UI which allows us to download or upload files through the web. The following describes the process of writing a new file</p><ol><li>The client uploads a file to the filer using the Web UI.</li><li>The filer will ask the master to provide the volume server IP, volume ID, and file ID to store the file in the volume server. However, according to filer configuration, files might be separated into chunks and stored as separate files in the volume servers to increase read and write speed.</li><li>The filer will store returned data from the master in the filer store and sync the other filer nodes in case an embedded filer approach is used.</li><li>The filer will upload the file to the volume server.</li></ol><p>In case of accessing the file from the filer Web UI:</p><ol><li>From the Web UI, the client will press on one of the files to download it.</li><li>The filer will ask the filer store to provide Volume ID, file ID of the requested file.</li><li>The filer will pull the file from the volume servers and provide it to the user. However, if the file is chunked then the filer will pull all the chunks and then combine the chunks to form the file, and then return the requested file to the user.</li></ol><p><a href="https://medium.com/@ahsifer/seaweedfs-25640728775c">Part 1: Introduction.</a><br><a href="https://medium.com/@ahsifer/seaweedfs-distributed-storage-part-3-features-b720b00479ca">Part 3: Features.</a></p><h4>Resources</h4><p><a href="https://github.com/seaweedfs/seaweedfs/wiki">https://github.com/seaweedfs/seaweedfs/wiki</a>.<br><a href="https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf">https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf</a>.</p><p>Thank you for reading my article on SeaweedFS. I hope you find it informative and helpful. If you enjoy the article and would like to support my work, follow me or you can buy me a coffee at <a href="https://www.buymeacoffee.com/ahsifer">https://www.buymeacoffee.com/ahsifer.</a> Your support is greatly appreciated</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c60da1a674b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seaweedfs Distributed Storage Part 1: Introduction.]]></title>
            <link>https://medium.com/@ahsifer/seaweedfs-25640728775c?source=rss-67610f37affb------2</link>
            <guid isPermaLink="false">https://medium.com/p/25640728775c</guid>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[distributed-storage]]></category>
            <category><![CDATA[storage-solutions]]></category>
            <category><![CDATA[object-storage]]></category>
            <dc:creator><![CDATA[Ali Hussein Safar]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 20:12:17 GMT</pubDate>
            <atom:updated>2023-09-10T00:39:26.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*LZnqfLvpWOlpiJw4tyTaVw.png" /></figure><p>SeaweedFS is a distributed storage inspired by Facebook’s <a href="https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf">Haystack</a> photo storage system which is designed to store blobs, objects, and files with predictable low latency with O(1) disk seek (Single disk read operation required to read the requested data from the storage).</p><p><strong>How Seaweedfs Store files</strong></p><p>In the SeaweedFS cluster, files are stored in volumes located in a volume server and volume is just a large empty file with a predefined size that is used to store files. For instance, a 10 GB volume could store 10,000 files with an average size of 1 MB.</p><p><strong>The Issues that SeaweedFS tries to solve:</strong></p><ol><li><strong>File Systems Inode Disk Size Limitation: </strong>As every file in every operating system must have metadata (Also known as inode in Linux) which includes file name, path, permission, date created, date modified, and location in the disk. Some of this stored metadata is crucial, but the others waste disk size. In XFS or EXT4 file systems the default inode size is 512 bytes if <a href="https://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> is enabled which means every single file size will be the size of the file itself plus 512 bytes for inode size and this includes empty files. For instance, storing 1 million small files will require 512 MB of extra storage for the inodes only. However, this issue was resolved in Seaweedfs by storing multiple files in a single larger file (volume). Furthermore, in the seaweedfs configuration, the default volume size is 30 GB, and this means all the required metadata is only 512 bytes plus 16 bytes per file (16 bytes for file metadata in the volume like file offset location and size) stored in the volume. Therefore, storing 1 million small files will only cost 512 bytes + (1Million * 16 bytes) which approximately is equal to 16MB. This approach was helpful in the case of Facebook storage for uploaded images that hold more than 260 billion images.</li><li><strong>Required Disk Operations to Read File from the Disk:</strong> In the typical file systems including XFS and EXT4, three disk read operations or more are required to read a single file from the disk, one for the file path to inode number mapping, one for inode retrieval from the disk to the memory, and one operation for file retrieval from the disk. Seaweedfs could overcome this issue by storing files’ metadata in the memory and therefore there will be only a single read operation to the disk because memory access time is in nanoseconds and the HDD hard drive is in milliseconds.</li></ol><p><strong>Seaweedfs Cluster Components:</strong></p><p>Typical Seaweedfs Cluster consists of the following components:</p><ol><li><strong>Master Service:</strong> In other distributed file systems masters manage files stored in the storage servers (volume servers) but in SeaweedFS masters only manage volumes stored in the volume servers and the volume servers will manage the files stored in the volumes. This means the master server will only store metadata about the volumes (like volume sizes, in which volume server the volume is stored, etc.). However, storing the actual file metadata is the role of the volume servers, not the master servers. Also, the master is responsible for choosing which volume server will be used to store new files and from which volume server we can access our stored files. Also, the master server will be responsible for converting volumes to read-only once they have reached the maximum size.</li><li><strong>Volume Service:</strong> The volume servers store a bunch of volumes with each volume size 30GB (configurable). The volume service is responsible for storing many objects (files and chunks of files) efficiently in the volume. Also, storing every file metadata (file name, size, offset location on the volume, etc.) on the disk and caching them in the memory to provide fast access to them and provide O(1) disk read operation. When the master is elected as leader in the cluster, all volume servers will send every stored volume’s metadata to the newly elected master.</li><li><strong>Filer Service:</strong> Interacting with the master and volume servers to upload and download files can be a tedious task therefore Seaweedfs team has created the Filer service to provide the following:</li></ol><ul><li>connects to master servers for up-to-date volume locations, and requests for volume server IP, volume ID, and file ID during file writes.</li><li>Handling file and directory operations, such as create, delete, read, write, and rename.</li><li>Keeping track of the metadata of files and directories, such as the file ID, file size, last modified time, and access time, etc…</li><li>Communicating with the master server to keep track of the cluster state.</li><li>Logging and auditing files and directory operations.</li></ul><p>Also, it provides an entry point to access the data in different ways some of them are:</p><ul><li>HTTP entry point to upload and download files.</li><li>Read and write files directly as a local directory via FUSE mount point.</li><li>S3 compatible API.</li><li>Accesses files from Hadoop/Spark/Flink/etc.</li><li>WebDAV.</li><li>Kubernetes CSI driver.</li></ul><p>4.<strong> Filer Store Service:</strong> This is an important component that is used by the filer service to store the files metadata (like Volume ID, file ID, etc.). Also, the filer store is used to scale the filer service. There are two types of filer stores</p><ol><li>Shared: All filers will talk to shared filer store like MariaDB, Redis, Cassandra, etc. Therefore, this option will ease the scalability of filer servers since all the filers will use the same shared database.</li><li>Embedded: Every single filer will store metadata locally using LevelDB which is “in disk a key-value store with memory cache” designed by Google. In the embedded filer store all the metadata changes are propagated to all the other filers if they exist. This will make sure that all filers are updated with the latest metadata changes.</li></ol><p>5. <strong>S3 service:</strong> This is an optional service that offers S3 buckets designed in the AWS style. It may be launched alone or simultaneously with the filer.</p><p>The following diagram will show cluster components and connections</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*3x-gtenv_-OUSny0J93rSQ.jpeg" /><figcaption>Seaweedfs Cluster Components</figcaption></figure><p>Note: The connection between the client and the volume server is optional. However, it can be used when the client mounts the cluster using a Fuse mount.</p><p><a href="https://medium.com/@ahsifer/seaweedfs-distributed-storage-part-2-reading-and-writing-files-process-8c60da1a674b">Part 2: Reading and Writing Files’ Process.</a><br><a href="https://medium.com/@ahsifer/seaweedfs-distributed-storage-part-3-features-b720b00479ca">Part 3: Features.</a></p><h4>Resources</h4><p><a href="https://github.com/seaweedfs/seaweedfs/wiki">https://github.com/seaweedfs/seaweedfs/wiki</a>.<br><a href="https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf">https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf</a>.</p><p>Thank you for reading my article on SeaweedFS. I hope you find it informative and helpful. If you enjoy the article and would like to support my work, follow me or you can buy me a coffee at <a href="https://www.buymeacoffee.com/ahsifer">https://www.buymeacoffee.com/ahsifer.</a> Your support is greatly appreciated</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25640728775c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>