<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Krishna Tej Chalamalasetty on Medium]]></title>
        <description><![CDATA[Stories by Krishna Tej Chalamalasetty on Medium]]></description>
        <link>https://medium.com/@chkrishnatej?source=rss-e419453bc98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b4ywj3VdbXeUr955tFPrrQ.jpeg</url>
            <title>Stories by Krishna Tej Chalamalasetty on Medium</title>
            <link>https://medium.com/@chkrishnatej?source=rss-e419453bc98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:04:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chkrishnatej/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Sandboxed My AI Coding Agent with Bubblewrap. It Still Read My Secrets.]]></title>
            <link>https://levelup.gitconnected.com/i-sandboxed-my-ai-coding-agent-with-bubblewrap-it-still-read-my-secrets-d865e8705311?source=rss-e419453bc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/d865e8705311</guid>
            <category><![CDATA[bpftrace]]></category>
            <category><![CDATA[bubble-wrap]]></category>
            <category><![CDATA[sandbox]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Krishna Tej Chalamalasetty]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 16:26:55 GMT</pubDate>
            <atom:updated>2026-11-04T16:26:55.674Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sandboxing an AI Coding Agent with Bubblewrap. What the Kernel Actually Enforces</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fC9oEO8tIwumUZhfCmEgOQ.png" /></figure><h3>🧪 Three Decisions, Three Places</h3><p><em>Same agent. Same sandbox. Different folder. Different blast radius.</em></p><p>Coding agents run real commands on your machine. A README, an issue or a dependency can steer what they run. I kept seeing posts saying agents behave differently depending on where you launch them: /, ~ or ~/dev. I wanted to know why at the kernel level, not just that they do.</p><p>So I wrapped a minimal coding agent in a sandbox I built myself, traced every process it started, and asked one question about every result: <strong>which flag decided this, and where in the kernel does that decision happen?</strong></p><p>The short version: a bubblewrap sandbox answers three separate questions in three separate places.</p><ul><li><strong>Can it write?</strong> Decided by the <strong>mount</strong> the path lives on.</li><li><strong>Can it read?</strong> Decided by the <strong>file’s owner and mode bits</strong>, the same as outside the sandbox.</li><li><strong>Can it talk?</strong> Decided by the <strong>network namespace</strong> the process is in.</li></ul><p>My policy controlled the first one well. The other two leaked in every run where the agent could work at all.</p><h3>The Setup</h3><p>pi runs everything with your full access. Whatever sandbox it gets is the one you build, which makes it a clean subject.</p><blockquote><strong><em>Note on Ubuntu 24.04:</em></strong><em> AppArmor blocks unprivileged user namespaces by default, so </em><em>bwrap fails for normal users until you add a small AppArmor profile for it in </em><em>/etc/apparmor.d/bwrap.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHM26Ba5PBnPvODJiLBGjg.png" /></figure><h3>The Policy, Flag by Flag</h3><p>This is the whole sandbox, saved as sandbox-agent:</p><pre>args=(<br>  --ro-bind / /                    # whole filesystem visible, read-only<br>  --dev /dev                       # minimal device nodes<br>  --proc /proc                     # fresh /proc: only sandboxed processes listed<br>  --tmpfs /tmp                     # private, empty /tmp<br>  --bind &quot;$PWD&quot; &quot;$PWD&quot;             # the launch directory is writable<br>  --bind &quot;$HOME/.pi&quot; &quot;$HOME/.pi&quot;   # the agent&#39;s own state<br>  --unshare-pid                    # own PID namespace<br>  --unshare-ipc --unshare-uts      # own IPC objects and hostname<br>  --die-with-parent                # tear down if the launcher dies<br>  --chdir &quot;$PWD&quot;<br>)<br># NET=off also unshares the network namespace<br>[[ &quot;${NET:-on}&quot; == &quot;off&quot; ]] &amp;&amp; args+=(--unshare-net)<br> <br>exec bwrap &quot;${args[@]}&quot; &quot;$@&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*045mDQ7C1WNwHUIx9H5Pxw.png" /></figure><h4>How bwrap turns these flags into a sandbox</h4><p>It helps to know what bwrap actually does with that list, because every result later comes back to it:</p><ol><li><strong>It creates new namespaces.</strong> One for mounts, plus one for each --unshare-* flag. Anything not unshared, like the network here, stays shared with the host.</li><li><strong>It builds a new root from nothing.</strong> The new mount namespace starts with an empty tmpfs root that the host never sees.</li><li><strong>It applies the filesystem flags in order.</strong> --ro-bind / / goes in first, as the base layer. Every later flag mounts <strong>on top of</strong> it. The bwrap man page says it directly: filesystem options are applied in the order they are given. That&#39;s why --bind &quot;$PWD&quot; can be writable inside a read-only root.</li><li><strong>It switches into that root</strong> with pivot_root, so the host&#39;s real mounts are no longer reachable.</li><li><strong>It drops capabilities.</strong> From the man page: <em>“By default no caps are left in the sandboxed process.”</em> Even as root.</li><li><strong>It runs the command.</strong></li></ol><p>Keep steps 3 and 5 in mind. They explain most of what follows.</p><h3>The Observers</h3><h4>Giving the agent its own cgroup</h4><p>To trace only the agent, it needs something that marks its processes apart from everything else on the VM. I launched pi with systemd-run:</p><blockquote><strong><em>systemd-run</em></strong><em> </em>“may be used to create and start a transient .service or .scope unit and run the specified COMMAND in it.”<em> With </em><em>--scope, the command runs in the foreground in a transient scope, and every scope gets its own cgroup.</em></blockquote><pre>PI=&quot;pi --provider deepseek --model deepseek-v4-flash&quot;<br> <br># Run A: no sandbox<br>systemd-run --user --scope --unit=agent-A -- $PI<br># Runs B-D: the same, wrapped in the sandbox<br>systemd-run --user --scope --unit=agent-B -- sandbox-agent $PI</pre><p>bubblewrap doesn’t move processes between cgroups, so everything pi and the sandbox spawn stays in that scope’s cgroup. That’s the handle the tracer filters on.</p><h4>The tracer: agent-exec.bt</h4><pre>BEGIN {<br>  printf(&quot;%-7s %-7s %-3s %-11s %-11s %-11s %-11s %s\n&quot;,<br>         &quot;PID&quot;, &quot;PPID&quot;, &quot;LVL&quot;, &quot;PIDNS&quot;, &quot;MNTNS&quot;, &quot;NETNS&quot;, &quot;USERNS&quot;, &quot;FILE&quot;);<br>}<br> <br>tracepoint:sched:sched_process_exec<br>/ cgroup == cgroupid(&quot;CGROUP_PATH&quot;) /<br>{<br>  $t = curtask;<br>  printf(&quot;%-7d %-7d %-3d %-11u %-11u %-11u %-11u %s\n&quot;,<br>    pid,                                        // PID as the host sees it<br>    $t-&gt;real_parent-&gt;tgid,                      // parent PID, host view<br>    $t-&gt;thread_pid-&gt;level,                      // PID ns depth: 0 = host, 1 = nested<br>    $t-&gt;nsproxy-&gt;pid_ns_for_children-&gt;ns.inum,  // PID ns its children get<br>    $t-&gt;nsproxy-&gt;mnt_ns-&gt;ns.inum,               // mount namespace<br>    $t-&gt;nsproxy-&gt;net_ns-&gt;ns.inum,               // network namespace<br>    $t-&gt;cred-&gt;user_ns-&gt;ns.inum,                 // user namespace<br>    str(args-&gt;filename));                       // binary that was exec&#39;d<br>}</pre><p>What each part does:</p><ul><li><strong>BEGIN { ... }</strong> runs once when bpftrace starts and prints the column header.</li><li><strong>tracepoint:sched:sched_process_exec</strong> is a fixed hook in the kernel that fires every time a process successfully replaces itself with a new program (execve). One event per program started, which is exactly the &quot;what did the agent run&quot; question.</li><li><strong>/ cgroup == cgroupid(&quot;CGROUP_PATH&quot;) /</strong> is a filter that runs <strong>inside the kernel</strong>. cgroup is the cgroup ID of the process that triggered the event, and cgroupid() turns the scope&#39;s path under /sys/fs/cgroup into that ID when the script starts. Events from everything else on the VM are dropped before they reach userspace. CGROUP_PATH is a placeholder I replaced with sed for each run.</li><li><strong>$t = curtask</strong> is a pointer to the kernel&#39;s own record of the process (struct task_struct). bpftrace can walk its fields because the kernel ships its type layouts as BTF in /sys/kernel/btf/vmlinux.</li><li><strong>pid</strong> and <strong>real_parent-&gt;tgid</strong> are the process and its parent, as the <strong>host</strong> numbers them.</li><li><strong>thread_pid-&gt;level</strong> is how deep the process&#39;s PID namespace is nested: 0 for the host, 1 for one sandbox in. This is the LVL column.</li><li><strong>nsproxy-&gt;..._ns-&gt;ns.inum</strong> reads the namespace IDs. nsproxy is the per-process bundle of namespace pointers, and ns.inum is the same inode number ls -l /proc/&lt;pid&gt;/ns shows.</li><li><strong>cred-&gt;user_ns</strong> comes from the process&#39;s credentials instead of nsproxy, because user namespaces are tied to who you are, not just to what you see.</li><li><strong>str(args-&gt;filename)</strong> is the path of the program being started.</li></ul><p>The namespace IDs only mean something next to a baseline. This is my own shell’s, outside everything (I covered how these IDs work in <a href="https://chkrishnatej.dev/posts/isolation-for-containers/">Isolation in Containers</a>):</p><pre>root@krish-dev:~# cat baseline-ns.txt<br>...<br>lrwxrwxrwx 1 root root 0 Oct 27 02:57 mnt -&gt; mnt:[4026531841]<br>lrwxrwxrwx 1 root root 0 Oct 27 02:57 net -&gt; net:[4026531840]<br>lrwxrwxrwx 1 root root 0 Oct 27 02:57 pid -&gt; pid:[4026531836]<br>lrwxrwxrwx 1 root root 0 Oct 27 02:57 user -&gt; user:[4026531837]</pre><h4>The probe: nsprobe</h4><p>nsprobe reports what the process running it can see and do: its identity, PID and namespaces, how many processes it can see, whether it can write in four places, read the fake token and make a direct HTTPS call. pi runs it, so it inherits whatever sandbox pi is in.</p><pre>#!/usr/bin/env bash<br># nsprobe: report what the calling process can see and do.<br># Run it through the agent so it inherits the agent&#39;s sandbox (or lack of one).<br> <br>echo &quot;== identity&quot;<br>echo &quot;user=$(id -un) cwd=$PWD&quot;<br> <br>echo &quot;== pid as seen from this /proc (a small number = own PID namespace)&quot;<br>grep NSpid /proc/self/status<br> <br>echo &quot;== namespace ids (compare with baseline-ns.txt)&quot;<br>for ns in pid mnt net user uts ipc cgroup; do<br>  printf &#39;%-7s %s\n&#39; &quot;$ns&quot; &quot;$(readlink /proc/self/ns/$ns)&quot;<br>done<br> <br>echo &quot;== processes visible&quot;<br>ls -d /proc/[0-9]* 2&gt;/dev/null | wc -l<br> <br>echo &quot;== write tests (error text says who blocked it)&quot;<br>#   &quot;Read-only file system&quot; -&gt; sandbox mount rules<br>#   &quot;Permission denied&quot;     -&gt; ordinary Unix permissions<br>for f in &quot;$PWD/.nsprobe&quot; &quot;$HOME/.nsprobe&quot; &quot;$HOME/.bashrc&quot; &quot;${TMPDIR:-/tmp}/.nsprobe&quot;; do<br>  if err=$(touch &quot;$f&quot; 2&gt;&amp;1); then<br>    echo &quot;OK    $f&quot;<br>  else<br>    echo &quot;FAIL  $f  (${err##*: })&quot;<br>  fi<br>done<br># touch on ~/.bashrc only bumps its timestamp; remove the probe files we created<br>rm -f &quot;$PWD/.nsprobe&quot; &quot;$HOME/.nsprobe&quot; &quot;${TMPDIR:-/tmp}/.nsprobe&quot; 2&gt;/dev/null<br> <br>echo &quot;== read test (fake credential)&quot;<br>head -c 40 &quot;$HOME/.fake-creds/token&quot; 2&gt;&amp;1; echo<br> <br>echo &quot;== direct network (bypassing any proxy)&quot;<br>curl -s --noproxy &#39;*&#39; -m 5 -o /dev/null -w &#39;HTTP %{http_code}\n&#39; https://example.com \<br>  || echo &quot;no direct route&quot;</pre><p>The write tests print the error text, because the error tells you <strong>who</strong> said no:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxOOuiJ6x60PdBuKmdt5dw.png" /></figure><h4>What NSpid tells you</h4><p>Both the probe and the sleep check later rely on one line in /proc/&lt;pid&gt;/status:</p><ul><li><strong>PID namespaces nest.</strong> A process in a sandbox belongs to the sandbox’s PID namespace <strong>and</strong> to every namespace above it, and it has a separate PID in each one.</li><li><strong>NSpid lists all of them</strong>, from the outermost to the innermost. The outermost is the namespace of whoever mounted the /proc you&#39;re reading.</li><li><strong>One value means one namespace.</strong> On the host, an ordinary process shows just its host PID.</li><li><strong>Two values means one level of nesting</strong>: the host’s number first, then the number inside the sandbox, which counts from 1.</li><li><strong>Inside the sandbox you only see the inner number.</strong> The sandbox’s /proc was mounted from inside, so its outermost level is the sandbox itself. That&#39;s why the probe prints a small number like 17.</li><li><strong>It’s the same depth as the tracer’s </strong><strong>LVL.</strong> thread_pid-&gt;level is the kernel&#39;s count of how many levels sit above the innermost one.</li></ul><p>Then I did four runs.</p><h3>Run A — No Sandbox</h3><p>pi was launched from ~/dev/demo with nothing around it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzZEJMX4ZBdMcWN8uVioBw.png" /></figure><p>The tracer:</p><pre>PID     PPID    LVL PIDNS       MNTNS       NETNS       USERNS      FILE<br>20960   20921   0   4026531836  4026531841  4026531840  4026531837  /usr/bin/ls<br>20962   20961   0   4026531836  4026531841  4026531840  4026531837  /usr/bin/which<br>20963   20961   0   4026531836  4026531841  4026531840  4026531837  /usr/local/bin/nsprobe</pre><p>The probe:</p><pre>== identity<br>user=root cwd=/root/dev/demo<br>== pid as seen from this /proc (a small number = own PID namespace)<br>NSpid:	20991<br>== namespace ids (compare with baseline-ns.txt)<br>pid     pid:[4026531836]<br>mnt     mnt:[4026531841]<br>net     net:[4026531840]<br>user    user:[4026531837]<br>uts     uts:[4026531838]<br>ipc     ipc:[4026531839]<br>cgroup  cgroup:[4026531835]<br>== processes visible<br>104<br>== write tests (error text says who blocked it)<br>OK    /root/dev/demo/.nsprobe<br>OK    /root/.nsprobe<br>OK    /root/.bashrc<br>OK    /tmp/.nsprobe<br>== read test (fake credential)<br>FAKE-TOKEN-do-not-use<br> <br>== direct network (bypassing any proxy)<br>HTTP 200</pre><h4>What I observed in run A</h4><ul><li><strong>Same namespaces as my shell.</strong> LVL was 0, and every namespace ID matched the baseline.</li><li><strong>NSpid had a single value</strong>, 20991. One value means one PID namespace: the host&#39;s.</li><li><strong>104 processes visible.</strong> That’s every process on the VM.</li><li><strong>Every write succeeded, </strong><strong>~/.bashrc included.</strong> With no mount namespace, the paths are the real files on disk.</li><li><strong>The token was readable and HTTPS got out</strong>, as expected with nothing in the way.</li><li><strong>The agent ran the probe before it knew what it was.</strong> Its first move was which nsprobe; nsprobe --help 2&gt;&amp;1 | head -50. nsprobe ignores arguments, so --help ran the whole probe: the writes, the token read and the outbound call. pi only noticed afterwards: <em>&quot;</em><em>nsprobe --help doesn&#39;t print help — it just runs the probe itself.&quot;</em></li><li><strong>The same pattern showed up in every run.</strong> In run C, pi’s reasoning said <em>“Let me check if nsprobe exists”</em>, and the check was which nsprobe; nsprobe 2&gt;&amp;1 | head -50. In run B, it ran the probe straight away and only then thought <em>&quot;this is a suspicious command name. Let&#39;s look at it.&quot;</em></li></ul><blockquote><em>Without a sandbox, the agent is simply you. And an agent’s “look before you leap” is usually a leap: its exploring is real execution, so whatever protection you add has to hold for that too, not just for the command you asked for.</em></blockquote><h3>Run B — Sandboxed, from the Project Directory</h3><p>Same launch directory, with pi inside the sandbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zX2nMiJQdPC3_iiOPTnKVA.png" /></figure><p>The tracer, trimmed:</p><pre>PID     PPID    LVL PIDNS       MNTNS       NETNS       USERNS      FILE<br>21271   21270   1   4026532336  4026532333  4026531840  4026531837  /usr/local/bin/nsprobe<br>21272   21271   1   4026532336  4026532333  4026531840  4026531837  /usr/bin/id<br>21274   21271   1   4026532336  4026532333  4026531840  4026531837  /usr/bin/readlink<br>...<br>21284   21283   1   4026532336  4026532333  4026531840  4026531837  /usr/bin/touch<br>21293   21271   1   4026532336  4026532333  4026531840  4026531837  /usr/bin/curl<br>21601   21600   1   4026532336  4026532333  4026531840  4026531837  /usr/bin/sleep</pre><p>The probe:</p><pre>== identity<br>user=root cwd=/root/dev/demo<br>== pid as seen from this /proc (a small number = own PID namespace)<br>NSpid:	17<br>== namespace ids (compare with baseline-ns.txt)<br>pid     pid:[4026532336]<br>mnt     mnt:[4026532333]<br>net     net:[4026531840]<br>user    user:[4026531837]<br>uts     uts:[4026532334]<br>ipc     ipc:[4026532335]<br>cgroup  cgroup:[4026531835]<br>== processes visible<br>6<br>== write tests (error text says who blocked it)<br>OK    /root/dev/demo/.nsprobe<br>FAIL  /root/.nsprobe  (Read-only file system)<br>FAIL  /root/.bashrc  (Read-only file system)<br>OK    /tmp/.nsprobe<br>== read test (fake credential)<br>FAKE-TOKEN-do-not-use<br> <br>== direct network (bypassing any proxy)<br>HTTP 200</pre><p>Then I asked pi to run sleep 60 and looked it up from the host:</p><pre>root@krish-dev:~# grep NSpid /proc/$(pgrep -n sleep)/status<br>NSpid:  21601   42</pre><h4>What I observed in run B</h4><ul><li><strong>New PID, mount, UTS and IPC namespaces. Network, user and cgroup unchanged.</strong> The PID and mount IDs (4026532336, 4026532333) differ from the host&#39;s, and so do UTS and IPC. The network (4026531840), user and cgroup IDs are identical to my shell&#39;s. Only the flags I passed created namespaces, and I never passed --unshare-net.</li><li><strong>One command, 18 programs, all inside.</strong> That single nsprobe started id, grep, seven readlinks, ls, wc, four touches, rm, head and curl. Every one inherited the same namespaces. A sandbox applies to a process and <strong>everything it ever spawns</strong>.</li><li><strong>~/.bashrc failed with </strong><strong>Read-only file system, even as root.</strong> --ro-bind / / doesn&#39;t change any file. It puts a read-only flag on the <strong>mount</strong>, and before any write the kernel checks whether the mount is writable. That check ignores your UID and capabilities. On top of that, bwrap dropped every capability before starting pi, so root inside can&#39;t remount / (needs CAP_SYS_ADMIN) or override permissions (needs CAP_DAC_OVERRIDE).</li><li><strong>The project write worked, and landed on the real disk.</strong> --bind &quot;$PWD&quot; came after --ro-bind / /, so it was mounted on top at /root/dev/demo. When the kernel resolves a path and reaches a mount point, it uses the topmost mount there. A bind mount isn&#39;t a copy. It&#39;s the same directory, visible in a second place.</li><li><strong>The </strong><strong>/tmp write worked, but never reached the host.</strong> --tmpfs /tmp mounts a new, empty, in-memory filesystem on top. The file existed only inside the sandbox and disappeared when it exited.</li><li><strong>The fake token was still readable.</strong> Reading never asks the mount for write access, so the read-only flag never comes into play. A read is checked only against the file’s owner and mode bits, the same as outside the sandbox. The token is owned by root, and the process was UID 0. <strong>A read-only bind controls what can change, not what can be seen.</strong></li><li><strong>6 processes, and one process with two PIDs.</strong> That takes two flags. --unshare-pid gives the sandbox its own PID numbering, so the host&#39;s 21601 is 42 inside. --proc /proc mounts a new procfs, and a procfs lists only <em>&quot;processes visible in the PID namespace of the process that performed the mount&quot;</em> (pid_namespaces(7)). Without --proc, the recursive --ro-bind / / would have brought in the host&#39;s /proc, and the probe would have counted 104 again.</li><li><strong>HTTPS still got out.</strong> pi stayed in the host’s network namespace, with the same interfaces and routes. DNS worked because /etc/resolv.conf was readable through the read-only root and pointed at the systemd-resolved stub on 127.0.0.53, which sits on the shared loopback.</li></ul><blockquote><em>The sandbox controlled writes well, because writes are a mount question and mounts were what I configured. It didn’t control reads, because reads aren’t a mount question. And it didn’t control the network, because I never unshared it. As far as secrets and the network go, run B is run A.</em></blockquote><h3>Run C — Same Sandbox, Launched from ~</h3><p>The policy didn’t change. Only the directory I started from did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miqTu3cn617GalB_WImgSg.png" /></figure><p>The probe:</p><pre>== identity<br>user=root cwd=/root<br>== pid as seen from this /proc (a small number = own PID namespace)<br>NSpid:	44<br>== namespace ids (compare with baseline-ns.txt)<br>pid     pid:[4026532334]<br>mnt     mnt:[4026532330]<br>net     net:[4026531840]<br>user    user:[4026531837]<br>uts     uts:[4026532331]<br>ipc     ipc:[4026532333]<br>cgroup  cgroup:[4026531835]<br>== processes visible<br>5<br>== write tests (error text says who blocked it)<br>OK    /root/.nsprobe<br>OK    /root/.nsprobe<br>OK    /root/.bashrc<br>OK    /tmp/.nsprobe<br>== read test (fake credential)<br>FAKE-TOKEN-do-not-use<br> <br>== direct network (bypassing any proxy)<br>HTTP 200</pre><h4>What I observed in run C</h4><ul><li><strong>Still sandboxed.</strong> New PID and mount namespaces (fresh IDs, since it’s a new sandbox), NSpid of 44 and 5 processes visible. Network and user namespaces unchanged again.</li><li><strong>OK /root/.nsprobe appears twice.</strong> $PWD and $HOME were both /root, so the probe&#39;s first two write tests hit the same file.</li><li><strong>Every write succeeded, </strong><strong>~/.bashrc included.</strong> --bind &quot;$PWD&quot; &quot;$PWD&quot; now meant --bind /root /root. That writable mount sat on top of the read-only root at /root, so <strong>everything under it</strong> resolved to a writable mount: dotfiles, ~/.fake-creds, and ~/.ssh if it existed. The ~/.pi bind on top became redundant.</li><li><strong>A writable </strong><strong>~/.bashrc is a way out of the sandbox.</strong> Whatever the agent appends runs the next time you open a shell, outside the sandbox, as you, with every capability bwrap took away. The probe only touched the file. A prompt-injected command wouldn&#39;t stop there.</li><li><strong>The token and network behaved exactly as in run B.</strong></li></ul><blockquote><em>The policy didn’t change, but its input did. A sandbox that binds </em><em>$PWD turns the launch directory into part of the policy. That&#39;s the real explanation behind the &quot;different behavior in </em><em>/ vs </em><em>~ vs </em><em>~/dev&quot; posts: launch this script from </em><em>/ and the whole disk is writable.</em></blockquote><h3>Run D — Cutting the Network</h3><p>NET=off adds --unshare-net, so the sandbox gets a new, empty network namespace. I asked pi to run the probe again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSLbeoujDLbrtOSGVmeINQ.png" /></figure><pre>Error: Connection error.<br>Error: Connection error.<br>Error: Connection error.<br>Error: Connection error.<br>Error: Retry failed after 3 attempts: Connection error.</pre><h4>What I observed in run D</h4><ul><li><strong>pi never ran a single command.</strong> The tracer log for this run had only its header.</li><li><strong>The new network namespace had only a loopback interface.</strong> No route out. The resolver at 127.0.0.53 lives on the <strong>host&#39;s</strong> loopback, not the new one, so most likely even the DNS lookup for the API failed.</li><li><strong>The agent and its commands share one network namespace.</strong> A namespace belongs to a process, and children inherit it. Wrapping the whole agent puts its API calls inside the same boundary as its commands. There’s no flag that says “pi may reach api.deepseek.com but its curl may not&quot;.</li><li><strong>This is why per-command sandboxing exists.</strong> <a href="https://code.claude.com/docs/en/sandboxing">Claude Code sandboxes each shell command</a> instead of the whole agent. On Linux, each command runs in a network namespace with no route out, and its traffic goes through a proxy on the host that checks domains against an allowlist.</li></ul><blockquote><em>Cutting the network worked perfectly, and that was the problem. When you wrap the whole agent, you can’t cut its commands off from the internet without cutting the agent off from its model.</em></blockquote><h3>What Each Flag Actually Decided</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*017flzFglcPq0r_lBStNdA.png" /></figure><blockquote><strong><em>Note on running as root:</em></strong><em> I ran everything as root on the VM, so bwrap didn’t need a user namespace and the user namespace ID never changed. As a normal user, bwrap creates one to get the privileges it needs to build the sandbox, which is what the AppArmor change is for. The token result would be the same: you’d own the token, so you could read it. Treat these as lab numbers, not a production setup.</em></blockquote><h4>What this policy doesn’t do at all</h4><p>Three things never came up in the probe, but they’re worth knowing:</p><ul><li><strong>No syscall filter.</strong> There’s no seccomp profile, so every system call is available. The sandbox shares the host kernel, and a kernel bug is a way out.</li><li><strong>No resource limits.</strong> bwrap doesn’t touch cgroups. A runaway build or a fork bomb inside the sandbox uses your machine’s CPU and memory. The systemd-run scope I used for tracing is the natural place to add limits like -p MemoryMax=.</li><li><strong>No protection for what’s already writable.</strong> Everything in the project directory can be read, changed or deleted. The sandbox protects the rest of the machine, not your work.</li></ul><h3>What I’ll Change for the Next Run</h3><p>Three small changes target the three leaks. <strong>I haven’t rerun the probe against them yet</strong>, so treat this as the plan, not a result:</p><pre># 1. Refuse to make your home (or the whole disk) &quot;the project&quot;<br>if [[ &quot;$PWD&quot; == &quot;$HOME&quot; || &quot;$PWD&quot; == &quot;/&quot; ]]; then<br>  echo &quot;sandbox-agent: launch from a project directory, not $PWD&quot; &gt;&amp;2<br>  exit 1<br>fi<br> <br># 2. Hide secrets: mount an empty tmpfs over each secret directory that exists.<br>#    Appended after --ro-bind / /, so it sits on top and wins.<br>for d in &quot;$HOME/.ssh&quot; &quot;$HOME/.aws&quot; &quot;$HOME/.fake-creds&quot;; do<br>  if [[ -d &quot;$d&quot; ]]; then<br>    args+=(--tmpfs &quot;$d&quot;)<br>  fi<br>done<br> <br># 3. Network: wrapping the whole agent can&#39;t fix this one.<br>#    It needs per-command sandboxing with a filtering proxy.</pre><p>The first two fit in the same 20 lines. The third one is why the next post runs the same probe against Claude Code’s per-command sandbox.</p><h3>Putting It Together</h3><p>The sandbox did exactly what I told it to. The problem was what I didn’t know I was telling it:</p><ul><li><strong>Writes</strong> are decided by mounts. --ro-bind and --bind gave me real control here, but the launch directory quietly decides how much is writable.</li><li><strong>Reads</strong> are decided by ownership, exactly as outside the sandbox. A read-only bind exposes everything it brings in.</li><li><strong>The network</strong> is decided by a namespace the agent itself needs, so wrapping the whole agent can’t close it.</li></ul><p>Namespaces held the boundary in every run. The leaks were all in my policy: a read-only bind over secrets, a launch directory that was too wide, and a network that had to stay open for the agent to work.</p><p>A sandbox makes mistakes smaller, not impossible. It still shares your kernel.</p><h3>References</h3><ul><li><a href="https://github.com/containers/bubblewrap">bubblewrap — GitHub</a> and its bwrap(1) man page</li><li><a href="https://man7.org/linux/man-pages/man1/systemd-run.1.html">systemd-run(1)</a></li><li><a href="https://github.com/bpftrace/bpftrace">bpftrace</a></li><li><a href="https://man7.org/linux/man-pages/man7/pid_namespaces.7.html">pid_namespaces(7)</a>, <a href="https://man7.org/linux/man-pages/man5/proc_pid_status.5.html">proc_pid_status(5)</a> for NSpid</li><li><a href="https://man7.org/linux/man-pages/man7/mount_namespaces.7.html">mount_namespaces(7)</a>, <a href="https://man7.org/linux/man-pages/man7/network_namespaces.7.html">network_namespaces(7)</a></li><li><a href="https://code.claude.com/docs/en/sandboxing">Configure the sandboxed Bash tool — Claude Code docs</a></li><li><a href="https://chkrishnatej.dev/posts/isolation-for-containers/">Isolation in Containers. Linux Primitives that help Achieve It</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d865e8705311" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/i-sandboxed-my-ai-coding-agent-with-bubblewrap-it-still-read-my-secrets-d865e8705311">I Sandboxed My AI Coding Agent with Bubblewrap. It Still Read My Secrets.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Container? The OS-Level Truth Most Engineers Don’t Know]]></title>
            <link>https://levelup.gitconnected.com/what-is-a-container-the-os-level-truth-most-engineers-dont-know-98324c31ac62?source=rss-e419453bc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/98324c31ac62</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Krishna Tej Chalamalasetty]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 17:11:40 GMT</pubDate>
            <atom:updated>2026-04-06T17:11:40.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYRxD7bVLdS3CELex1_cZQ.jpeg" /></figure><h3>“You Keep Using That Word”. Dispelling Container Misconceptions at the OS Level</h3><p><em>Before we write a single line of code, we need to kill the buzzword fog.</em></p><p>This blog is originally published at <a href="https://chkrishnatej.dev/posts/what-is-a-container-the-os-level-truth-most-engineers-dont-know/">https://chkrishnatej.dev/posts/what-is-a-container-the-os-level-truth-most-engineers-dont-know/</a></p><h3>What a Container Actually Is</h3><p>The marketing definition you have heard a hundred times:</p><p>”<em>a container is an executable unit of software with its dependencies bundled together</em>.”</p><p>That is not wrong, but it tells you nothing useful about what is actually happening on the machine.</p><p>Here is the OS-level truth:</p><p><em>“a container is a process (or a tree of processes) that the kernel runs with a restricted view of its own namespaces and a cgroup-enforced ceiling on the resources it can consume.”</em></p><p>That is the entire trick. No hypervisor, no guest kernel, no virtualized hardware. Just a process with a carefully constructed set of constraints.<br>Everything else in this article is evidence for that single claim.</p><h3>Spin up a simple HTTPD container</h3><p>I used the following podman command to spin up the HTTPD container with limited amount of resources.</p><pre>podman run -d \<br> - name my-limited-httpd \<br> - replace \<br> - memory=512m \ # hard memory ceiling<br> - memory-swap=512m \ # swap ceiling equal to memory = no swap allowed<br> - cpus=1.5 \ # CPU quota: 1.5 cores worth of CPU time<br> - cpu-shares=512 \ # relative CPU weight during contention<br> - pids-limit=100 \ # max 100 processes/threads in this container<br> - blkio-weight=500 \ # relative block I/O weight<br> -p 8081:80 \<br> registry.access.redhat.com/ubi8/httpd-24</pre><p>This starts a container with the given resources. You can check</p><pre>krish-local:~ # pstree -pT<br>systemd(1)─┬─NetworkManager(944)<br> ├─agetty(1011)<br> ├─agetty(1012)<br> ├─auditd(835)<br> ├─chronyd(1007)<br> # ConMon is container monitor. HTTPD is the container we ran<br> ├─conmon(13669)───httpd(13684)─┬─cat(13727) <br> │ ├─cat(13728)<br> │ ├─cat(13729)<br> │ ├─cat(13730)<br> │ ├─httpd(13731)<br> │ ├─httpd(13734)<br> │ └─httpd(35659)<br> ├─dbus-broker-lau(854)───dbus-broker(856)<br> ├─dotd(959)───sleep(3951905)<br> ├─irqbalance(858)<br> ├─rsyslogd(1159)<br> ├─sshd(1562)───sshd-session(3949831)───sshd-session(3950094)───bash(3950096)───pstree(3954963)<br> ├─systemd(3950077)───(sd-pam)(3950079)<br> ├─systemd-journal(621)<br> ├─systemd-logind(890)<br> ├─systemd-udevd(657)<br> └─wpa_supplicant(891)</pre><h3>From podman run to a Process — What Actually Happens</h3><p>When you ran <strong><em>podman run</em></strong>, Podman did not start <strong><em>httpd</em></strong> directly. It handed the work to an OCI runtime. On SLES 16, that runtime is <strong><em>crun</em></strong> (you can verify with <strong><em>podman info | grep -i runtime</em></strong>). <strong><em>crun</em></strong> is the thing that actually calls <strong><em>clone()</em></strong> with the right namespace flags, writes the cgroup limits into <strong><em>/sys/fs/cgroup</em></strong>, sets up the root filesystem from the image layers, and then calls <strong><em>execve()</em></strong> to start your process. <br><strong><em>runc</em></strong> does the same job but its original OCI reference runtime is written in Go. <strong><em>crun</em></strong> is a C rewrite that is lighter and faster, and is now the default on most modern distros.</p><p><strong><em>conmon</em></strong> in the <strong><em>pstree</em></strong> output is the container monitor that acts as a small supervisor process that holds the container’s stdio open, watches for the OCI runtime to exit, and reports container exit codes back to Podman. It is not part of your workload. It is bookkeeping infrastructure.</p><p>So the full chain is:</p><pre>podman → crun → clone() + execve() → your processpl</pre><p>By the time <strong><em>httpd</em></strong> appears in the process table, <strong><em>crun</em></strong> has already exited. Its job was setup, not supervision.</p><h3>Four Words the Industry Uses Interchangeably — and Shouldn’t</h3><p>These four terms get collapsed into each other constantly. The confusion is not accidental. Vendors benefit from the blurring. But it costs engineers clarity when something breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcUzg09tIwgF8UT1bCyxwA.png" /></figure><h3>What an Image Actually Is</h3><p>An image is a blueprint. A container is one running instance of it. You can start ten containers from the same image simultaneously and each one gets its own thin writable layer on top of the shared read-only filesystem layers underneath. The image itself never runs. It is inert until a runtime turns it into a process.</p><p><strong>At the OCI spec level:</strong> an image is a stack of read-only filesystem layers plus a JSON config manifest. When you run a container, the OCI runtime (crun on most modern Linux systems, runc historically) unpacks those layers into a root filesystem, applies the runtime constraints, and hands a process off to the kernel.</p><ul><li>Image = what to run.</li><li>Runtime spec = how to run it</li><li>The container = the process that results.</li></ul><h3>The PID 1 Myth</h3><p><strong>The belief:</strong> there is a mini Linux inside the container, and PID 1 is its init system — the root of a private process universe.</p><p><strong>The reality: </strong>PID 1 is namespace-relative. The first process spawned inside a new PID namespace gets assigned PID 1 <em>within that namespace</em>. It is simultaneously visible on the host with a completely different PID. One process, two identities, depending on which namespace you are observing from.</p><p>Let us verify this directly. The <strong><em>nsenter</em></strong> command lets us step into a process’s namespaces and run a command from inside them.</p><p><strong>Stepping into the host’s namespaces (PID 1 = systemd):</strong></p><pre># Enter PID 1&#39;s PID namespace (-p) and mount namespace (-m, needed so<br># /proc reflects the target namespace) and run ps<br>krish-local:~ # nsenter -t 1 -p -m ps -ef<br>UID PID PPID C STIME TTY TIME CMD<br>root 1 0 0 Mar29 ? 00:00:05 /usr/lib/systemd/systemd - switched-root - system - deserialize=47<br>root 2 0 0 Mar29 ? 00:00:00 [kthreadd]<br>root 3 2 0 Mar29 ? 00:00:00 [pool_workqueue_release]<br>root 4 2 0 Mar29 ? 00:00:00 [kworker/R-kvfree_rcu_reclaim]<br>root 5 2 0 Mar29 ? 00:00:00 [kworker/R-rcu_gp]<br>…</pre><p><strong>Stepping into the container’s namespaces (container process host PID = 13684):</strong></p><pre># Same command, but targeting the container&#39;s PID namespace.<br># Inside this namespace, httpd was the first process spawned - so it gets PID 1.<br>krish-local:~ # nsenter -t 13684 -p -m ps -ef<br>UID PID PPID C STIME TTY TIME CMD<br>default 1 0 0 01:47 ? 00:00:29 httpd -D FOREGROUND<br>default 38 1 0 01:47 ? 00:00:00 /usr/bin/coreutils - coreutils-prog-shebang=cat /usr/bin/cat<br>default 39 1 0 01:47 ? 00:00:00 /usr/bin/coreutils - coreutils-prog-shebang=cat /usr/bin/cat<br>default 40 1 0 01:47 ? 00:00:00 /usr/bin/coreutils - coreutils-prog-shebang=cat /usr/bin/cat<br>default 41 1 0 01:47 ? 00:00:00 /usr/bin/coreutils - coreutils-prog-shebang=cat /usr/bin/cat<br>default 42 1 0 01:47 ? 00:00:29 httpd -D FOREGROUND<br>default 45 1 0 01:47 ? 00:00:17 httpd -D FOREGROUND<br>root 615091 0 0 10:11 ? 00:00:00 ps -ef</pre><p>That <strong><em>httpd</em></strong> process sitting at PID 1 inside the container namespace? On the host, it is PID 13684. Same process, different lens.</p><p><strong>The Shared Kernel — <em>uname</em> Does Not Lie</strong></p><p>If there were a mini Linux inside, it would have its own kernel, its own kernel version, its own architecture identity. Run <strong><em>uname</em></strong> on the host and inside the container and compare:</p><p><strong>Host:</strong></p><pre>krish-local:~ # uname -s &amp;&amp; uname -m &amp;&amp; uname -o &amp;&amp; uname -r<br>Linux<br>x86_64<br>GNU/Linux<br>6.12.0–160000.9-default</pre><p><strong>Inside the container:</strong></p><pre>krish-local:~ # podman exec my-limited-httpd `uname -s &amp;&amp; uname -m &amp;&amp; uname -o &amp;&amp; uname -r`<br>Linux<br>x86_64<br>GNU/Linux<br>6.12.0–160000.9-default</pre><p>Identical output. The container is not running a different kernel but, it is sharing the host kernel. The UTS namespace gives it an isolated hostname, but kernel identity is not part of that isolation. There is no guest kernel to find.</p><h3>Resource Isolation: cgroups Are the Real Enforcement Mechanism</h3><p>Namespaces control <strong><em>what a process can see</em></strong>. cgroups control <strong><em>what a process can consume</em>.</strong> Together they are the two pillars of container isolation.</p><blockquote><strong>Note on cgroup versions:</strong> The demos below use cgroup v2 paths (<strong><em>/sys/fs/cgroup/&lt;scope&gt;/memory.max</em></strong>), which is the unified hierarchy used by SLES 16 with kernel 6.12. If you are on an older distro still running cgroup v1, your paths will look different (<strong><em>/sys/fs/cgroup/memory/&lt;scope&gt;/memory.limit_in_bytes</em></strong>).</blockquote><p>Now compare cgroup limits for systemd (PID 1 on the host) versus the container process.</p><p><strong>systemd — no enforced ceiling:</strong></p><pre>krish-local:~ # CGROUP=$(cat /proc/1/cgroup | cut -d: -f3)<br>krish-local:~ # echo $CGROUP<br>/init.scope<br>krish-local:~ # cat /sys/fs/cgroup${CGROUP}/memory.max<br>max<br>krish-local:~ # cat /sys/fs/cgroup${CGROUP}/pids.max<br>max</pre><p><strong><em>max</em></strong> means unlimited. The init process is not constrained.</p><p><strong>The container process — enforced ceiling:</strong></p><pre>krish-local:~ # PID=13684 # container&#39;s PID on the host<br>krish-local:~ # CGROUP=$(cat /proc/$PID/cgroup | cut -d: -f3)<br>krish-local:~ # echo $CGROUP<br>/machine.slice/libpod-a67892f3083285e34c738fd1e75cccd7eaadbda71f5a8c60a522e73546c0d5a2.scope<br>krish-local:~ # cat /sys/fs/cgroup${CGROUP}/memory.max<br>536870912<br>krish-local:~ # cat /sys/fs/cgroup${CGROUP}/pids.max<br>100</pre><p><strong><em>536870912</em></strong> <strong><em>bytes = 512 MiB</em></strong>. Exactly the. <strong><em>— memory=512m</em></strong> flag we passed at startup. The <strong><em>pids.max</em></strong> of 100 matches <strong><em>— pids-limit=100</em></strong>. The kernel is enforcing these budgets directly , not Podman, not any container runtime abstraction sitting above the kernel.</p><h3>Putting It Together</h3><p>A container is a process. It shares the host kernel and <strong><em>uname</em></strong> proves it. Its PID 1 is an artifact of namespace isolation, not evidence of a private OS and <strong><em>nsenter</em></strong> proves it. Its resource limits are enforced by cgroups in the kernel, not by any runtime magic and <strong><em>/sys/fs/cgroup</em></strong> proves it.</p><p>The image is the blueprint.<strong><em> crun/runc</em></strong> is the assembly line. The running container is just another entry in the host’s process table, one that happens to have a restricted worldview and a constrained resource budget.</p><p>That is the mental model. Everything in Part 2 builds on top of it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98324c31ac62" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/what-is-a-container-the-os-level-truth-most-engineers-dont-know-98324c31ac62">What is a Container? The OS-Level Truth Most Engineers Don’t Know</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From OOM Crashes to 85% Faster Onboarding: Scaling ID Generation with Redis]]></title>
            <link>https://levelup.gitconnected.com/from-oom-crashes-to-85-faster-onboarding-scaling-id-generation-with-redis-716f5224bf3c?source=rss-e419453bc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/716f5224bf3c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Krishna Tej Chalamalasetty]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 17:43:12 GMT</pubDate>
            <atom:updated>2026-03-26T13:47:36.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4RC0pf68qX-E96CA2d29g.png" /></figure><h3>It Started with a Simple Counter</h3><p>I work on a cloud-based document management platform used by large construction and engineering firms. Every document uploaded drawings, RFIs, approvals gets an unique ID following a tenant-defined schema:</p><pre>PROJ-9012-1001<br>  │      │     │<br>  │      │     └── Sequence number (auto-incremented)<br>  │      └──────── Document type identifier<br>  └──────────────── Project code</pre><p>An internal microservice called id-generator handled this. It worked fine for years, a closed system behind our portal, moderate traffic, no drama.</p><p>Then we opened Public APIs so customers could automate their workflows. And the first large customer tried to migrate 200,000 documents in a single batch.</p><p>The id-generator was called once per document, sequentially. Each call was a network hop. The migration ran for over six hours. The customer was not pleased.</p><h3>Why Sequential Doesn’t Scale: The Math</h3><p>A single ID generation involves a network round-trip to the id-generator (~100ms) plus the generator’s own processing and sequence counter commit (~50ms). Call it <strong>150ms per ID</strong>.</p><p>For 200,000 documents, sequential processing means:</p><pre>200,000 × 150ms = 30,000 seconds ≈ 8.3 hours</pre><p>“Just add more app instances” doesn’t help. We can spread requests across three instances behind a load balancer, but all three call the <strong>same id-generator</strong>. The generator processes one request at a time to guarantee sequential numbering. The bottleneck isn’t the app layer, it’s the single-threaded sequence generation.</p><p>Even if I made the id-generator handle<strong> 10 concurrent requests</strong> (with database level locking on the counter):</p><pre>200,000 ÷ 10 concurrent × 150ms = 3,000 seconds ≈ 50 minutes</pre><p>Better, but fragile. The id-generator becomes a high contention hotspot, and any slowdown cascades to every project uploading at the same time.</p><p>I needed to <strong>decouple ID consumption from ID generation entirely, </strong>serve IDs without waiting for the generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2OCnvHLKef-HSsxWfPGYQ.png" /><figcaption>The Bottleneck</figcaption></figure><h3>The Architecture</h3><p>This is a <strong>classic producer-consumer</strong> problem. Thousands of clients across different projects and organizations fire upload requests through an API gateway. The gateway distributes traffic across multiple app instances. But all instances need IDs from the same sequence space per (project, documentType), and a single producer (the id-generator) feeds that space.</p><p><strong>The insight:</strong> if I pre-generate IDs in bulk and stash them in a shared store, the app instances become <strong>consumers</strong> popping from a ready made pool, while the id-generator becomes a <strong>background producer</strong> that refills the pool asynchronously. Consumers never wait for the producer. The pool is the buffer that decouples them.</p><p>I chose Redis as that shared store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuuCRfF_BTsquD_CCAGX7A.png" /><figcaption>Producer-Consumer Architecture</figcaption></figure><h3>The Fix: Pre-populated ID Pools in Redis</h3><p>The idea is straightforward. Instead of generating an ID when a request arrives, generate them ahead of time and stash them in Redis. When a request comes in, pop one off the list. No waiting.</p><p>Each (project, documentType) combination gets its own Redis List:</p><pre>Key:   id-pool:PROJ:9012<br>Value: [&quot;1001&quot;, &quot;1002&quot;, &quot;1003&quot;, ..., &quot;2000&quot;]   ← 1000 pre-generated IDs</pre><blockquote>LPOP gives us an atomic, O(1) retrieval. One pop, one ID, sub-millisecond.</blockquote><p>But a pool drains. I needed a way to refill it before it runs dry.</p><h3>Threshold-based Replenishment</h3><p>I used a watermark pattern, borrowed from stream processing systems like Kafka and Flink. You define a threshold level on a resource, and when usage crosses that mark, you trigger an action <em>before</em> the resource is exhausted.</p><p>Think of a water tank with a sensor at the 25% mark: when water drops below it, you automatically reorder before the tank runs dry.</p><p><strong>In my case:</strong> each time an ID is served, I check the pool size. When <strong>75%</strong> of the pool has been consumed (250 or fewer remaining out of 1000), I kick off an async task that calls the id-generator for a fresh batch and pushes them into the Redis list.</p><pre>public String fetchNextId(String projectCode, String docTypeId) {<br>    String poolKey = &quot;id-pool:&quot; + projectCode + &quot;:&quot; + docTypeId;<br>    // Atomic pop - O(1), sub-ms<br>    String sequence = redisTemplate.opsForList().leftPop(poolKey);<br>    if (sequence == null) {<br>        // Pool empty - synchronous fallback (discussed later)<br>        sequence = idGenerator.generateSingle(projectCode, docTypeId);<br>    }<br>    checkAndReplenish(poolKey, projectCode, docTypeId);<br>    return projectCode + &quot;-&quot; + docTypeId + &quot;-&quot; + sequence;<br>}</pre><p>The replenishment runs on a bounded thread pool with CallerRunsPolicy . If the pool and queue are saturated, the request thread itself does the refill. This applies natural backpressure instead of silently dropping work. Or so I thought.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcCXjlwaDG4OV86aheZE1Q.png" /><figcaption>Pool Architecture — Happy Path</figcaption></figure><p>This worked beautifully in testing. Sub millisecond ID retrieval. Invisible background replenishment. We shipped it.</p><h3>The Production Outage: OOM from a Thundering Herd</h3><p>Within a week of going live with the large customer migration, the service started crashing with java.lang.OutOfMemoryError: Java heap space. Repeatedly.</p><p>I pulled a heap dump and started analysing it. The heap was full of hundreds of ArrayList&lt;String&gt; instances, each holding a thousand generated IDs. They were all alive simultaneously.</p><p><strong>The root cause was a race condition in the replenishment logic.</strong></p><p><strong>Here’s what happened:</strong> during a bulk upload, thousands of concurrent requests hit the service. Multiple requests for the <em>same</em> (project, docType) would check the pool level at nearly the same instant, all see &quot;below 75%&quot;, and all independently trigger replenishAsync(). Multiply this across hundreds of (project, docType) combinations, and you get hundreds of async tasks, each generating and holding a 1000 element list in memory.</p><p>The heap couldn’t take it.</p><p>Counterintuitively, the CallerRunsPolicy I&#39;d chosen for backpressure made things worse. It was supposed to prevent RejectedExecutionException when the executor&#39;s queue filled up. It did by making the request-handling threads <em>also</em> run generation tasks, adding even more large lists to the heap. The policy solved thread pool rejection but amplified the memory problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0_STGjlMI-FGr6IKCt1Pg.png" /><figcaption>The Thundering Herd</figcaption></figure><h3>The Fix: Redis Distributed Locks</h3><p>The problem was clear: nothing prevented duplicate replenishment for the same pool key. I needed a mutex, but a Java ReentrantLock or synchronized block only protects a single JVM. Our service runs on multiple instances behind a load balancer. Instance A&#39;s lock means nothing to Instance B.</p><p>I needed a distributed lock. Redis gives you one with a single command:</p><pre>SET lock:id-pool:PROJ:9012 &quot;a1b2c3-uuid&quot; NX EX 120</pre><p>NX means &quot;only set if it doesn&#39;t exist&quot;, atomic check-and-acquire. EX 120 means &quot;auto-expire after 120 seconds&quot;, prevents deadlocks if the holder crashes.</p><h3>The Subtle Bug: Safe Lock Release</h3><p>My first implementation used a simple DELETE in the finally block. This has a nasty race condition:</p><pre>t=0s    Instance A acquires lock (TTL=60s)<br>t=65s   Lock auto-expires (A&#39;s generation was slow)<br>t=66s   Instance B acquires the lock<br>t=70s   Instance A finishes → DELETE → deletes B&#39;s lock<br>t=71s   Instance C sees no lock → acquires → duplicate work</pre><p><strong>The fix:</strong> store a UUID as the lock value, and use a Lua script for atomic compare-and-delete. An instance only deletes the lock if the value still matches its own UUID.</p><p><strong>Why Lua?</strong> Redis doesn’t offer a native “<strong>delete if value equals X</strong>” command. A GET followed by a conditional DELETE in application code has a race window another instance could acquire the lock between the GET and DELETE. Lua scripts execute atomically inside Redis, eliminating that gap.</p><pre>@Async(&quot;idGenExecutor&quot;)<br>public void replenishAsync(String projectCode, String docTypeId) {<br>    String lockKey = &quot;lock:id-pool:&quot; + projectCode + &quot;:&quot; + docTypeId;<br>    String lockValue = UUID.randomUUID().toString();<br>    // Atomic acquire: SET NX EX<br>    Boolean acquired = redisTemplate.opsForValue()<br>        .setIfAbsent(lockKey, lockValue, Duration.ofSeconds(120));<br>    if (Boolean.FALSE.equals(acquired)) {<br>        return;  // Someone else is handling it<br>    }<br>    try {<br>        // Double-check pool level under lock - another instance<br>        // may have already refilled between our check and acquire<br>        Long currentSize = redisTemplate.opsForList().size(poolKey);<br>        if (currentSize &gt; POOL_SIZE * 0.5) {<br>            return;  // Already refilled<br>        }<br>        List&lt;String&gt; newIds = idGenerator.generateBatch(<br>            projectCode, docTypeId, POOL_SIZE - currentSize.intValue());<br>        redisTemplate.opsForList().rightPushAll(poolKey, newIds);<br>    } finally {<br>        // Lua script: delete ONLY if value matches our UUID<br>        String lua = <br>            &quot;if redis.call(&#39;get&#39;,KEYS[1]) == ARGV[1] then &quot; +<br>            &quot;  return redis.call(&#39;del&#39;,KEYS[1]) &quot; +<br>            &quot;else return 0 end&quot;;<br>        redisTemplate.execute(<br>            new DefaultRedisScript&lt;&gt;(lua, Long.class),<br>            List.of(lockKey), lockValue);<br>    }<br>}</pre><p>The double-check after acquiring the lock is the distributed equivalent of double-checked locking between the time I decided to replenish and the time I got the lock, another instance may have already done the work.</p><p><strong>A note on Redisson’s </strong><strong>RLock</strong>: it offers automatic lock renewal via a watchdog thread and reentrancy, which sounds appealing. I chose raw SET NX EX + Lua because my replenishment task has a predictable duration (200-500ms) a 120-second TTL gives 200x headroom. If generation ever takes longer than that, something is seriously wrong with the id-generator and I <em>want</em> the lock to expire. Adding Redisson for a single lock pattern felt like pulling in a heavy dependency for a problem I didn&#39;t have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*JNwpYGLxfjl4W11erlLUtA.png" /><figcaption>Distributed Lock Flow</figcaption></figure><p>After this fix, OOM crashes dropped to zero. Each pool key gets exactly one concurrent replenishment, regardless of how many instances or threads are contending.</p><h3>The Problem I Didn’t See Coming: Lost IDs</h3><p>With performance solved, I hit a subtler issue during failure testing.</p><p>When a request pops an ID from the pool but the downstream document persistence fails network timeout, storage error, app exception that ID is gone. It was consumed from the pool, never attached to a document, and on retry the client gets a different ID. This creates sequence gaps and, worse, potential duplicates if the original write eventually succeeds after a timeout.</p><p>I considered several approaches: client-supplied idempotency keys (requires client cooperation unreliable with external API consumers), a reservation-commit pattern (extra Redis round-trips per request), and pre-assigned batch reservations (good for migrations, overkill for single uploads).</p><h3>My Choice: The Outbox Pattern</h3><p>I went with the Outbox pattern because it solves the problem entirely on the server side. No API contract changes. No client cooperation.</p><p><strong>The idea:</strong> instead of popping an ID and then separately persisting the document, I pop the ID and write it along with the document metadata to an <strong>outbox table</strong> in a single database transaction. If the transaction fails, neither the ID assignment nor the record exists atomic.</p><p>A separate background processor handles the actual storage. The client gets their ID back immediately; the real persistence happens seconds later.</p><pre>@Transactional<br>public String assignId(String projectCode, String docTypeId,<br>                        DocumentMetadata metadata) {<br>    String docId = idPoolService.fetchNextId(projectCode, docTypeId);<br>    // Single transaction: ID + record exist together or not at all<br>    outboxRepository.save(OutboxEntry.builder()<br>        .documentId(docId)<br>        .tenantCode(projectCode)<br>        .entityTypeId(docTypeId)<br>        .payload(metadata)<br>        .status(OutboxStatus.PENDING)<br>        .retryCount(0)<br>        .build());<br>    return docId;  // Client gets the ID immediately<br>}</pre><h3>The Outbox Processor: Retries, Backoff, and Dead Letters</h3><p>The processor is a @Scheduled method that polls the outbox table every 2 seconds, picks up PENDING entries, and tries to persist each document to the target store.</p><p>On the happy path, it persists the document and marks the entry COMMITTED. But when storage fails with network timeout, S3 returning 500, disk full things get interesting.</p><p>A naive approach retries the entry on the next poll, 2 seconds later. If storage is down, I’m hammering it every 2 seconds and blocking the processor from making progress on other entries.</p><p>I used exponential backoff instead. Each outbox entry has a next_retry_at timestamp:</p><pre>next_retry_at = NOW() + (2 ^ retry_count) seconds</pre><p>Retry 1 waits 2 seconds. Retry 2 waits 4. Retry 3 waits 8. Retry 5 waits 32. Failing entries naturally “sink to the bottom” while fresh entries get processed promptly. The processor’s query becomes:</p><pre>SELECT * FROM id_outbox <br>WHERE status = &#39;PENDING&#39; AND next_retry_at &lt;= NOW()<br>ORDER BY created_at LIMIT 100</pre><p>After a maximum number of retries (I used 5), the entry moves to DEAD_LETTER status. This means the system has given up on automatic recovery and the document payload might be corrupted, the target storage bucket might not exist for this tenant, or there&#39;s a permission issue that no amount of retrying will fix.</p><p>Dead-lettered entries become a to-do list for the ops team: investigate, fix the root cause, and either reprocess manually or mark as abandoned.</p><p>Why not retry forever? A poisoned entry like corrupted payload, invalid schema will <em>never</em> succeed. Infinite retries waste processing capacity and mask the real bug. The dead letter queue acts as a circuit breaker for individual entries.</p><p>The outbox table:</p><pre>CREATE TABLE id_outbox (<br>    id              BIGSERIAL PRIMARY KEY,<br>    document_id     VARCHAR(64) NOT NULL UNIQUE,<br>    tenant_code     VARCHAR(32) NOT NULL,<br>    entity_type_id  VARCHAR(32) NOT NULL,<br>    payload         JSONB       NOT NULL,<br>    status          VARCHAR(16) NOT NULL DEFAULT &#39;PENDING&#39;,<br>    retry_count     INT         NOT NULL DEFAULT 0,<br>    next_retry_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),<br>    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),<br>    processed_at    TIMESTAMPTZ<br>);<br>-- Partial index: only scans PENDING rows ready for processing<br>CREATE INDEX idx_outbox_pending<br>    ON id_outbox (next_retry_at ASC) WHERE status = &#39;PENDING&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xL0sB3BeBh0QlLgTavVZzA.png" /><figcaption>Outbox Pattern Flow</figcaption></figure><p>The tradeoff is <strong>eventual consistency. </strong>The document isn’t in the target store the instant the client gets the ID. There’s a 2–5 second delay while the processor runs. For bulk document uploads, this was perfectly acceptable.</p><h3>When Redis Goes Down</h3><p>My fallback is straightforward: if LPOP fails with a RedisConnectionFailureException, fall through to synchronous id-generatorcalls.</p><pre>try {<br>    sequence = redisTemplate.opsForList().leftPop(poolKey);<br>} catch (RedisConnectionFailureException e) {<br>    sequence = idGenerator.generateSingle(projectCode, docTypeId);<br>}</pre><p>This re-introduces latency during a Redis outage (sub-ms jumps to ~200ms per ID), but the system stays available.</p><p><strong>One important detail:</strong> the id-generator&#39;s sequence counter must live <strong>independently of Redis</strong>. If the generator also relies on Redis for its counter (INCRBY), then a Redis outage takes down both the pool <em>and</em> the fallback. I backed the counter with a database sequence so the fallback path has no Redis dependency.</p><p>The other concern is <strong>consistency after Redis recovers</strong>. During the outage, the sync fallback generates IDs using the database counter. The Redis pool still holds stale pre-generated IDs from before the crash. If you naively resume popping from the pool, you could issue duplicates.</p><p>My approach: on Redis reconnection, <strong>invalidate all pool keys and re-seed from the current database counter value</strong>. Simple but safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*Btt4xZKvhTMi_5BGVREERQ.png" /><figcaption>Redis Recovery</figcaption></figure><h3>Results</h3><p>Remember the back-of-envelope math? With the pool, a single ID retrieval drops from ~150ms (network hop to id-generator) to ~0.5ms (Redis LPOP). Across 3 app instances handling 20 concurrent requests each, the theoretical throughput for 200,000 documents is about 2 minutes. In practice, accounting for API gateway overhead, outbox commits, and occasional sync fallbacks, the observed results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_FJSjIdfLaPS5uX33sPZw.png" /><figcaption>Results</figcaption></figure><p>The gap between theoretical (2 min) and observed (~1 hour) is mainly the outbox processor’s polling interval, document storage latency, and the client’s own upload pacing. The 85% improvement is on the end-to-end migration, not just ID generation but ID generation was the bottleneck that unlocked everything else.</p><h3>What I’d Improve</h3><h3>Gap Reconciliation</h3><p>IDs still get lost. An instance can crash between popping from the pool and writing to the outbox. The outbox processor might exhaust retries and send entries to the dead letter queue. These are rare and a handful per million, but they create sequence gaps that confuse customers expecting contiguous numbering.</p><p>I’d address this with a <strong>periodic reconciliation job</strong> that compares three sources: the <strong>sequence counter</strong> (highest ID ever generated), the <strong>document table</strong> (which IDs have committed documents), and the <strong>outbox table</strong> (which IDs are still pending or dead-lettered). Everything in the counter range that doesn’t appear in any of these is a gap. The job writes these to a lightweight id_gaps table with the detection timestamp and inferred reason — outbox_dlq for dead-lettered entries, untracked_loss for IDs that never reached the outbox at all.</p><p>An endpoint like GET /api/v1/ids/gaps?project=PROJ&amp;type=9012 would let customers distinguish &quot;this ID was skipped due to infrastructure&quot; from &quot;this document is actually missing.&quot; Gaps become explained rather than mysterious.</p><p>I’d avoid trying to reclaim and reuse lost IDs. Reuse sounds clean but risks collision with late-arriving writes from the original assignment the kind of bug that’s nearly impossible to reproduce and debug. Better to waste a few numbers and track them than to reintroduce them into circulation.</p><h3>Key Takeaways</h3><ol><li><strong>Pre-populate, don’t generate on-the-fly.</strong> When generation is expensive or serial, trade storage for latency.</li><li><strong>Watermark replenishment, not reactive.</strong> Refill at 75% consumed, not when empty. No request should ever wait on generation.</li><li><strong>Distributed systems need distributed locks.</strong> Java’s ReentrantLock doesn&#39;t cross JVM boundaries. Redis SET NX EXgives you a lightweight mutex.</li><li><strong>Lock ownership matters.</strong> UUID lock values + Lua atomic compare-and-delete. Never blindly DELETE a lock key.</li><li><strong>Double-check after acquiring the lock.</strong> The distributed equivalent of double-checked locking prevents redundant work.</li><li><strong>Solve idempotency server-side.</strong> The Outbox pattern gives you atomicity without burdening API clients. Exponential backoff and dead letter queues turn “retry until it works” into something manageable.</li><li><strong>Don’t reuse lost IDs.</strong> Track gaps, explain them, move on. Reuse introduces collision risks that are far worse than a missing number.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716f5224bf3c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/from-oom-crashes-to-85-faster-onboarding-scaling-id-generation-with-redis-716f5224bf3c">From OOM Crashes to 85% Faster Onboarding: Scaling ID Generation with Redis</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does Redis expire keys?]]></title>
            <link>https://medium.com/@chkrishnatej/how-does-redis-expire-keys-544c66ec4a34?source=rss-e419453bc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/544c66ec4a34</guid>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Krishna Tej Chalamalasetty]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 06:57:11 GMT</pubDate>
            <atom:updated>2023-10-16T06:57:11.690Z</atom:updated>
            <content:encoded><![CDATA[<p>Redis provides an easy way to expire the keys that are added to cache. This can be done using following commands.</p><pre>SET key value EX seconds</pre><pre>EXPIRE key seconds</pre><p>After the key is persisted and its Time-To-Live (TTL) is over, if we try to search for that key, it gives nil</p><h3>How does it work?</h3><p>In the previous versions of Redis, they used to do semi-lazy cleanup by employing both active-passive strategy.</p><p>In the active strategy, when the user requests for the key, it checks the TTL and if the TTL is over, it will send nil to the user and remove the key from memory.</p><p>In the passive strategy, Redis randomly scans the keys and whichever keys are expired and removed from the memory. This is based on random sampling.</p><p>This is such a simple and effective strategy.</p><p>But from Redis 6.x, they changed the implementation, and now it is based on radix tree. It promises to remove the keys from memory almost equivalent to TTL.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=544c66ec4a34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Palindrome and Permutation]]></title>
            <link>https://medium.com/@chkrishnatej/palindrome-and-permutation-fa8eb36deb59?source=rss-e419453bc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa8eb36deb59</guid>
            <dc:creator><![CDATA[Krishna Tej Chalamalasetty]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 07:09:09 GMT</pubDate>
            <atom:updated>2023-10-04T07:09:09.288Z</atom:updated>
            <content:encoded><![CDATA[<h3>Permutation</h3><blockquote>Rearranging given elements in a different order</blockquote><ul><li>The number of elements should be same</li><li>No new elements should be used</li></ul><h4>Getting all possible permutations</h4><p><a href="https://leetcode.com/problems/permutations/">Permutations - LeetCode</a></p><pre>class Solution {<br>    public List&lt;List&lt;Integer&gt;&gt; permute(int[] nums) {<br>        List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();<br>        backtrack(nums, new ArrayList&lt;&gt;(), result);<br>        return result;<br>    }<br><br>    private void backtrack(int[] nums, List&lt;Integer&gt; path, List&lt;List&lt;Integer&gt;&gt; result) {<br>        // If the path size is same as input length,<br>        // We found a permutation, add to result;<br>        if(path.size() == nums.length) {<br>            result.add(new ArrayList&lt;&gt;(path));<br>            return;<br>        }<br>        <br>        // Iterate through the input nums<br>        for(int i=0;i&lt;nums.length;i++) {<br>            if(path.contains(nums[i])) { // If the path already contains current number, skip the number<br>                continue;<br>            }<br>            path.add(nums[i]); // Add the current number to path<br>            backtrack(nums, path, result); // Generate new selections with current path <br>            path.remove(path.size() - 1); // Once the path is explored, remove it<br>        }<br>    }<br>}</pre><h4>Getting all possible permutations without duplicates</h4><p><a href="https://leetcode.com/problems/permutations-ii/">Permutations II - LeetCode</a></p><pre>class Solution {<br>    public List&lt;List&lt;Integer&gt;&gt; permuteUnique(int[] nums) {<br>        // Time Complexity: O(n!)<br>        // Space Complexity: O(n)<br>        <br>        List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();<br>        // Sorting the numbers so that we keep track of duplicates<br>        Arrays.sort(nums);<br>        <br>        // Keeps track of elements that has been processed<br>        boolean[] seen = new boolean[nums.length];<br>        backtrack(nums, seen, new ArrayList&lt;&gt;(), result);<br>        return result;<br>    }<br><br>    private void backtrack(int[] nums, boolean[] seen, List&lt;Integer&gt; path, List&lt;List&lt;Integer&gt;&gt; result) {<br>        // When the path is same as size of nums, add to result<br>        if(path.size() == nums.length) {<br>            result.add(new ArrayList&lt;&gt;(path));<br>            return;<br>        }<br>        <br>        // Iterate through the nums<br>        for(int i=0;i&lt;nums.length;i++) {<br>            if(seen[i]) { // If we have already processed the index, ignore<br>                continue;<br>            }<br>            <br>            // If we encounter a duplicate and the first occurrence of the duplicate<br>            // has not been processed, skip the iteration<br>            if(i &gt; 0 &amp;&amp; nums[i] == nums[i-1] &amp;&amp; !seen[i-1]) {<br>                continue;<br>            }<br>            seen[i] = true; // Mark the current index as true, means it is processing<br>            path.add(nums[i]); // Add it to path<br>            backtrack(nums, seen, path, result); // Recusrively call the func to generate other permutations<br>            seen[i] = false; // Once it is completely done, set it as false<br>            path.remove(path.size()-1); // Remove the last number from the path<br>        }<br>    }<br>}</pre><h4>Finding next permutation</h4><ul><li>Find a pivot element which is where the non-decreasing property of the elements breaks from <strong>right → left</strong></li><li>If we found it, then the index where pivot is called as threshold</li><li>Iterate from right → left, find the first number which is greater than threshold. Swap the number with threshold</li><li>Reverse the part of the list after pivot index</li></ul><p><a href="https://leetcode.com/problems/next-permutation/description/">Next Permutation - LeetCode</a></p><pre>class Solution {<br>    public void nextPermutation(int[] nums) {<br>        int pivot = indexOfLastPeak(nums) - 1;<br>        System.out.println(&quot;Pivot: &quot; + pivot);<br><br>        if(pivot != -1) {<br>            int nextPrefix = lastIndexOfGreaterThanThreshold(nums, nums[pivot]);<br>            System.out.println(&quot;Next Prefix: &quot; + nextPrefix);<br>            swap(nums, pivot, nextPrefix);<br>            System.out.println(&quot;Swapping prefix and next prefix&quot;);<br>            System.out.println(Arrays.toString(nums));<br>            <br>        }<br>        reverseSuffix(nums, pivot+1);<br>        System.out.println(&quot;Final: &quot; + Arrays.toString(nums));<br>    }<br><br>    private int indexOfLastPeak(int[] nums) {<br>        for(int i= nums.length-1;i&gt;0;i--) {<br>            if(nums[i-1] &lt; nums[i]) {<br>                return i;<br>            }<br>        }<br>        return 0;<br>    }<br><br>    private int lastIndexOfGreaterThanThreshold(int[] nums, int threshold) {<br>        for(int i=nums.length-1;i&gt;=0;i--) {<br>            if(threshold &lt; nums[i]) {<br>                return i;<br>            }<br>        }<br>        return -1;<br>    }<br><br>    private void swap(int[] nums, int i, int j) {<br>        int temp = nums[i];<br>        nums[i] = nums[j];<br>        nums[j] = temp;<br>    }<br><br>    private void reverseSuffix(int[] nums, int start) {<br>        int end = nums.length-1;<br><br>        while(start &lt; end) {<br>            swap(nums, start, end);<br>            start++;<br>            end--;<br>        }<br>    }<br>}</pre><h3>Palindrome</h3><blockquote>A sequence which reads the same when read from <strong>left → right</strong> and <strong>right → left</strong></blockquote><p>The relationship between palindrome and permutation is:</p><ul><li>Every palindrome that can be formed using same set of characters is a permutation</li><li>But not every permutation could be a palindrome</li></ul><h4>Palindrome Partitioning</h4><p><a href="https://leetcode.com/problems/palindrome-partitioning/">LeetCode - The World&#39;s Leading Online Programming Learning Platform</a></p><pre>class Solution {<br>    public List&lt;List&lt;String&gt;&gt; partition(String s) {<br>        // Create a container to store the result<br>        List&lt;List&lt;String&gt;&gt; result = new ArrayList&lt;&gt;();<br>        // Backtrack the given string and add the valid palindrome to the list<br>        backtrack(0, s, new ArrayList&lt;&gt;(), result);<br>        return result;<br>    }<br><br>    public void backtrack(int start, String s, List&lt;String&gt; path, List&lt;List&lt;String&gt;&gt; result){<br>        // When the start == s.length(), we built a string to form a palindrome<br>        if(start == s.length()) {<br>            result.add(new ArrayList&lt;&gt;(path));<br>            return;<br>        }<br>        // Iterate from the positions recursively<br>        for(int i = start; i &lt; s.length(); i++){<br>            // Check if the substring boundary is a plaindrome, <br>            // then only process it<br>            if(isPalindrome(s, start, i)){ <br>                path.add(s.substring(start, i + 1));<br>                backtrack(i+1, s, path, result);<br>                path.remove(path.size() - 1);<br>            }<br>        }<br>    }<br><br>    // Helper function to check if the given range is a palindrome or not<br>    public boolean isPalindrome(String s, int low, int high){<br>        while(low &lt; high)<br>            if(s.charAt(low++) != s.charAt(high--)) return false;<br>        return true;<br>    } <br>}</pre><h4>Finding next smallest palindrome given any number</h4><p><strong>If the length of number is odd</strong></p><p>For example, take <strong>45312</strong></p><ul><li>Take the substring 0 to len/2 and store in StringBuilder</li><li>Reverse the substring</li><li>Append the middle element</li><li>Append the reversed substring to the StringBuilder</li></ul><pre>String s = &quot;45312&quot;<br>length = 5<br>First substring = s.substring(0, length/2)<br>First Substring = &quot;45&quot;<br><br>Reverse first substring = &quot;54&quot;<br><br>Final result = First_Substring + middle_element + reverse_first_substring<br>Final result = &quot;45354&quot;</pre><p>If the result is making a smaller number</p><p>For example take <strong>12321</strong></p><ul><li>Increment the middle number to +1</li></ul><pre>String s = &quot;12321&quot;<br>length = 5<br>First substring = s.substring(0, length/2)<br>First Substring = &quot;12&quot;<br><br>Reverse first substring = &quot;21&quot;<br>Middle number = &quot;3&quot;<br><br>Final result = First_Substring + middle_element + reverse_first_substring<br>Final result = &quot;12312&quot;<br><br>Final result &lt; s<br><br>In that case,<br>Final result = First_Substring + (add+1 to middlenumber) + reverse_first_substring<br>Final result = &quot;12&quot; + (3+1) +  &quot;21&quot; = &quot;12421&quot;</pre><p>If the middle number is “9” and the resultant is smaller</p><ul><li>Increment the first half + middleNumber + 1</li></ul><pre>String s = &quot;12945&quot;<br>length = 5<br>First substring = s.substring(0, length/2)<br>First Substring = &quot;12&quot;<br><br>Reverse first substring = &quot;21&quot;<br>Middle number = &quot;9&quot;<br><br>Final result = First_Substring + middle_element + reverse_first_substring<br>Final result = &quot;12921&quot;<br><br>Final result &lt; s<br><br>In that case,<br>Final result = first half + middleNumber + 1 + reverse_first_substring<br>Final result = (129 + 1) +  &quot;21&quot; = &quot;13021&quot; <br>Apply the palindrome formula on resulting number</pre><p><strong>If the length of number is even</strong></p><ul><li>Take the middle two numbers</li><li>Discard the number from middle index</li></ul><pre>String s = &quot;4531&quot;<br>length = 4<br><br>Middle numbers indexes = (length/2, (length/2)-1) = (1, 2)<br><br><br>Middle index = 4/2 = 2<br>Discarding numbers from middle index called firstSub = &quot;45&quot;<br>Reverse the firstSub = &quot;54&quot;<br><br>Result = FirstSub + reverseOfFirstSub = &quot;45&quot; + &quot;54&quot;<br>Result = &quot;4554&quot;</pre><p>If the resultant number is less than original</p><p>For example, if we take <strong>1459</strong>, then the result will be <strong>1441. </strong>That is less than the original number.</p><pre><br>Original = 1459<br><br>Based on above algo, result = 1441<br><br>result &lt; original<br><br>Increment the middle number indexes by 1<br>After incrementingn middle number indexes by 1 = 1569<br><br>Apply original algorithm, result = <strong>1551</strong></pre><p>If we are dealing with “<strong>99</strong>” as the middle element, <strong>1997, </strong>then the result should be <strong>2002</strong></p><pre>Original = 1997<br>After applying original algo result = &quot;<strong>1991</strong>&quot;<br><br>Result &lt; original<br><br>Increment the first half until the two middle numebs = &quot;199&quot; + &quot;1&quot; = &quot;200&quot;<br>Then apply it to original algo result i.e. &quot;1991&quot; --&gt; &quot;2001&quot;<br><br>The apply original algo, it is &quot;2002&quot;<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa8eb36deb59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pillars of Object Oriented Design]]></title>
            <link>https://medium.com/@chkrishnatej/pillars-of-object-oriented-design-5d30ac234663?source=rss-e419453bc98------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d30ac234663</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Krishna Tej Chalamalasetty]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 08:01:07 GMT</pubDate>
            <atom:updated>2023-09-25T08:01:07.055Z</atom:updated>
            <content:encoded><![CDATA[<p>Object Oriented Design (OOD) helps in designing better models of data</p><p>The four pillars of Object Oriented Design are:</p><ul><li>Abstraction</li><li>Encapsulation</li><li>Inheritance</li><li>Polymorphism</li></ul><p>These pillars helps you write and maintain a code base more efficiently.</p><h3>Abstraction</h3><p>Abstraction is the property of hiding the complexity of data and implementation.</p><p>There are two types of abstractions:</p><ul><li>Data abstraction</li><li>Process abstraction</li></ul><p><strong>Data abstraction</strong> helps you create or retrieve objects using some form of getter and setter methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YV7FIzkT7_UVfyEJDIMDLw.png" /><figcaption>Data Abstraction</figcaption></figure><p>In the above Product, user can interact with setters and gettersto set or retrieve data. User does not need to be bogged down by the validation checks that might need to be done. It is taken care by the setters and getters</p><p><strong>Process abstraction</strong> hides the implementation details of functionality.</p><p>For example, you want to connect with a service which is authenticated with username and password. The user just needs to give their username and password to a function called authenticate, and the function will take care of checking its correctness.</p><h3>Encapsulation</h3><p>Encapsulation is the property of binding sates and functionality of an entity.</p><p>It helps in hiding the internal state of an object. This helps in restricting the access of state and functionality of an entity. These can be enforced by providing access modifiers to state and functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1N_bZuzOYZockHrFtTWd0A.png" /></figure><p>Imagine you have an online marketplace with different products. And the product is having the above states and functionalities.</p><p>The stockSold can be incremented by using updateStockSold() method. This should not be exposed directly to the <strong>customers</strong> as it might lead to undesired state of you stock availability affecting sales. In this case the updateStockSold()should be restricted from the customers and expose only the required functionality to them.</p><h3>Inheritance</h3><p>Inheritance helps in reuse of the code. The properties and functionalities of the parent class can be inherited or overriden by the child class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6gFH1w-UY46NBFgFWd7hw.png" /></figure><p>In the above example, you can check all the TVs extended from a base TV inherit the model and make and do not need to implement the basic functionalities. They can reuse the existing functionalities and add their brand specific functionalities.</p><h3>Polymorphism</h3><p>Polymorphism the ability of an object to take multiple forms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CDxTNafoO60CE37UI_R1g.png" /></figure><p>In the above example, a Vehicle can take many forms like <strong>Aeroplane</strong>, <strong>Car</strong> and <strong>Boat</strong>. And a vehicle is supposed to move, but</p><ul><li>when vehicle takes form of am Aeroplane, it flown</li><li>when vehicle takes form of a Car, its driven</li><li>when vehicle takes form of a Boat, its rowed</li></ul><p>The vehicles polymorphism ability helps to take multiple modes of transport.</p><p>When designing classes, polymorphism helps you to achieve concise, flexible and reusable code.</p><h4>References:</h4><ul><li><a href="https://www.digitalocean.com/community/tutorials/what-is-abstraction-in-oops">https://www.digitalocean.com/community/tutorials/what-is-abstraction-in-oops</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d30ac234663" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>