<?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[Marionete - Medium]]></title>
        <description><![CDATA[innovating at the edge of what‘s possible - Medium]]></description>
        <link>https://medium.com/marionete?source=rss----fe96a436cca7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Marionete - Medium</title>
            <link>https://medium.com/marionete?source=rss----fe96a436cca7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:08:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/marionete" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[PART 2/2] Unveiling the Path: Tracing Linked Chains in Databases using Recursive CTEs in SQL]]></title>
            <link>https://medium.com/marionete/part-2-2-unveiling-the-path-tracing-linked-chains-in-databases-using-recursive-ctes-in-sql-0f32d1331500?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/0f32d1331500</guid>
            <category><![CDATA[cte]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Diego Rodrigues]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 15:58:06 GMT</pubDate>
            <atom:updated>2026-01-07T15:58:05.648Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part of the 2-part tutorial on using Recursive Common Table Expressions (CTEs) in SQL. In this article, we present a problem to find the origin of a chain of linked records in a database table. The linked records can be traces of log messages or even the hierarchical representation of a company’s employees.</p><p><a href="https://medium.com/@dedego/200d8cbc124a">As in part one of this tutorial</a>, a hands-on workbook is available to showcase the walkthrough described in this article.</p><h3>Introducing Recursive Common Table Expressions</h3><p>A Common Table Expression (CTE) is a temporary result that can be referenced in other query statements. They are useful for breaking down complex queries into smaller pieces and making them more readable, they act as virtual tables created during the query execution, used by it, and then deleted after the query finishes.</p><p>A Recursive CTE is a special type of CTE that references itself in a <em>SELECT</em> statement, creating a recursive loop. It is useful when traversing hierarchical data structures or networks <a href="https://learnsql.com/blog/recursive-cte-sql-server/">[1]</a><a href="https://www.geeksforgeeks.org/cte-in-sql/">[2]</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlDUBUp8ZXiWSWr2K2Ue6A.png" /><figcaption>Recursive CTE behaviour</figcaption></figure><p>To define a recursive CTE:</p><ol><li>First, write the anchor step which creates the first temporary result <em>R1</em>. <em>R1</em> will be used in the next step <em>SELECT</em> query. <em>R1</em> is also added to the result table.</li><li>Next, apply the recursive step on the most recent result batch (in this case, <em>R1</em>). The result <em>R2</em> will be used in the next recursive step and is added to the result table.</li><li>Repeat the recursive step on the most recent result batch until the recursive step doesn’t generate any results.</li><li>After the recursive steps finish, select the desired results from the CTE.</li></ol><p>In the following sections, we present two problems that can be solved with recursive CTEs. The first problem implements an adaptation of the Dijkstra algorithm to find the shortest path in a graph. The second problem uses recursive CTE to discover the first record of a chain of linked records in a table.</p><p>⚠️ The examples in this article were tested using a PostgreSQL server in a Docker container. The <em>docker-compose</em> file and the SQL code used are available on <a href="https://github.com/diego-rodrigues/recursive-ctes-workboook">GitHub</a>.</p><h3>Finding the First Record in a Chain of Linked Records</h3><p>💻 <em>Hands-on workbook: </em><a href="https://github.com/diego-rodrigues/recursive-ctes-workboook/blob/main/rcte-hands-on-chains.sql"><em>rcte-hands-on-chains.sql</em></a></p><p>In this problem, consider a table where records might be linked to one another as if they were part of a record chain. The goal is to find the first record of the chain, i.e., the one record that does not have any previous record associated with it.</p><p>Each record in a table has a <em>record_id</em> and a <em>previous_record_id</em>, in case the record is linked to another one. Take the table (<em>RECORD</em>) as an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*Pao4Dt3JebJ2LUiq9o8dfw.png" /><figcaption>Records might be linked to a previous record</figcaption></figure><p>The table contains three <em>chains</em>: [0], [1 ← 2 ← 3], and [4 ↔︎ 5]. The goal is to find the origin (or the first element) of the chain, for the first two cases they should be 0 and 1, respectively. When there is a loop, as no origin record can be specified, let’s consider the record as its origin. Hence, our goal is to find the <em>CHAIN_ORIGIN</em> table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*3vIgkX4NKALADPQrVXdhpA.png" /></figure><p>To find such a table, we use a recursive CTE that will follow the <em>previous_record_id</em> from every <em>record_id</em> until it finds a <em>null</em> value, meaning there are no <em>previous_record_id</em> to follow. The structure of the CTE will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*1oHTOOpr_wU6w2w0Aqfuaw.png" /><figcaption>Structure of the recursive CTE used</figcaption></figure><p>The <em>record_id</em> field will store the <em>record_id</em>s. The <em>current_origin_record</em> and <em>previous_record_id_step</em> fields are columns used in the recursive steps to follow the chain of records. Finally, the <em>chain_sequence</em> will store the sequence of records visited.</p><p>Let’s start initialising the recursive CTE with the anchor query, which takes the rows from the record table. The <em>current_origin_record</em> and <em>previous_record_id_step</em> will be the variable columns during the execution, for now, they receive the first values of the <em>record_id</em> and its predecessor:</p><pre>-- anchor query<br>SELECT <br>    r.record_id as record_id,<br>    r.record_id as current_origin_record,<br>    r.previous_record_id as previous_record_id_step,<br>    ARRAY[r.record_id] as chain_sequence<br>FROM record r</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kMugxx2hemiI6HmGwr6vA.gif" /><figcaption>The anchor query selects the first batch of data to be used in the recursive step</figcaption></figure><p>Following the anchor query, we define the recursive step that takes every record in the previous step and follows its <em>previous_record_id_step</em> when not <em>null</em>. To avoid being in an infinite loop, another condition is added to only follow the previous id if it’s not already present in the <em>chain_sequence</em> array. The recursive step also adds the new record into the <em>chain_sequence</em> array:</p><pre>-- recursive step<br>SELECT<br>    rc.record_id,<br>    rc.previous_record_id_step,<br>    r.previous_record_id,<br>    rc.previous_record_id_step || rc.chain_sequence<br>FROM chain_origin rc<br>JOIN record r<br>    ON rc.previous_record_id_step = r.record_id<br>    AND NOT rc.previous_record_id_step = ANY(rc.chain_sequence)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhX-LcG3LbkxCrHD59YKrw.gif" /><figcaption>The first recursive step generates four new rows</figcaption></figure><p>After that, the recursive step is applied to the result of the previous step, generating one more row. Note rows with <em>record_id</em> 4 and 5 don’t generate new rows, as the values of <em>previous_record_id_step</em> are already in <em>chain_sequence</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3QhambiAG57n251OpoImA.gif" /><figcaption>The next recursive step is applied to the previous result (green rows)</figcaption></figure><p>The only row that yields new results is where <em>record_id</em> equals 3. The other rows either have <em>previous_record_id_step</em> equal to <em>null</em>, or the value is already in the <em>chain_sequence</em> (causing a loop).</p><p>Finally, one more recursion step is executed (over the yellow rows), however, it doesn’t generate any new rows. This ends the processing of the recursion. The last step is to select among all the rows the ones with the values we need.</p><p>The final selection is a <em>union</em> of two sub-queries:</p><ul><li>The first one selects all the rows where previous_record_id_step is null. The selected rows will have chains of one or more elements.</li></ul><pre>-- records in a chain<br>SELECT record_id as record_id,<br>    current_origin_record as chain_origin_id,<br>    chain_sequence as chain_sequence<br>FROM chain_origin<br>WHERE previous_record_id_step IS NULL</pre><ul><li>The second one selects one entry of all record_ids not selected in the previous query. The selected rows will be the ones where the chain doesn’t have a defined origin (loop cases).</li></ul><pre>-- records in a loop, no valid chain<br>SELECT DISTINCT record_id as record_id,<br>    record_id as chain_origin_id,<br>    ARRAY[record_id] as chain_sequence<br>FROM chain_origin a<br>WHERE NOT EXISTS (<br>    SELECT 1<br>    FROM chain_origin b<br>    WHERE b.previous_record_id_step IS NULL<br>        AND a.record_id = b.record_id<br>)</pre><p>The selection should result in the following table, finishing this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*3Tsg2Qo0qjHO3ZjVDiOcPA.png" /><figcaption>A table containing all the chains and their origin record ID</figcaption></figure><p>As showcased in <a href="https://medium.com/@dedego/200d8cbc124a">part one of this tutorial</a>, recursive CTEs are useful in databases when the data manipulated can be linked to one another, either on a chain, in hierarchical settings, or even on a graph.</p><p>This is the end of this tutorial, where we visited a solution to finding the first element of a linked chain of records in a database table. The solution presented uses a Recursive Common Table Expression, an elegant and simple way to recursively reuse data from a table in SQL.</p><h3>References</h3><p>🔗 [1] <a href="https://learnsql.com/blog/recursive-cte-sql-server/">https://learnsql.com/blog/recursive-cte-sql-server/</a><br>🔗 [2] <a href="https://www.geeksforgeeks.org/cte-in-sql/">https://www.geeksforgeeks.org/cte-in-sql/</a><br>🔀 <a href="https://github.com/diego-rodrigues/recursive-ctes-workboook">https://github.com/diego-rodrigues/recursive-ctes-workboook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f32d1331500" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/part-2-2-unveiling-the-path-tracing-linked-chains-in-databases-using-recursive-ctes-in-sql-0f32d1331500">[PART 2/2] Unveiling the Path: Tracing Linked Chains in Databases using Recursive CTEs in SQL</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[PART 1/2] Unveiling the Path: Finding Graphs Shortest Routes using Recursive CTEs in SQL]]></title>
            <link>https://medium.com/marionete/part-1-2-unveiling-the-path-finding-graphs-shortest-routes-using-recursive-ctes-in-sql-200d8cbc124a?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/200d8cbc124a</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[cte]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Diego Rodrigues]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 15:57:53 GMT</pubDate>
            <atom:updated>2026-01-07T15:57:52.287Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part one of a two-part tutorial on using Recursive Common Table Expressions (CTEs) in SQL. In this article, we present a problem to find the shortest path between two nodes in a graph, where the graph is presented as an adjacency table in a database. A walkthrough of the problem and its solution is detailed in this article, as well as a hands-on workbook, showcasing the examples described in this article.</p><h3>Introducing Recursive Common Table Expressions</h3><p>A Common Table Expression (CTE) is a temporary result that can be referenced in other query statements. They are useful for breaking down complex queries into smaller pieces and making them more readable, they act as virtual tables created during the query execution, used by it, and then deleted after the query finishes.</p><p>A Recursive CTE is a special type of CTE that references itself in a <em>SELECT</em> statement, creating a recursive loop. It is useful when traversing hierarchical data structures or networks <a href="https://learnsql.com/blog/recursive-cte-sql-server/">[1]</a><a href="https://www.geeksforgeeks.org/cte-in-sql/">[2]</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlDUBUp8ZXiWSWr2K2Ue6A.png" /><figcaption>Recursive CTE behaviour</figcaption></figure><p>To define a recursive CTE:</p><ol><li>First, write the anchor step which creates the first temporary result <em>R1</em>. <em>R1</em> will be used in the next step <em>SELECT</em> query. <em>R1</em> is also added to the result table.</li><li>Next, apply the recursive step on the most recent result batch (in this case, <em>R1</em>). The result <em>R2</em> will be used in the next recursive step and is added to the result table.</li><li>Repeat the recursive step on the most recent result batch until the recursive step doesn’t generate any results.</li><li>After the recursive steps finish, select the desired results from the CTE.</li></ol><p>In the following sections, we present two problems that can be solved with recursive CTEs. The first problem implements an adaptation of the Dijkstra algorithm to find the shortest path in a graph. The second problem uses recursive CTE to find the first record of a chain of linked records in a table.</p><p>⚠️ The examples in this article were tested using a PostgreSQL server in a Docker container. The <em>docker-compose</em> file and the SQL code used are available on <a href="https://github.com/diego-rodrigues/recursive-ctes-workboook">GitHub</a>.</p><h3>Finding the Shortest Path on a Graph</h3><p>💻 <em>Hands-on workbook: </em><a href="https://github.com/diego-rodrigues/recursive-ctes-workboook/blob/main/rcte-hands-on-shortest-path.sql"><em>rcte-hands-on-shortest-path.sql</em></a></p><p>Consider the graph below, with six vertices and directed edges among them. The same graph can be represented in a table of adjacencies, where source and target vertices (or nodes) are listed, along with their weights. The goal is to find the shortest path (less weight) between two nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pIK8p0RVootJd-LwGuUK3w.png" /><figcaption>A graph and its edges: The shortest path from 1 to 5 goes through nodes 2 and 4</figcaption></figure><p>In the example, if we want to find the shortest path from node 1 to node 5, the path goes from 1 → 2 → 4 → 5 with a total weight of 3.</p><p>The graph can be created in SQL as an adjacency table with the following code (lines 1–16):</p><pre>CREATE TABLE edge (<br>    source_node INTEGER,<br>    target_node INTEGER,<br>    weight INTEGER<br>);<br><br>INSERT INTO edge (source_node, target_node, weight)<br>VALUES<br>    (1, 2, 1),<br>    (1, 3, 2),<br>    (2, 4, 1),<br>    (3, 4, 3),<br>    (4, 5, 1),<br>    (3, 5, 4),<br>    (1, 5, 4),<br>    (6, 1, 2);</pre><p>The first step to define the recursive CTE is to create the anchor query (lines 19–22). The anchor query should select all nodes reached by a source node. The structure of the CTE is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*J-AXh29sMsVmLD61XcXXaw.png" /><figcaption>The CTE will have four columns</figcaption></figure><pre>-- Anchor query: Initialize the shortest path from the source node to immediate neighbors<br>SELECT source_node, target_node, weight, ARRAY[source_node,target_node] AS path, weight AS total_weight<br>FROM edge<br>WHERE source_node = 1</pre><p>Running the anchor query (using 1 as the <em>source_node</em>) will produce the behaviour depicted in the next animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29yzgW9ymkLDKD9oRwmyfQ.gif" /><figcaption>The anchor query selects all rows where source_node is equal to 1</figcaption></figure><p>The three records generated in the CTE (here represented by the <em>SHORTEST_PATH</em> table) will be used in the recursive step to generate new results in subsequent steps. The CTE will have three records, future records will be appended to the table using an <em>UNION ALL</em> clause:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*2Pb_Xm6ekhJyHBBJpl-xGQ.png" /></figure><p>Next, we define the recursive step (lines 27–34):</p><pre>-- Recursive query: Expand the shortest path to reach neighboring nodes<br>SELECT e.source_node,<br>       e.target_node,<br>       e.weight,<br>       sp.path || e.target_node AS path,<br>       sp.total_weight + e.weight AS total_weight<br>FROM SHORTEST_PATH sp<br>JOIN edge e <br>ON sp.target_node = e.source_node<br>WHERE NOT e.target_node = ANY(sp.path) -- Avoid cycles</pre><p>It joins the <em>SHORTEST_PATH</em> table (results from anchor query) with the <em>EDGE</em> table to generate the next set of rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0ZMimPnhJ6jUuqDwyW-Bw.gif" /><figcaption>The next recursive step uses data from the previous recursive step</figcaption></figure><p>The first recursive step finds three more rows and adds them to the CTE. Only the newest three rows will be used in the next recursive step. The following recursive step generates two new rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fYxDuWRH54q-S7OLuBPUg.gif" /><figcaption>The next recursive step uses data from the previous recursive step</figcaption></figure><p>And finally, the next recursion step doesn’t generate any new rows, ending the recursion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pNiookBvOnJUtyALTBMrw.gif" /><figcaption>The query doesn’t generate any new rows as 5 is not the source_node in any rows in the EDGE table</figcaption></figure><p>To get the shortest path, select from the CTE the paths to each node with the lowest <em>total_weight</em> value (lines 38–43):</p><pre>-- Final query: Select the shortest path to each node from the source node<br>SELECT DISTINCT ON (target_node)<br>       target_node,<br>       path,<br>       total_weight<br>FROM SHORTEST_PATH<br>ORDER BY target_node, total_weight;</pre><p>The above query should return the shortest paths starting from node 1 to every other reachable node in the graph, along with their paths, note node 6 is not reachable and thus is not present in the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*rfaVvQAOP3eh61N_6nRw_w.png" /><figcaption>Shortest paths to all reachable nodes starting from node 1</figcaption></figure><p>Recursive Common Table Expressions are useful when dealing with hierarchical or recursive data structures in databases. Other examples recursive CTEs can be used include:</p><ul><li>Organisational hierarchies</li><li>Comment Trees</li><li>Date hierarchies</li><li>Logging aggregation</li></ul><p>This is the end of part one of this tutorial, where we studied a solution to find the shortest path in a graph using recursive common table expressions, which present an elegant and efficient way to deal with hierarchical data in SQL. In the <a href="https://medium.com/@dedego/0f32d1331500#ba5d-f4e7d16f3fa5">next article of this tutorial</a>, another example is presented aiming to use a recursive CTE to solve a problem in a database.</p><h3>References</h3><p>🔗 [1] <a href="https://learnsql.com/blog/recursive-cte-sql-server/">https://learnsql.com/blog/recursive-cte-sql-server/</a><br>🔗 [2] <a href="https://www.geeksforgeeks.org/cte-in-sql/">https://www.geeksforgeeks.org/cte-in-sql/</a><br>🔀 <a href="https://github.com/diego-rodrigues/recursive-ctes-workboook">https://github.com/diego-rodrigues/recursive-ctes-workboook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=200d8cbc124a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/part-1-2-unveiling-the-path-finding-graphs-shortest-routes-using-recursive-ctes-in-sql-200d8cbc124a">[PART 1/2] Unveiling the Path: Finding Graphs Shortest Routes using Recursive CTEs in SQL</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring In‑Place Kubernetes Pod Resource Resizing]]></title>
            <link>https://medium.com/marionete/exploring-in-place-kubernetes-pod-resource-resizing-3cc09eaab724?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/3cc09eaab724</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Bruno Costa]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 14:29:27 GMT</pubDate>
            <atom:updated>2025-09-25T14:28:31.963Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A game‑changer for cloud‑native workloads</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kINv7MI0w2W5H4aQ" /><figcaption>Photo by <a href="https://unsplash.com/@imaginebuddy?utm_source=medium&amp;utm_medium=referral">Imagine Buddy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Kubernetes has matured into the default orchestration platform for modern, cloud‑native applications. Its declarative resource model allows teams to specify the CPU and memory each container requires, while the scheduler ensures those requests are met and enforces limits.</p><p>Until recently, the only way to adjust a pod’s resources was to change its manifest and redeploy it, resulting in a brief outage, temporary underutilization and higher operational costs.</p><p>Kubernetes v1.33 solves this friction by turning pod resource resizing from a legacy, “stop‑and‑restart” feature into a first‑class, in‑place API. This article explains the new v1.33 changes, why they matter, how you can leverage them today and a call to thought into the future.</p><h3>What Is In-Place Pod Resource Resizing?</h3><p>In-place pod resource resizing enables the CPU and memory allocations of a running pod to be adjusted <strong>without requiring a restart</strong>, which was previously necessary. This development comes after years of evolving from the alpha stage in v1.27 to beta readiness in v1.33, signalling maturity and stability.</p><h3>Why this matters</h3><p>Before, updating a Pod’s CPU or memory typically meant <strong>recreating the Pod</strong>, which is fine for stateless microservices but painful for <strong>stateful apps, long-running jobs or latency-sensitive workloads</strong>. In-lace resize lets you shape <strong>without downtime</strong>, cut wasted resources by scaling down when a load is stale or temporarily boost resources during spikes or startup.</p><h3>Technical Overview</h3><h4>Pod subresource resize</h4><p>Kubernetes added a new subresource called resize to the Pod API. This endpoint (/pods/&lt;name&gt;/resize) accepts a ResourceRequirements patch. You can now modify the spec.containers[*].resources field for CPU and memory on a running pod—changing its <strong>desired</strong> resources—while Kubernetes tracks the <strong>actual</strong> resources via status.containerStatuses[*].resources.</p><h4>kubectl support</h4><p>To initiate a resize, you typically use kubectl patch targeting the pod’s resize<strong> </strong>subresource when the spec and desired resources differ from the currently allocated ones.</p><p>You can define the resizePolicyin your Pod spec and use kubectl patch pod &lt;pod_name&gt; … --subresource=resize to adjust the Pod resources.</p><h4>Validation Layer</h4><p>The admission controller (ResourceQuota and PodSecurityPolicy) validates the new request/limit values against namespace quotas and policy constraints before accepting the change.</p><h4>Controller Runtime</h4><p>The kube-controller-manager runs a Pod Resize Controller that watches for resize requests. When a resize request is detected, the controller updates the spec of the pod and sets the status.resize field to track progress.</p><h3>How In-Place Pod resize works</h3><ol><li><strong>You request</strong> a change by updating spec.containers[*].resources via the resize subresource.</li><li><strong>Kubelet evaluates</strong> feasibility (node capacity, policies) and either applies it or marks the Pod with a condition (Pending with Deferred/Infeasible or InProgress).</li><li><strong>Runtime applies</strong> the change. Depending on the policy, the CPU can be changed<strong> in-place</strong>, while <strong>memory may require a container restart</strong>.</li></ol><h3>Validation and Safety Checks</h3><ul><li><strong>Request vs. Limit</strong> — The API server verifies that new requests don’t exceed the corresponding limits.</li><li><strong>Runtime Usage</strong> — When decreasing a limit, the request succeeds only if the pod’s current resource usage is below the new limit. Otherwise, the operation is rejected to prevent evictions.</li><li><strong>Quota and Policy</strong> — Namespace resource quotas, PodSecurityPolicies and admission controllers still run against the patched spec.</li></ul><h3>Advantages of In-Place Resizing</h3><h4>Zero-downtime adjustments</h4><p>In-Place resize lets you increase or decrease CPU and memory on a <strong>running</strong> Pod, avoiding redeploys that can disrupt stateful or latency-sensitive workloads. That means fewer connection drops, faster remediation when capacity is tight, and smoother user experience while changes take effect. <br><em>Example:</em> Kafka Connect workers are long-running JVMs that you typically <strong>over-provision</strong> for peak ingestion, leaving CPU and memory idle most of the day. With <strong>in-place vertical scaling,</strong> you can <strong>lower CPU (and sometimes memory)</strong> on running Pods during off-peak hours <strong>without a redeploy</strong>. When traffic or lag rises, you <strong>bump CPU back up in-place</strong>, clearing backlogs faster, then shrink again.</p><blockquote><em>Rule of thumb: prioritize </em><strong><em>CPU downscaling</em></strong><em> for savings (safe and restart-free); keep memory a bit above the </em><strong><em>observed benchmark </em></strong><em>(memory downsizing may restart depending on </em><em>resizePolicy).</em></blockquote><h4>Cost-efficiency</h4><p>Right-sizing isn’t just about scaling up, it’s also about <strong>giving resources back</strong> when demand decreases. By shrinking limits and requests after peaks, you reduce idle headroom, improve node utilisation and lower infrastructure costs (especially at scale!). <br><em>Example:</em> after a nightly ETL finishes, a microservice reduces its CPU limit by 20%, letting the scheduler reclaim cores for other services and shrinking monthly spend.</p><h4>Rapid elasticity and Enhanced Performance</h4><p>Because changes apply immediately, platforms can <strong>react or prepare to live telemetry</strong> (latency, queue depth, error rates) or scheduled events to keep SLOs healthy. Adapting CPU before predictable spikes prevents tail-latency cliffs, adding memory during compactions or backups shortens maintenance windows. <br><em>Example:</em> CDN edge Pods raise CPU when a campaign goes viral, maintaining low p99 latency during the surge.</p><h4>Operational simplicity</h4><p>A single patch to the Pod’s resize subresource replaces multi-step redeploy process, making capacity changes <strong>easy to automate</strong> via CI/CD, GitOps or a right-sizing controller. You gain faster feedback loops and fewer moving parts during incident response. <br><em>Example:</em> a pipeline runs a right-sizing job hourly; when metrics indicate under/over-provisioning, it patches Pods and verifies success via alerts and Pod resize conditions.</p><h3>Limitations and Considerations</h3><h4>Limited to CPU and Memory</h4><p>For now, only CPU and Memory can be resized in‑place. Other limits (e.g., GPU) still need a full pod replacement. Plan capacity for those separately, and don’t assume the resize will help. Also, remember that changing requests/limits can affect scheduling pressure and eviction priority, so validate the behaviour and impact.</p><h4>Cannot Reduce Below Runtime Usage</h4><p>Kubernetes won’t let you shrink resources beneath what the container is actively using. If you try, the request will land in a PodResizePending state (often with reason Infeasible) and be rejected or deferred to protect workload stability. Practically, that means you should decrease load (e.g. drain tasks, flush buffers, reduce concurrency) before attempting aggressive downsizing - especially for JVM-based workers.</p><h4>RBAC Over-permission</h4><p>Granting patch on the resizesubresource is powerful and can give broad power inside the cluster. <br>Restrict it tightly via a dedicated Role/ClusterRole (e.g., ResizePods) or a policy that only allows patch on pods/resize</p><h4>Not all changes are disruption-free</h4><p>Not all resource changes can be applied without disruption. Understanding these limitations is crucial for setting appropriate expectations.</p><p>CPU adjustments generally work seamlessly without container restart, as they involve cgroup limit modifications that the kernel handles gracefully. However, memory resizing might be trickier. While memory limits can be increased without a restart, decreasing memory may require a container restart, depending on current usage. If a container uses more memory than the new limit, the resize will fail to protect application stability.</p><h3>Zero-to-hero: try it in a minute</h3><p>Use the quick tutorial below in a test namespace to see how in-place resizing behaves. We’ll show CPU resize with restartPolicy: NotRequired (applies live, with no restart) and memory resize with restartPolicy: RestartContainer (applies via container restart). <br>You can experiment with kubectl patch pod ... --subresource=resize and observe both behaviours directly from the CLI.</p><h4>1) Create a Pod designed for smooth resizing</h4><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: nginx-resizable<br>spec:<br>  containers:<br>  - name: nginx<br>    image: nginx<br>    resources:<br>      requests:<br>        cpu: &quot;100m&quot;<br>        memory: &quot;128Mi&quot;<br>      limits:<br>        cpu: &quot;200m&quot;<br>        memory: &quot;256Mi&quot;<br>    resizePolicy:<br>      - resourceName: cpu<br>        restartPolicy: NotRequired<br>      - resourceName: memory<br>        restartPolicy: RestartContainer</pre><pre>kubectl apply -f nginx-resizable.yaml</pre><h4>2) Scale CPU up in-place (no restart)</h4><p>You can perform an in-place pod resize using:</p><pre>kubectl patch pod nginx-resizable --subresource=resize -p &#39;{<br>  &quot;spec&quot;: {<br>    &quot;containers&quot;: [{<br>      &quot;name&quot;: &quot;nginx&quot;,<br>      &quot;resources&quot;: {<br>        &quot;requests&quot;: {<br>          &quot;cpu&quot;: &quot;300m&quot;<br>        },<br>        &quot;limits&quot;: {<br>          &quot;cpu&quot;: &quot;500m&quot;<br>        }<br>      }<br>    }]<br>  }<br>}&#39;</pre><h4>3) Observe desired vs actual values</h4><pre>kubectl get pod nginx-resizable -o jsonpath=&#39;{.status.containerStatuses[0].resources}&#39;<br><br>kubectl describe pods nginx-resizable | grep &#39;Restart Count&#39;</pre><p>You should see spec and status.containerStatuses[*].resources aligned for CPU, with conditions reflecting progress. Restart Count should be equal to 0 after the changes take effect.</p><h4>4) Scale memory (expect a restart, by policy)</h4><pre>kubectl patch pod nginx-resizable --subresource=resize -p &#39;{<br>  &quot;spec&quot;: {<br>    &quot;containers&quot;: [{<br>      &quot;name&quot;: &quot;nginx&quot;,<br>      &quot;resources&quot;: {<br>        &quot;requests&quot;: {<br>          &quot;memory&quot;: &quot;384Mi&quot;<br>        },<br>        &quot;limits&quot;: {<br>          &quot;memory&quot;: &quot;512Mi&quot;<br>        }<br>      }<br>    }]<br>  }<br>}&#39;</pre><pre>kubectl get pod nginx-resizable -o jsonpath=&#39;{.status.containerStatuses[0].resources}&#39;<br><br>kubectl describe pods nginx-resizable | grep &#39;Restart Count&#39;<br><br>kubectl delete pod nginx-resizable</pre><p>Because the memory policy is RestartContainer the container restarts to apply the new memory.</p><p>Don’t forget to clean the resources after you are done.</p><h4>Best Practices</h4><p>We couldn’t pass up the opportunity to recall some best practices.</p><ul><li><strong>Dry‑run first — </strong>Use kubectl patch --dry-run=client to validate the manifest.</li><li><strong>Add monitoring</strong> — Create alerts when a pod hits a new limit or when resizing is attempted.</li><li><strong>Keep a rollback plan </strong>— In case resizing fails, have a rollback plan — e.g. revert to the previous pod spec or trigger a manual restart.</li><li><strong>east-privilege mindset — </strong>Only give resize privileges to trusted operators or automation tools.</li><li><strong>Document the changes</strong> — Add a comment in your CI pipeline logs indicating why a resize was performed.</li></ul><h3>The Future of Kubernetes Resource Management</h3><p>In‑place resizing is just the tip of the iceberg.</p><p>In‑place resizing is a powerful tool, but it’s just one piece of a larger puzzle. As workloads evolve (think AI/ML pipelines, real‑time analytics or hybrid cloud environments) the ability to dynamically manage resources at granular levels will become indispensable.</p><p>Here are emerging trends that will shape how Kubernetes handles resources:</p><ul><li><strong>Auto‑tuned in‑place scaling: </strong>AI models predict optimal CPU/memory and apply patches automatically (combining VPA + new resize API).</li><li><strong>Fine‑grained limits: </strong>Per‑process or per‑thread limits inside containers to avoid “noisy neighbour” problems.</li><li><strong>Accelerator auto‑resizing: </strong>GPUs, TPUs, and FPGAs can be added/removed on the fly without pod restarts, enabled by a similar resize subresource.</li><li><strong>Observability‑driven policies: </strong>Kubernetes could expose a policy engine that enforces limits based on real‑time telemetry (e.g. throttling thresholds).</li><li><strong>Hybrid‑cloud elasticity: </strong>Pods can shift between on‑prem, edge and cloud nodes, automatically adjusting resources as the workload migrates.</li></ul><p>As the ecosystem evolves, the in‑place resize API will likely become a standard building block for these more advanced automation patterns.</p><h3>Conclusion</h3><p>In‑place pod resource resizing transforms how we think about elasticity in Kubernetes. By allowing CPU and memory limits to be tweaked on the fly, it eliminates the friction of redeployments, keeps applications responsive, and optimises cluster utilisation.<br>Whether you’re a platform engineer looking to cut costs, a developer wanting instant scalability or an architect designing for variable workloads, embracing this feature can give you a tangible edge.</p><h3>References and Further Reading</h3><ul><li><a href="https://kubernetes.io/blog/2025/04/23/kubernetes-v1-33-release/"><strong>Kubernetes v1.33 release (Octarine)</strong></a></li><li><a href="https://kubernetes.io/blog/2025/05/16/kubernetes-v1-33-in-place-pod-resize-beta/"><strong>In-place Pod Resize (beta) blog</strong></a></li><li><a href="https://kubernetes.io/docs/tasks/configure-pod-container/resize-container-resources/"><strong>How-to: Resize CPU/Memory</strong></a><strong> — </strong>official docs with examples, policies, and limitations</li><li><a href="https://github.com/kubernetes/enhancements/issues/1287"><strong>KEP-1287</strong></a><strong> — </strong>design notes for in-place Pod resource updates</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cc09eaab724" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/exploring-in-place-kubernetes-pod-resource-resizing-3cc09eaab724">Exploring In‑Place Kubernetes Pod Resource Resizing</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on: Assigning Pods to Nodes using Affinity Rules]]></title>
            <link>https://medium.com/marionete/hands-on-assigning-pods-to-nodes-using-affinity-rules-9b02c914224d?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/9b02c914224d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[high-availability]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Rafael Natali]]></dc:creator>
            <pubDate>Tue, 27 May 2025 09:14:48 GMT</pubDate>
            <atom:updated>2025-02-21T17:09:26.336Z</atom:updated>
            <content:encoded><![CDATA[<p>This article describes how to configure your Pods to run in specific nodes based on affinity and anti-affinity rules. Affinity and anti-affinity allow you to inform the Kubernetes Scheduler whether to assign or not assign your Pods, which can help optimise performance, reliability, and compliance.</p><p>There are two types of affinity and anti-affinity, as per the <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity">Kubernetes documentation</a>:</p><ul><li><em>requiredDuringSchedulingIgnoredDuringExecution</em>: The scheduler can’t schedule the Pod unless the rule is met. This functions like nodeSelector, but with a more expressive syntax.</li><li><em>preferredDuringSchedulingIgnoredDuringExecution</em>: The scheduler tries to find a node that meets the rule. If a matching node is not available, the scheduler still schedules the Pod.</li></ul><p>Let’s see a couple of scenarios where you can use this configuration.</p><h3>Scenario 1: Kafka cluster with a Pod in a different K8s worker node</h3><p>In this scenario, I’m running a Kafka cluster with 3 nodes (Pods). For resilience and high-availability I want to have each Kafka node running in a different worker node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtcjvAllQT-mn-7LP5oNcQ.png" /></figure><p>In this case, Kafka is deployed as a <em>StatefulSet</em>, so the affinity is configured in the <em>.template.spec.affinity</em> field:</p><pre>spec:<br>  affinity:<br>    podAntiAffinity:<br>      requiredDuringSchedulingIgnoredDuringExecution:<br>      - labelSelector:<br>          matchExpressions:<br>          - key: app<br>            operator: In<br>            values:<br>            - kafka<br>        topologyKey: kubernetes.io/hostname</pre><p>In the configuration above, I’m using <em>podAntiAffinity</em> because it allows to create rules based on labels on Pods and not only in the node itself. In addition to that, I’m setting the <em>requiredDuringSchedulingIgnoredDuringExecution</em> because I don’t want two Kafka Pods running in the same cluster at any time. The <em>labelSelector</em> field look for the label <em>app=kafka</em> in the Pod and <em>topologyKey</em> is the label node. Pod anti-affinity requires nodes to be consistently labeled, in other words, every node in the cluster must have an appropriate label matching <em>topologyKey</em>.</p><p>In the event of a failure in one of the workers (considering that we only have three workers), the Kafka Pod will be in a Pending status because the other two nodes already have a Kafka node running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoW3DAJv64bWl26hbfy0TA.png" /></figure><p>If we change the type from <em>requiredDuringSchedulingIgnoredDuringExecution</em> to <em>preferredDuringSchedulingIgnoredDuringExecution</em>, then <em>kafka-2</em> would be assigned to another worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khJZ4cJ7FveQAiCH16U7bw.png" /></figure><h3>Scenario 2: Data Science applications that must run on specific nodes</h3><p>Conceptually, node affinity is similar to <em>nodeSelector</em> where you define where a Pod will run. However, affinity gives us more flexibility. Let’s say that in our cluster we have two worker nodes with GPU processors and some of our applications must run in one of these nodes.</p><p>In the Pod configuration we configure the .spec.affinity field:</p><pre>spec:<br>  affinity:<br>    nodeAffinity:<br>      requiredDuringSchedulingIgnoredDuringExecution:<br>        nodeSelectorTerms:<br>        - matchExpressions:<br>          - key: processor<br>            operator: In<br>            values:<br>            - gpu-east1<br>            - gpu-west1</pre><p>In this example, the following rules apply:</p><ul><li>The node <em>must</em> have a label with the key processor and the value of that label <em>must</em> be either gpu-east1 or gpu-west1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8z0bU2xUoVzFHJMmtjG8JA.png" /></figure><p>In this scenarios, the Data Science applications will be assigned to workers 1 and 2. Worker 3 will never host a Data Science application.</p><h3>Summary</h3><p>Affinity and anti-affinity rules provide us flexibility and control on where to run our applications in Kubernetes. It’s an important feature to create a highly available and resilient platform. There are more features, like weight and other operations, that you can study in the official <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/">Kubernetes documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b02c914224d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/hands-on-assigning-pods-to-nodes-using-affinity-rules-9b02c914224d">Hands-on: Assigning Pods to Nodes using Affinity Rules</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Kubernetes vulnerabilities with CIS Benchmark]]></title>
            <link>https://medium.com/marionete/handling-kubernetes-vulnerabilities-with-cis-benchmark-5e99991e5f99?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/5e99991e5f99</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cis-benchmarks]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Rafael Natali]]></dc:creator>
            <pubDate>Mon, 05 May 2025 09:32:32 GMT</pubDate>
            <atom:updated>2025-05-05T09:32:06.436Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.cisecurity.org/benchmark/kubernetes">CIS (Center for Internet Security)</a> is an independent, nonprofit organisation responsible for creating worldwide recognised security best practices, benchmarks, and controls. Regarding Kubernetes, they have benchmarks for securing Kubernetes clusters in the major cloud providers like AWS and on standalone installations.</p><p>In this article, I will use a tool called <em>kube-bench</em> to evaluate a Kubernetes cluster for vulnerabilities covered in the CIS benchmark. I will show how to access the <em>kube-bench</em> report and fix some vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNB-4YIkyvzfWRanmk4_kQ.jpeg" /></figure><h3>Generate the vulnerability report</h3><p>To generate the report using the command-line, install the <em>kube-bench</em> binary according to your operating system:</p><pre>&gt; curl -L https://github.com/aquasecurity/kube-bench/releases/download/v0.7.3/kube-bench_0.7.3_linux_amd64.deb -o kube-bench_0.7.3_linux_amd64.deb</pre><pre>&gt; sudo apt install ./kube-bench_0.7.3_linux_amd64.deb -f</pre><p>To generate the vulnerability report for the Kubernetes cluster, execute <em>kube-bench run</em>:</p><pre>&gt;kube-bench run</pre><pre>[[INFO] 1 Master Node Security Configuration<br>[INFO] 1.1 Master Node Configuration Files<br>[PASS] 1.1.1 Ensure that the API server pod specification file permissions are set to 644 or more restrictive (Automated)<br>[PASS] 1.1.2 Ensure that the API server pod specification file ownership is set to root:root (Automated)<br>[PASS] 1.1.3 Ensure that the controller manager pod specification file permissions are set to 644 or more restrictive (Automated)<br>...<br>== Remediations node<br>4.2.6 If using a Kubelet config file, edit the file to set protectKernelDefaults: true.<br>If using command line arguments, edit the kubelet service file<br>/lib/systemd/system/kubelet.service on each worker node and<br>set the below parameter in KUBELET_SYSTEM_PODS_ARGS variable.<br>--protect-kernel-defaults=true<br>Based on your system, restart the kubelet service. For example:<br>systemctl daemon-reload<br>systemctl restart kubelet.service<br>...<br>== Summary total ==<br>68 checks PASS<br>12 checks FAIL<br>43 checks WARN<br>0 checks INFO</pre><p>Another installation option is to run <em>kube-bench</em> as a <em>Job </em>in the Kubernetes cluster. For this, create a local file based on the the job.yaml file from <a href="https://github.com/aquasecurity/kube-bench/blob/main/job.yaml">https://github.com/aquasecurity/kube-bench/blob/main/job.yaml</a> and apply it to you cluster:</p><pre>&gt; kubectl apply -f job.yamljob.batch/kube-bench created</pre><p>A Pod will be created and generate the <em>kube-bench</em> report. To visualize the report, access the Pod’s logs:</p><pre>&gt; kubectl logs kube-bench-wddkj</pre><p>The output will be the same as running with the command-line. The report has five parts: <em>master, etcd, control plane, worker (node),</em> and <em>policies</em>. The report’s summary indicates that 12 checks have <strong>failed</strong> and 43 have triggered <strong>warnings</strong>. We will now address some of these issues.</p><h3>How to fix CIS vulnerabilities</h3><p>The <em>kube-bench</em> report provides us with recommendation to fix the vulnerabilities. In this subsection, we will solve two vulnerabilities. One for the <strong>control plane</strong> and another one for a <strong>worker node</strong>.</p><h3>Control Plane</h3><p>In this example, we will solve the vulnerability <strong>1.1.12</strong>:</p><pre>[FAIL] 1.1.12 Ensure that the etcd data directory ownership is set to etcd:etcd (Automated)</pre><p>In the report, you can see the recommendation on how to fix this vulnerability:</p><pre>1.1.12 On the etcd server node, get the etcd data directory, passed as an argument --data-dir, from the below command:</pre><pre>ps -ef | grep etcd</pre><pre>Run the below command (based on the etcd data directory found above).</pre><pre>For example, chown etcd:etcd /var/lib/etcd</pre><p>Execute the instructions as directed. First, in the control plane, locate the <em>data-dir</em> directory for <em>etcd</em>:</p><pre>&gt; ps -ef | grep etcd</pre><pre>root        1594    1296  2 09:24 ?        00:01:05 etcd --advertise-client-urls=https://172.31.119.105:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd</pre><p>Change the permissions in the <em>/var/lib/etcd</em> and execute <em>kube-bench</em> and filter by the vulnerability <strong>1.1.12</strong>:</p><pre>&gt;chown etcd:etcd /var/lib/etcd</pre><pre>&gt;kube-bench run | grep -i 1.1.12[PASS] 1.1.12 Ensure that the etcd data directory ownership is set to etcd:etcd (Automated)</pre><p>Now, the vulnerability for the <em>etcd</em> <em>data-dir</em> directory ownership is resolved.</p><h3>Worker node</h3><p>For the worker, the vulnerability<strong> 4.2.10</strong> must be solved:</p><pre>[FAIL] 4.2.10 Ensure that the --rotate-certificates argument is not set to false (Automated)</pre><p>Reviewing the recommendations:</p><pre>4.2.10 If using a Kubelet config file, edit the file to add the line `rotateCertificates` to `true` or remove it altogether to use the default value.</pre><pre>If using command line arguments, edit the kubelet service file/lib/systemd/system/kubelet.service on each worker node andremove --rotate-certificates=false argument from the KUBELET_CERTIFICATE_ARGS variable.</pre><pre>Based on your system, restart the kubelet service. For example,</pre><pre>systemctl daemon-reload<br>systemctl restart kubelet.service</pre><p>To fix this we need to log in into the worker node:</p><pre>&gt; ssh &lt;user&gt;@&lt;node_name/ip address&gt;</pre><p>Once logged in the worker node, find the <em>kubelet</em> config file:</p><pre>&gt; ps -auxwww | grep -i kubeletroot        4016  1.3  4.2 2140228 83988 ?       Ssl  19:00   0:14 /usr/bin/kubelet --bootstrap-kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf --kubeconfig=/etc/kubernetes/kubelet.conf --config=/var/lib/kubelet/config.yaml --container-runtime-endpoint=unix:///var/run/containerd/containerd.sock --pod-infra-container-image=registry.k8s.io/pause:3.9</pre><p>Open the config file in the editor:</p><pre>&gt; sudo vi /var/lib/kubelet/config.yaml</pre><p>Change the <em>— rotate-certificates=false </em>parameter to <em>true</em>:</p><pre>rotateCertificates: false  #change from false to true</pre><p>Restart the <em>kubelet</em> service:</p><pre>&gt; sudo systemctl daemon-reload<br>&gt; sudo systemctl restart kubelet</pre><p>Return to the control plane and generate a new report to validate the changes. To do that with the Kubernetes job, delete the current job and apply it again:</p><pre>&gt; kubectl delete jobs.batch kube-bench<br>job.batch &quot;kube-bench&quot; deleted</pre><pre>&gt; kubectl apply -f job.yaml<br>job.batch/kube-bench created</pre><p>In the Pod’s log, search for the <strong>4.2.10</strong> vulnerability:</p><pre>&gt; kubectl logs kube-bench-n52f8 | grep -i 4.2.10<br>[PASS] 4.2.10 Ensure that the --rotate-certificates argument is not set to false (Automated)</pre><p>One more vulnerability successfully resolved!</p><h3>Summary</h3><p><em>kube-bench</em> is an easy-to-use and straightforward tool that helps administrators determine the current vulnerabilities of your Kubernetes cluster and define the priorities for tackling these vulnerabilities. The tool provides the necessary information on how to solve the vulnerabilities. Also, you can access the <a href="https://www.cisecurity.org/benchmark/kubernetes">CIS Kubernetes Benchmarks</a> reports and download a PDF complete with all the instructions.</p><p>Give <em>kube-bench </em>a chance and improve the security of your cluster today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e99991e5f99" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/handling-kubernetes-vulnerabilities-with-cis-benchmark-5e99991e5f99">Handling Kubernetes vulnerabilities with CIS Benchmark</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing the Kubernetes Host Operating System]]></title>
            <link>https://medium.com/marionete/securing-the-kubernetes-host-operating-system-bdeb95a5d0df?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/bdeb95a5d0df</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Rafael Natali]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 17:36:44 GMT</pubDate>
            <atom:updated>2025-04-10T20:03:41.587Z</atom:updated>
            <content:encoded><![CDATA[<p>It is crucial to prioritise Kubernetes security by safeguarding the Kubernetes host from the containers operating on it. If an attacker manages to compromise a container or a Pod, there are several potential attack paths they could exploit to compromise the hosts. If the host operating system is breached, the attacker could use it to target other nodes in the cluster, along with all the Pods and applications running on that node. Eventually, the attacker can even access other systems in your network! The next subsections contain the information necessary to secure the host operating system.</p><h3>Operating System Namespaces</h3><p>In terms of security, containers make use of <em>operating system namespaces</em>. This concept of operating system namespaces is distinct from the idea of Kubernetes namespaces. In this context, namespaces refer to a Linux kernel feature that container technologies use to separate themselves from other containers running on the same machine and the host operating system.</p><p>In a Kubernetes server, there are <em>host namespaces</em>, which are used by normal applications running directly on the host operating system. On the other hand, containers operate in a completely separate <em>containers namespace</em>. This setup creates separation between containers and between containers and the host operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BDqMX2M-xBVa_WQuBnCxQ.png" /><figcaption>Figure 1.1 — Host operating system namespaces</figcaption></figure><p>As a result of this configuration, if a container is compromised, an attacker’s activities are limited to the container namespace. This isolation restricts the attacker’s ability to potentially compromise the host or other containers.</p><p>This introduction is important because you can configure Pods to use the host namespace instead of the isolated container namespace. You might want to do that if you have a container that needs to interact directly with the host operating system. However, <em>this should only be done if absolutely necessary due to the security risks involved</em>. If that container is compromised, the attacker potentially has more ability to interact with components of the operating system because the isolation of the container namespace is not present.</p><p>This is the Pod configuration that allows it to interact with the host operating system:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: host-pod<br>spec:<br>  hostIPC: true<br>  hostNetwork: true<br>  hostPID: true<br>  containers:<br>  - name: nginx<br>    image: nginx</pre><p>When setting <em>spec.hostIPC </em>to <em>true</em> containers will use the host’s <em>inter-process communication (IPC) namespace</em>. Interprocess communication is a feature of Linux that allows processes to communicate with each other. Usually, containers use a separate IPC namespace, meaning there is no communication between containers and processes in the host operating system. Another setting is <em>spec.hostNetwork</em>, and this controls the <em>network namespace.</em> The <em>spec.hostPID</em> will make this container use the <em>host process ID namespace</em>. All these configurations instruct the container to use the host namespace in each one of these different areas. All these values default to <em>false</em>. So, if you don’t specify any of these settings, the containers will use the isolated namespace.</p><h3>Avoiding Pods running in privileged mode</h3><p>Another concept you might need to be aware of when protecting the host operating system is the concept of <em>privileged mode</em>. Privileged mode provides the broadest possible level of permissions. It allows containers to use privilege escalation and access host-level resources, similar to a process running directly on the host.</p><p>In the digram below, we have a <em>non-privileged</em> and a <em>privileged</em> container running in the same host. If the <em>non-privileged</em> container is compromised, that limits what an attacker can do. On the other hand, <em>privileged</em> containers can access host-level resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jy-FWkj-7plUco-L-ZubZA.png" /><figcaption>Figure 1.2 — Privileged and non-privileged containers</figcaption></figure><p>To create a privileged container, we set the field <em>spec.containers[*].securityContext.privileged</em> to <em>true</em> in the Pod definition:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: privileged-pod<br>spec:<br>  containers:<br>  - name: nginx<br>    image: nginx<br>    securityContext:<br>      privileged: true</pre><h3>Studying Linux capabilities</h3><p>A third concept we need to study is <a href="https://man7.org/linux/man-pages/man7/capabilities.7.html">Linux capabilities</a>. With Linux capabilities, you can give specific privileges to a process without granting all the privileges of the root user. By default, containers are executed with a default set of capabilities as specified by the Container Runtime, and this is sufficient for most scenarios. Following the principle of least privilege, it’s advisable to <em>remove all capabilities from a Pod</em> definition unless they are necessary. Otherwise, granting more permissions than required to a Pod could expose your host operating system to security threats.</p><p>To explicitly drop all capabilities of a Pod, set <em>spec.containers[*].securityContext.capabilities.drop</em> to <em>ALL</em>:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: capabilities-pod<br>spec:<br>  containers:<br>  - image: busybox<br>    name: busybox<br>    command:<br>      - sleep<br>      - &quot;3600&quot;<br>    securityContext:<br>      capabilities:<br>        drop:<br>          - ALL</pre><p>To check the capabilities allowed in your Pod, kubectl exec into your Pod and in the shell, locate a running process:</p><pre>ps aux</pre><p>Output:</p><pre>PID   USER     TIME  COMMAND<br>    1 1000      0:00 sleep 3600<br>    7 1000      0:00 sh<br>   14 1000      0:00 ps aux</pre><p>In your shell, view the status for process 1:</p><pre>cd /proc/1<br>cat status</pre><p>The output shows the capabilities bitmap for the process:</p><pre>...<br>CapInh: 0000000000000000<br>CapPrm: 0000000000000000<br>CapEff: 0000000000000000<br>CapBnd: 0000000000000000<br>CapAmb: 0000000000000000<br>....</pre><h3>Running containers as non-root users</h3><p>The final concept we are going to review is the <em>runAsUser</em>. Containers may run as any Linux user. Containers that run as the root user — <em>runAsUser: 0 </em>— if compromised, can likely be used to gain root access to the host operating system. Again, with root access to the host, an attacker can take control of the entire Kubernetes cluster or other systems in the company.</p><p>This is the Pod configuration to mitigate the risk of running containers as root:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: capabilities-pod<br>spec:<br>  containers:<br>  - image: busybox<br>    name: busybox<br>    command:<br>      - sleep<br>      - &quot;3600&quot;<br>    securityContext:<br>      runAsNonRoot: true<br>      runAsUser: 1000<br>      runAsGroup: 1000</pre><p>With the field <em>spec.containers[*].securityContext.runAsNonRoot</em> set to <em>true</em>, a container is required to run as non-root users. The other two fields, <em>spec.containers[*].securityContext.runAsUser</em> and <em>spec.containers[*].securityContext.runAsGroup</em>, define the user and group that has permission to execute the application within the container. To make sure that the application will run as non-root user, besides the configurations in the Pod definition, set the user and group in the <em>Dockerfile</em> when creating the Docker image for the application.</p><h3>Summary</h3><p>Securing and isolating the host operating system is paramount to guarantee not only the Kubernetes cluster security but also the security of your company. Some points to remember:</p><ul><li>Beware of Pod settings like <em>hostIPC</em>, <em>hostPID</em>, and <em>hostNetwork</em></li><li>Privileged mode is configured when the field <em>spec.containers[*].securityContext.privileged</em> is set to true</li><li>Drop all Linux capabilities in the Pod definition</li><li>Containers should be running as non-root users</li></ul><p>This is an example of a strictly configured Pod with the settings mentioned in this article:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: capabilities-pod<br>spec:<br>  hostIPC: false<br>  hostNetwork: false<br>  hostPID: false<br>  containers:<br>  - image: busybox<br>    name: busybox<br>    command:<br>      - sleep<br>      - &quot;3600&quot;<br>    securityContext:<br>      privileged: false<br>      runAsNonRoot: true<br>      runAsUser: 1000<br>      runAsGroup: 1000<br>      capabilities:<br>        drop:<br>          - ALL</pre><p>Review the official documentation at <a href="https://kubernetes.io/docs/tasks/configure-pod-container/security-context/">https://kubernetes.io/docs/tasks/configure-pod-container/security-context/</a> and <a href="https://kubernetes.io/docs/concepts/security/pod-security-standards/">https://kubernetes.io/docs/concepts/security/pod-security-standards/</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdeb95a5d0df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/securing-the-kubernetes-host-operating-system-bdeb95a5d0df">Securing the Kubernetes Host Operating System</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Kafka Security with Access Control Lists (ACLs)]]></title>
            <link>https://medium.com/marionete/unlocking-kafka-security-with-access-control-lists-acls-a6aa1010984f?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/a6aa1010984f</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kraft]]></category>
            <category><![CDATA[acl]]></category>
            <dc:creator><![CDATA[Rafael Natali]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 21:24:07 GMT</pubDate>
            <atom:updated>2025-03-19T08:15:08.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Building on my previous article <a href="https://medium.com/@rafael-natali/running-kafka-in-kubernetes-with-kraft-mode-and-sasl-authentication-f7350eaba81f">Running Kafka in Kubernetes with Kraft mode and SASL authentication</a>, I will demonstrate how to configure the broker to use ACLs, how to troubleshoot ACL-related issues, and some ACL examples.</p><p>Apache Kafka employs Access Control Lists (ACLs) as a vital component of its security infrastructure. ACLs regulate access to Kafka resources by specifying which users or applications can perform specific actions. By implementing ACLs, Kafka administrators can enforce granular access control policies, ensuring data integrity and confidentiality within their Kafka clusters.</p><p>ACLs serve as a robust defence mechanism against unauthorised access, safeguarding sensitive data and preventing malicious activities within Kafka clusters. With ACLs, administrators can restrict topics, partitions, consumer groups, and administrative operations, empowering them to enforce compliance standards and protect against data breaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VZWDY6P1tuX0F7qRIfOQA.jpeg" /><figcaption>Photo by Patrick Robert Doyle on Unsplash</figcaption></figure><h3>Kafka with Zookeeper vs. KRaft-based Kafka Clusters</h3><p>Configuring ACLs in Kafka differs based on the underlying cluster architecture. The environment variable <strong><em>KAFKA_AUTHORIZER_CLASS_NAME</em></strong><em> </em>in the Kafka configuration — <a href="https://github.com/rafaelmnatali/kafka-k8s/blob/main/acls/01-kafka.yaml"><strong><em>01-kafka.yml</em></strong></a>—must be updated accordingly:</p><ul><li>Kafka with Zookeeper: In traditional Kafka clusters with Zookeeper, ACLs are managed through Zookeeper nodes, where access control settings are stored using the following class:</li></ul><pre>authorizer.class.name=kafka.security.authorizer.AclAuthorizer</pre><ul><li>Kafka with KRaft: In KRaft-based Kafka clusters, ACLs are integrated directly into the broker configuration, simplifying management and ensuring consistency across the cluster. KRaft-based cluster uses a different class:</li></ul><pre>authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer</pre><h3>Configuring Kafka for ACLs</h3><p>Next are the parameters we need to add our previous Kafka Broker to enable ACLs and a new <em>admin client</em> configuration.</p><h3>Broker</h3><p>The information below is in the <a href="https://github.com/rafaelmnatali/kafka-k8s/blob/main/acls/01-kafka.yaml">Kafka StatefulSet manifest file</a>.</p><ul><li>Enable SASL/PLAIN mechanism for the <strong>CONTROLLER</strong></li></ul><pre>- name: KAFKA_LISTENER_NAME_CONTROLLER_PLAIN_SASL_JAAS_CONFIG<br>  value: org.apache.kafka.common.security.plain.PlainLoginModule required username=&quot;admin&quot; password=&quot;admin-secret&quot; user_admin=&quot;admin-secret&quot; user_kafkaclient1=&quot;kafkaclient1-secret&quot;; <br>- name: KAFKA_SASL_MECHANISM_CONTROLLER_PROTOCOL<br>  value: PLAIN<br>- name: KAFKA_CONTROLLER_ENABLED_MECHANISMS<br>  value: PLAIN</pre><p><strong><em>KAFKA_LISTENER_NAME_CONTROLLER_PLAIN_SASL_JAAS_CONFIG </em></strong>is the variable used to create the users (admin and kafka_client1). If you want to add a new user, this is the place to go.</p><ul><li>Update the <em>security.protocol.map</em> of the <strong>CONTROLLER</strong> to use <strong>SASL_PLAINTEXT</strong></li></ul><pre>- name: KAFKA_LISTENER_SECURITY_PROTOCOL_MAP<br>  value: &quot;CONTROLLER:SASL_PLAINTEXT,SASL:SASL_PLAINTEXT&quot;</pre><ul><li>Configure the <strong>authorizer</strong> and <strong>super.user</strong></li></ul><pre>- name: KAFKA_SUPER_USERS<br>  value: User:admin<br>- name: KAFKA_AUTHORIZER_CLASS_NAME<br>  value: org.apache.kafka.metadata.authorizer.StandardAuthorizer<br>- name: KAFKA_ALLOW_EVERYONE_IF_NO_ACL_FOUND<br>  value: &quot;false&quot;</pre><h3>Admin Client</h3><ul><li>Create a <a href="https://kubernetes.io/docs/concepts/configuration/configmap/">ConfigMap</a> based on the <em>sasl_client.properties</em> file:</li></ul><pre>kubectl create configmap kafka-admin --from-file sasl_admin.properties -n kafka    <br>kubectl describe configmaps -n kafka kafka-admin<br><br>Output:<br>configmap/kafka-admin created<br>Name:         kafka-admin<br>Namespace:    kafka<br>Labels:       &lt;none&gt;<br>Annotations:  &lt;none&gt;<br>    <br>Data<br>====<br>sasl_admin.properties:<br>----<br>sasl.mechanism=PLAIN<br>security.protocol=SASL_PLAINTEXT<br>    sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \<br>      username=&quot;admin&quot; \<br>      password=&quot;admin-secret&quot;;<br>    <br>BinaryData<br>====<br>Events:  &lt;none&gt;</pre><ul><li>Mount the ConfigMap as a <em>volume</em>:</li></ul><pre>volumeMounts:<br>        - mountPath: /etc/kafka/secrets/<br>          name: kafka-admin<br>    ...<br>    volumes:<br>    - name: kafka-admin<br>      configMap: <br>        name: kafka-admin</pre><h3>Creating the deployment</h3><p>Clone the repo:</p><pre>git clone https://github.com/rafaelmnatali/kafka-k8s.git<br>cd acls</pre><p>You can deploy Kafka using the following commands:</p><pre>kubectl apply -f 00-namespace.yaml<br>kubectl apply -f 01-kafka.yaml</pre><h3>Verify communication across brokers</h3><p>There should now be three Kafka brokers each running on separate pods within your cluster. Name resolution for the headless service and the three pods within the StatefulSet is automatically configured by Kubernetes as they are created, allowing for communication across brokers. See the related <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/">documentation</a> for more details on this feature.</p><p>You can check the first pod’s logs with the following command:</p><pre>kubectl logs kafka-0</pre><p>The name resolution of the three pods can take more time to work than it takes the pods to start, so you may see <em>UnknownHostException</em> warnings in the pod logs initially:</p><pre>WARN [RaftManager nodeId=2] Error connecting to node kafka-1.kafka-headless.kafka.svc.cluster.local:29093 (id: 1 rack: null) (org.apache.kafka.clients.NetworkClient) java.net.UnknownHostException: kafka-1.kafka-headless.kafka.svc.cluster.local         ...</pre><p>Eventually, each pod will successfully resolve pod hostnames and end with a message stating the broker has been <em>unfenced</em>:</p><pre>INFO [Controller 0] Unfenced broker: UnfenceBrokerRecord(id=1, epoch=176) (org.apache.kafka.controller.ClusterControlManager)</pre><h3>Testing Kafka ACLs</h3><p>To test the ACLs, we will deploy two clients: admin and non-admin. Open two terminal windows and deploy the admin client in one and the non-admin in the another one.</p><p>Commands:</p><pre>kubectl apply -f 02-kafka-client.yaml<br>kubectl apply -f 03-kafka-admin.yaml</pre><p>Let’s use the operation CREATE as an example of how to troubleshoot and solve permission errors in Kafka.</p><p>First, create a topic from the admin client:</p><pre>kubectl exec -it kafka-admin -- bash -c &quot;kafka-topics --bootstrap-server kafka-0.kafka-headless.kafka.svc.cluster.local:9092 -create --topic kafka-admin --command-config /etc/kafka/secrets/sasl_admin.properties&quot;</pre><p>Output:</p><pre>Created topic kafka-admin</pre><p>Second, try to create a topic from the non-admin client:</p><pre>kubectl exec -it kafka-client -- bash -c &quot;kafka-topics --bootstrap-server kafka-0.kafka-headless.kafka.svc.cluster.local:9092 -create --topic kafka-client --command-config /etc/kafka/secrets/sasl_client.properties&quot;</pre><p>Output:</p><pre>Error while executing topic command : Authorization failed.</pre><p>Our client does not have permission. Looking into the Kafka logs it’s possible to see the following entry:</p><pre>kafka-0 kafka [2024-03-13 20:10:17,259] INFO Principal = User:kafkaclient1 is Denied operation = CREATE from host = 10.244.0.9 on resource = Topic:LITERAL:kafka-admin for request = CreateTopics with resourceRefCount = 1 based on rule DefaultDeny (kafka.authorizer.logger)</pre><p>⚠️ Note that in the log this is an <strong>INFO</strong> entry and not an <strong>ERROR</strong>.</p><p>Create the ACL from the admin client:</p><pre>kubectl exec -it kafka-admin -- bash -c &quot;kafka-acls --bootstrap-server kafka-0.kafka-headless.kafka.svc.cluster.local:9092 --add --allow-principal User:kafkaclient1 --operation Create --allow-host 10.244.0.9 --cluster --command-config /etc/kafka/secrets/sasl_admin.properties&quot;</pre><p>Output:</p><pre>Adding ACLs for resource `ResourcePattern(resourceType=CLUSTER, name=kafka-cluster, patternType=LITERAL)`: <br>        (principal=User:kafkaclient1, host=10.244.0.9, operation=CREATE, permissionType=ALLOW)</pre><p>Try to create a topic from the non-admin client again:</p><pre>kubectl exec -it kafka-client -- bash -c &quot;kafka-topics --bootstrap-server kafka-0.kafka-headless.kafka.svc.cluster.local:9092 -create --topic kafka-client --command-config /etc/kafka/secrets/sasl_client.properties&quot;</pre><p>Output:</p><pre>Created topic kafka-client.</pre><h3>More Kafka ACL examples</h3><p>Read/Write in a Topic:</p><pre>kafka-acls --bootstrap-server kafka-0.kafka-headless.kafka.svc.cluster.local:9092 --add --allow-principal User:kafkaclient1 --operation Read --operation Write --allow-host 10.244.0.9 --topic kafka-client --command-config /etc/kafka/secrets/sasl_admin.properties</pre><p>List ACLs:</p><pre>kafka-acls --bootstrap-server kafka-0.kafka-headless.kafka.svc.cluster.local:9092 --list --topic kafka-client --command-config /etc/kafka/secrets/sasl_admin.properties</pre><p>Remove ACLs:</p><pre>kafka-acls --bootstrap-server kafka-0.kafka-headless.kafka.svc.cluster.local:9092 --remove --topic kafka-client --command-config /etc/kafka/secrets/sasl_admin.properties</pre><h3>Summary</h3><p>Access Control Lists (ACLs) are indispensable for securing Apache Kafka deployments, enabling administrators to enforce fine-grained access controls and mitigate security risks. Whether managing Kafka with Zookeeper or adopting KRaft-based Kafka clusters, ACLs play a pivotal role in ensuring data protection, compliance, and overall cluster security. By understanding and leveraging ACLs effectively, organisations can fortify their Kafka infrastructure against unauthorised access and potential threats, bolstering the integrity and confidentiality of their event streaming pipelines.</p><h3>References</h3><ul><li><a href="https://docs.confluent.io/platform/current/kafka/authorization.html#cluster-resource-operations">https://docs.confluent.io/platform/current/kafka/authorization.html#cluster-resource-operations</a></li><li><a href="https://github.com/rafaelmnatali/kafka-k8s">https://github.com/rafaelmnatali/kafka-k8s</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6aa1010984f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/unlocking-kafka-security-with-access-control-lists-acls-a6aa1010984f">Unlocking Kafka Security with Access Control Lists (ACLs)</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing your Azure Kubernetes Services Cluster]]></title>
            <link>https://medium.com/marionete/securing-your-azure-kubernetes-services-cluster-c802a58c2d0d?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/c802a58c2d0d</guid>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-devops]]></category>
            <dc:creator><![CDATA[Rafael Natali]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 15:01:37 GMT</pubDate>
            <atom:updated>2024-09-13T07:18:20.997Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will present my perspective on securing an Azure Kubernetes cluster with the <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">principle of least privilege</a> as a top priority. I will explain the available built-in Azure Kubernetes Roles, the function of the Microsoft Entra (formerly Azure Active Directory) groups, and how to utilize Kubernetes RBAC to manage access to the workloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*frSwoRVeBQ3MoiPK" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=medium&amp;utm_medium=referral">FlyD</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Authentication and Authorization</h3><p>Configure the cluster to <a href="https://learn.microsoft.com/en-us/azure/aks/concepts-identity#microsoft-entra-integration">integrate with Microsoft Entra</a> and take advantage to manage users and groups from a central identity management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B47MJer7fC4xVFQV.png" /></figure><h3>Microsoft Entra Groups and Azure Kubernetes Roles</h3><p>Create one or more <a href="https://learn.microsoft.com/en-us/entra/fundamentals/how-to-manage-groups">Entra Groups</a> to separate the administrators from the non-administrators. The number and structure of groups will depend on your structure. Let’s assume we created two groups:</p><ul><li>admin</li><li>developers</li></ul><p>Now, we need to assign <a href="https://learn.microsoft.com/en-us/azure/aks/concepts-identity#summary">roles</a> to these groups. There are two Azure Kubernetes Roles I use:</p><p><strong>Role: </strong>Azure Kubernetes Service Cluster User Role</p><p><strong>Description: </strong>This role allows the user to log into the cluster; however if no <em>(Cluster)RoleBidings</em> exists, the user cannot execute any <em>kubectl</em> command.</p><p><strong>Role: </strong>Azure Kubernetes Service RBAC Cluster Admin</p><p><strong>Description: </strong>Allows super-user access to perform any action on any resource.</p><p>The “admin” group will have the “RBAC Cluster Admin” and the “developers” the “User Role”. With this role assignment, we achieved the principle of least privilege because we denied all <em>kubectl</em> commands to the “developers”. From now on, I, as an administrator, will use <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">Kubernetes RBAC</a> to control what the developers can do. The RBAC you’ll implement will vary depending on your use cases.</p><h3>Kubernetes RBAC</h3><p>Now, for example, I’ll give permissions for the “developers” to read <em>Pods </em>in the <em>dev </em>namespace using the following <em>Role</em>:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: dev<br>  name: pod-reader<br>rules:<br>- apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group<br>  resources: [&quot;pods&quot;]<br>  verbs: [&quot;get&quot;, &quot;watch&quot;, &quot;list&quot;]</pre><p>Get the resource ID for the <em>developers</em> group using the <a href="https://learn.microsoft.com/en-us/cli/azure/ad/group#az_ad_group_show"><em>az ad group show</em></a> command. This group is set as the subject of a <em>RoleBinding</em> in the next step.</p><pre>az ad group show --group developers --query id -o tsv</pre><p>Create a <em>RoleBinding</em> for the “developers” group to use the previously created <em>Role</em> for reading <em>Pods</em>.</p><pre>kind: RoleBinding<br>apiVersion: rbac.authorization.k8s.io/v1<br>metadata:<br>  name: dev-user-access<br>  namespace: dev<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: Role<br>  name: pod-reader<br>subjects:<br>- kind: Group<br>  namespace: dev<br>  name: &lt;groupObjectId&gt; # output of the az ad group show</pre><p>And now, the members of the “developers” group will be able to read <em>Pods </em>in the <em>dev </em>namespace.</p><h3>Summary</h3><p>We can set up non-administrator groups with the “Azure Kubernetes Service Cluster User Role” to effectively enforce a “deny-all” policy. This means that members of these groups will have no permission to carry out any actions in the Kubernetes cluster. The administrator can then selectively grant only the necessary permissions to these groups.</p><p>This approach allows the administrator to protect Kubernetes Secrets from unauthorised access, prevent the deletion of system Pods, and control access to specific namespaces, which is particularly useful in multi-tenant environments.</p><p>In my view, it’s better to begin with a closed environment and then gradually open up access as needed rather than starting with open access and then trying to restrict it.</p><h3>Reference</h3><ul><li><a href="https://learn.microsoft.com/en-us/azure/aks/concepts-identity">https://learn.microsoft.com/en-us/azure/aks/concepts-identity</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c802a58c2d0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/securing-your-azure-kubernetes-services-cluster-c802a58c2d0d">Securing your Azure Kubernetes Services Cluster</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up a Local Flink Cluster Using Docker]]></title>
            <link>https://medium.com/marionete/how-to-set-up-a-local-flink-cluster-using-docker-0a0a741504f6?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/0a0a741504f6</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[flink]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ricardo Cordeiro]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 11:17:31 GMT</pubDate>
            <atom:updated>2024-07-16T11:17:31.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Running a local Flink cluster provides an isolated environment for developing, testing, experimenting, and troubleshooting Flink applications. By setting up a local Flink cluster, you can gain hands-on experience and ensure that your Flink jobs are robust and performant before deploying them to a production environment.</p><h3>What is Flink?</h3><p><a href="https://flink.apache.org/"><strong><em>Apache Flink</em></strong></a> is a framework and distributed processing engine for stateful computations over unbounded and bounded data streams.</p><h4>Deployment Modes</h4><p>Before we start its important to notice that Flink can execute applications in two ways:</p><ul><li><strong>Application Mode</strong>: Creates a cluster per submitted application. A dedicated JobManager is started for submitting the job. The JobManager will only execute this job, then exit. Although Application Mode comes with better resource isolation, it comes at the price of spinning up a dedicated cluster for each application.</li><li><strong>Session Mode</strong>: The applications are executed on the client side and one JobManager instance manages multiple jobs that share the same cluster of TaskManagers. This has the advantage that you do not pay the resource overhead of spinning up a cluster for every job.</li></ul><p>We will use Session Mode during this demonstration to have Job and Task Managers running continuously for testing and interaction with the cluster.</p><h3>Dockerfile Image</h3><p>First, create a new file named &#39;flink.Dockerfile&#39; with the following content:</p><pre>FROM flink:1.19.0-scala_2.12-java17<br><br>RUN wget -P /opt/flink/lib https://repo.maven.apache.org/maven2/org/apache/flink/flink-sql-connector-kafka/3.0.2-1.18/flink-sql-connector-kafka-3.0.2-1.18.jar &amp;&amp; \ <br>    wget -P /opt/flink/lib https://repo1.maven.org/maven2/org/apache/kafka/kafka-clients/3.6.1/kafka-clients-3.6.1.jar</pre><p>To ensure your Flink cluster can connect to various data sources and sinks, you need to include the necessary dependencies. In this example, we are adding dependencies for Apache Kafka. Depending on your use case, you might need to add additional connectors to your setup.</p><p>Now build the Docker image with:</p><pre>docker build -t my-flink -f flink.Dockerfile .</pre><h3>Docker compose</h3><p>Afterwards we will create a new file named &#39;env-compose.yml&#39; with the following content:</p><pre>version: &#39;1&#39;<br>services:<br>  taskmanager:<br>    image: my-flink<br>    container_name: taskmanager<br>    hostname: taskmanager<br>    depends_on:<br>      - jobmanager<br>    command: taskmanager<br>    scale: 1<br>    environment:<br>      - |<br>        FLINK_PROPERTIES=<br>        jobmanager.rpc.address: jobmanager<br>        taskmanager.numberOfTaskSlots: 6 <br><br>  jobmanager:<br>    image: my-flink<br>    container_name: jobmanager<br>    hostname: jobmanager<br>    ports:<br>      - &quot;8082:8082&quot;<br>    command: jobmanager<br>    environment:<br>      - |<br>        FLINK_PROPERTIES=<br>        jobmanager.rpc.address: jobmanager<br>        rest.address: jobmanager<br>        rest.port: 8082</pre><p>This configuration includes the minimum necessary components to run a functional Flink cluster:</p><ul><li><strong>JobManager</strong>: Manages job execution, task scheduling, and cluster resources.</li><li><strong>TaskManager</strong>: Executes the tasks of the submitted jobs.</li></ul><p>To enable our Flink cluster to interact with other technologies, you might add services for the data sources and sinks that your Flink jobs will interact with.</p><p>In order to have a Kafka cluster available in our environment, add the following configuration to the &#39;env-compose.yml&#39; file:</p><pre>  zookeeper:<br>    image: wurstmeister/zookeeper:latest<br>    ports:<br>      - &quot;2181:2181&quot;<br><br>  kafka:<br>    image: wurstmeister/kafka:latest<br>    ports:<br>      - &quot;9092:9092&quot;<br>    expose:<br>      - &quot;9093&quot;<br>    environment:<br>      KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT<br>      KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092<br>      KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_CREATE_TOPICS: &quot;input-topic:1:1,output-topic:1:1&quot;<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock</pre><p>If both files are correctly created, run the docker-compose to deploy the environment:</p><pre>docker-compose -f env-compose.yml up -d</pre><p>Likewise, if you want to tear down the environment:</p><pre>docker-compose -f env-compose.yml down</pre><h3>Access Flink Dashboard</h3><p>Access the Flink web dashboard at http://localhost:8082. This dashboard allows you to monitor the status of your Flink cluster, including Job and Task Managers statuses. It also allows submitting and inspecting already finished or ongoing jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohD_LRd9T3gt6RoRkxHa3Q.png" /></figure><h3>Creating a Flink Job</h3><p>Creating jobs in Apache Flink involves defining the logic for data processing. Flink jobs can be written in various programming languages and paradigms, including SQL, Java, Scala, and Python.</p><p>Here, we will focus on creating jobs in SQL and Java, demonstrating how to interact with a Kafka cluster. Both examples will do exactly the same thing: read data from a Kafka topic, process it using SQL/Java, and write the result back to another Kafka topic.</p><h4><em>SQL:</em></h4><pre>-- Create source table to read from Kafka<br>CREATE TABLE source_table (<br>  `field1` STRING,<br>  `field2` STRING<br>) WITH (<br>  &#39;connector&#39; = &#39;kafka&#39;,<br>  &#39;topic&#39; = &#39;input-topic&#39;,<br>  &#39;properties.bootstrap.servers&#39; = &#39;kafka:9093&#39;,<br>  &#39;properties.group.id&#39; = &#39;my-group&#39;,<br>  &#39;scan.startup.mode&#39; = &#39;earliest-offset&#39;,<br>  &#39;format&#39; = &#39;json&#39;<br>);<br><br>-- Create sink table to write to Kafka<br>CREATE TABLE sink_table (<br>  `field1` STRING,<br>  `field2` STRING<br>) WITH (<br>  &#39;connector&#39; = &#39;kafka&#39;,<br>  &#39;topic&#39; = &#39;output-topic&#39;,<br>  &#39;properties.bootstrap.servers&#39; = &#39;kafka:9093&#39;,<br>  &#39;format&#39; = &#39;json&#39;<br>);<br><br>-- Define the SQL query to process the data<br>INSERT INTO sink_table<br>SELECT field1, field2<br>FROM source_table<br>WHERE field2 = &#39;correct&#39;;</pre><h4>Java:</h4><pre>package org.example;<br><br>import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;<br>import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;<br><br>public class MyTableExample {<br>    public static void main(String[] args) throws Exception {<br>        // Set up the Flink execution environment<br>        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();<br>        // Set up the Flink table environment<br>        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);<br><br>        // Create source table to read from Kafka<br>        String create_source_table = &quot;CREATE TABLE source_table (\n&quot; +<br>                &quot;    field1 STRING,\n&quot; +<br>                &quot;    field2 STRING\n&quot; +<br>                &quot;) WITH (\n&quot; +<br>                &quot;    &#39;connector&#39; = &#39;kafka&#39;,\n&quot; +<br>                &quot;    &#39;topic&#39; = &#39;input-topic&#39;,\n&quot; +<br>                &quot;    &#39;properties.bootstrap.servers&#39; = &#39;kafka:9093&#39;,\n&quot; +<br>                &quot;    &#39;properties.group.id&#39; = &#39;my-group&#39;,\n&quot; +<br>                &quot;    &#39;scan.startup.mode&#39; = &#39;earliest-offset&#39;,\n&quot; +<br>                &quot;    &#39;format&#39; = &#39;json&#39;\n&quot; +<br>                &quot;)&quot;;<br>        tableEnv.executeSql(create_source_table);<br><br>        // Create sink table to write to Kafka<br>        String create_sink_table = &quot;CREATE TABLE sink_table (\n&quot; +<br>                &quot;    field1 STRING,\n&quot; +<br>                &quot;    field2 STRING\n&quot; +<br>                &quot;) WITH (\n&quot; +<br>                &quot;    &#39;connector&#39; = &#39;kafka&#39;,\n&quot; +<br>                &quot;    &#39;topic&#39; = &#39;output-topic&#39;,\n&quot; +<br>                &quot;    &#39;properties.bootstrap.servers&#39; = &#39;kafka:9093&#39;,\n&quot; +<br>                &quot;    &#39;format&#39; = &#39;json&#39;\n&quot; +<br>                &quot;)&quot;;<br>        tableEnv.executeSql(create_sink_table);<br><br>        // Define the SQL query to process the data<br>        String insertQuery = &quot;INSERT INTO sink_table &quot; +<br>                &quot;SELECT field1, field2 &quot; +<br>                &quot;FROM source_table &quot; +<br>                &quot;WHERE field2 = &#39;correct&#39;&quot;;<br><br>        tableEnv.executeSql(insertQuery);<br>    }<br>}</pre><p>In this Java example, to keep it simple, we are using the SQL API to define our job, just like in the SQL example above. Feel free to explore and experiment with Flink’s Table and DataStream APIs.</p><p>Also we need our pom.xml to include the necessary dependencies for Flink and Kafka:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br>         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>    &lt;groupId&gt;org.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;java-flink&lt;/artifactId&gt;<br>    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;<br><br>    &lt;properties&gt;<br>        &lt;maven.compiler.source&gt;11&lt;/maven.compiler.source&gt;<br>        &lt;maven.compiler.target&gt;11&lt;/maven.compiler.target&gt;<br>        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>    &lt;/properties&gt;<br><br>    &lt;dependencies&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.flink&lt;/groupId&gt;<br>            &lt;artifactId&gt;flink-table-api-java&lt;/artifactId&gt;<br>            &lt;version&gt;1.19.0&lt;/version&gt;<br>            &lt;scope&gt;compile&lt;/scope&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.flink&lt;/groupId&gt;<br>            &lt;artifactId&gt;flink-table-api-java-bridge&lt;/artifactId&gt;<br>            &lt;version&gt;1.19.0&lt;/version&gt;<br>            &lt;scope&gt;compile&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        <br>    &lt;/dependencies&gt;<br><br>&lt;/project&gt;</pre><h3>Submit a Flink Job</h3><p>Flink offers multiple methods to submit jobs to a cluster, each suited for different use cases. For instance, the Command Line Interface (CLI), Web Interface, REST API, or programmatically. We will do it in two ways, using the Flink SQL Client, and via REST using the dashboard.</p><h4>Flink SQL Client:</h4><p>The Flink SQL Client allows you to interact directly with the Flink cluster, including submitting jobs using a SQL-like syntax.</p><p>Access your Flink cluster and from within the JobManager start the SQL client using the following command:</p><pre>./bin/sql-client.sh</pre><p>We now need to run each statement from the SQL job described above individually. First, the two CREATE TABLE statements and only at the end the INSERT INTO.</p><h4>REST (using Dashboard):</h4><p><strong>1. Package Your Flink Job</strong>:</p><p>Ensure your Flink job is packaged as a JAR file.</p><p><strong>2. Access the Flink Dashboard</strong>:</p><p>Open a browser and go to the Flink Dashboard URL <a href="http://localhost:8082/">http://localhost:8082</a>.</p><p><strong>3. Submit the Flink Job</strong>:</p><ul><li>Click on the Submit New Job button.</li><li>Upload your JAR file.</li><li>Select the job class: org.example.MyTableExample.</li><li>Click on the Submit button.</li></ul><p>Congratulations, you were able to submit your first Flink job!</p><p>You can now send data with the right format, for example {field1: &#39;a&#39;, field2: &#39;correct&#39;}, through the input-topic topic and see the results in the output-topic topic.</p><p><strong>Note that our configuration doesn’t support processing malformed json messages.</strong></p><h3>Conclusion</h3><p>By following this guide, you should now have a functional local Flink cluster up and running.</p><p>Also, we explained how to integrate Kafka with your Flink cluster, enabling you to process and analyse streaming data efficiently.</p><p>Not only this, we presented detailed examples of creating Flink jobs using both SQL and Java, showcasing how to read from and write to Kafka topics.</p><p>In the end, we explored two different ways to submit jobs to your Flink cluster: using the Flink SQL Client, and via the REST API using the dashboard. Each method offering unique advantages tailored to different use cases.</p><p>For the complete code and additional resources, please visit <a href="https://github.com/ricardocajo/flink-kafka-local"><strong><em>flink-kafka-local</em></strong></a>.</p><p>This setup will allow you to experiment with different job configurations, connectors, and processing logic in a safe and controlled environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a0a741504f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/how-to-set-up-a-local-flink-cluster-using-docker-0a0a741504f6">How to Set Up a Local Flink Cluster Using Docker</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sleep Tight, Code Right ]]></title>
            <link>https://medium.com/marionete/sleep-tight-code-right-f714910778dc?source=rss----fe96a436cca7---4</link>
            <guid isPermaLink="false">https://medium.com/p/f714910778dc</guid>
            <category><![CDATA[reading]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sleep]]></category>
            <dc:creator><![CDATA[Luis Fernandes]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 09:22:54 GMT</pubDate>
            <atom:updated>2024-06-24T09:22:54.829Z</atom:updated>
            <content:encoded><![CDATA[<p>Sleep is one of the most important factors for health, productivity, and well-being. Yet in our fast-paced, always-on world, many people, especially busy professionals are not prioritizing sleep enough.</p><p>I must confess, writing this article feels a bit ironic as I’ve personally struggled with maintaining healthy sleep habits for years — beginning in university and continuing into my career as a data engineer. I would often stay up late working on projects, then struggle to wake up in the morning feeling rested. My productivity and mood would suffer as a result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJmqu9_8B9gUrq8w4h_URA.jpeg" /><figcaption>Image from <a href="https://www.freepik.com/free-photo/little-boy-sleeping-keyboard-his-laptop_7774482.htm#fromView=search&amp;page=1&amp;position=19&amp;uuid=bfce665a-529a-448f-bbd0-74441886005d">Freepick.com</a> 💤</figcaption></figure><h3>“Why We Sleep” by Matthew Walker</h3><p>It wasn’t until I read Matthew Walker’s eye-opening book “Why We Sleep” that I realized the profound importance of sleep and how it was impacting my life. As Walker explains:</p><blockquote>“The shorter you sleep, the shorter your life. The leading causes of disease and death in developed nations — diseases that are crippling health-care systems, such as heart disease, cancer, Alzheimer’s disease, diabetes — all have causal links to a lack of sleep.”</blockquote><p>Reading this book was a wake-up call for me. I realized that sleep is not a luxury, but a biological necessity that is just as important as diet and exercise for physical and mental health. Chronic sleep deprivation has been linked to a wide range of negative health outcomes, from increased risk of heart disease and stroke to weakened immune function and weight gain, just to name some.</p><h3><strong>The Vital Role of Sleep for Software/Data Engineers</strong></h3><p>For software/data engineers, sleep is especially critical for optimal cognitive performance. Lack of sleep impairs focus, memory, creativity, and problem-solving ability. As Walker notes:</p><blockquote>“Sleep, and in particular REM sleep, is the only time our brain has a chance to go over the day’s events, solidify the memories, and turn those fragmented facts into understanding.”</blockquote><p>Pulling an all-nighter to meet a deadline may seem productive at the moment, but it will likely lead to more errors and slower progress in the long run. Consistently getting 7–9 hours of high-quality sleep per night is ideal for maintaining peak mental performance.</p><p>Since making sleep a priority and implementing some of the healthy habits I’ll outline below, I’ve noticed a significant improvement in my work as a data engineer. I’m more focused, creative, and productive during the day and I also feel better physically and mentally overall.</p><h3><strong>Establishing Healthy Sleep Habits</strong></h3><p>So how can software/data engineers ensure they are getting enough sleep? Here are my personal tips (it worked for me, it might work for you 🤷🏻‍♂️):</p><ul><li><strong>Set a consistent sleep schedule: </strong>Go to bed and wake up at the same time each day, even on weekends (okay, let’s say a little cheat on weekends won’t hurt). This helps regulate your body’s internal clock.</li><li><strong>Create a relaxing bedtime routine: </strong>Engage in calming activities like reading, stretching, or meditation to signal to your body that it’s time to wind down.</li><li><strong>Optimize your sleep environment: </strong>Keep your bedroom cool, dark, and quiet. Avoid screens (TV, phone, computer) for at least an hour before bed.</li><li><strong>Limit caffeine and alcohol: </strong>Caffeine is a stimulant that can disrupt sleep — yeah, I know, there’s no code without coffee, I feel you, just try to avoid it after lunchtime. Regarding alcohol, well it may help you fall asleep faster (😅) but leads to more fragmented sleep later in the night.</li><li><strong>Exercise regularly: </strong>Overall any kind of physical activity promotes better sleep, but avoid intense workouts close to bedtime as they can be stimulating.</li></ul><h3><strong>Final Thoughts</strong></h3><p>I know it can be challenging to make sleep a priority, especially with the demanding nature of roles such as software/data engineering, but I encourage you to make the effort. Your mind and body will thank you, and you may just find that you’re a better professional, and a happier person, for it.</p><p>As Matthew Walker eloquently states:</p><blockquote>“Sleep is the single most effective thing we can do to reset our brain and body health each day — Mother Nature’s best effort yet at contra-death.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f714910778dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/marionete/sleep-tight-code-right-f714910778dc">Sleep Tight, Code Right 💤</a> was originally published in <a href="https://medium.com/marionete">Marionete</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>