<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Muhammad Sumon Molla Selim — Articles</title><description>Articles on software engineering, cloud infrastructure, DevOps and building AI systems.</description><link>https://www.sumonselim.com/</link><language>en-us</language><item><title>PHP2Shell: Patch or Mitigate PHP Servers, and the Claude Code Skill That Does It</title><link>https://www.sumonselim.com/php2shell-defense-patch-or-mitigate-with-a-claude-code-skill/</link><guid isPermaLink="true">https://www.sumonselim.com/php2shell-defense-patch-or-mitigate-with-a-claude-code-skill/</guid><description>Two critical PHP runtime bugs, CVE-2026-109618 and CVE-2026-109619, were exploited in the wild hours before the fix shipped on 21 October 2026. This is what I did on two servers that morning, what the official advisory changed, what broke, and the Claude Code skill that now does the whole sequence from your own laptop.</description><pubDate>Wed, 21 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; PHP 8.2.35, 8.3.36, 8.4.27 and 8.5.12 fix two bugs in PHP itself that run before your application. One corrupts memory when a request runs PHP out of memory during startup. The other lets state from a crashed request leak into the next request on the same worker. WordPress, Laravel and application-level WAF rules cannot stop either. PHP says there are no complete mitigations. On the morning of 21 October 2026, before the fix was out, I protected two servers with an ini change, a multipart block at the edge, and a firewall that only lets Cloudflare in, then verified each change on the PHP process that serves traffic. The whole sequence, plus the patch step, is now a Claude Code skill: &lt;a href=&quot;https://github.com/SumonMSelim/skills/tree/main/php2shell-defense&quot;&gt;php2shell-defense&lt;/a&gt;. It runs from your own machine over SSH and changes nothing without showing you first.&lt;/p&gt;
&lt;h2 id=&quot;what-php2shell-is&quot;&gt;What PHP2Shell is&lt;/h2&gt;
&lt;p&gt;On 20 October 2026 the PHP team &lt;a href=&quot;https://www.php.net/archive/2026.php#2026-10-20-1&quot;&gt;announced an emergency release&lt;/a&gt; for 21 October at 14:00 UTC. Two critical bugs, both CVSS (Common Vulnerability Scoring System) 9.2. No details.&lt;/p&gt;
&lt;p&gt;The details leaked anyway. &lt;a href=&quot;https://watchtowr.com/intelligence/php-cve-2026-109618-faq/&quot;&gt;watchTowr&lt;/a&gt; reproduced one bug in a lab, &lt;a href=&quot;https://sansec.io/research/php2shell&quot;&gt;Sansec&lt;/a&gt; and &lt;a href=&quot;https://hadrian.io/vulnerability-alerts/php2shell-leaked-critical-php-rce-cve-2026-109618-cve-2026-109619&quot;&gt;Hadrian&lt;/a&gt; reported exploitation at scale from early morning, and the &lt;a href=&quot;https://www.ncsc.gov.uk/news/critical-security-issue-affecting-php&quot;&gt;UK NCSC&lt;/a&gt; issued an alert. The exploit kit is called PHP2Shell.&lt;/p&gt;
&lt;p&gt;PHP released early, at about 13:35 UTC, with the &lt;a href=&quot;https://www.php.net/archive/2026.php#2026-10-21-5&quot;&gt;security advisory&lt;/a&gt; and two GitHub advisories:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;CVE-2026-109618, RCE via OOM corruption&lt;/strong&gt; (&lt;a href=&quot;https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w&quot;&gt;GHSA-w8hw-w9fx-j79w&lt;/a&gt;). When PHP runs out of memory it used to jump out of the request. If that happens while request memory is only partly set up, shutdown trusts half-built data. An attacker gets there with a multipart body that stays inside every visible limit: no usable Content-Length, thousands of headers per part, or nested empty file fields. Confirmed remote code execution on Apache mod_php with default settings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CVE-2026-109619, RCE via stale global state&lt;/strong&gt; (&lt;a href=&quot;https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp&quot;&gt;GHSA-6wmf-4rv5-p3rp&lt;/a&gt;). PHP workers live for many requests. When a request dies from a fatal error, out of memory, or a timeout, some global state still points into freed memory. The next request on the same worker can use it before normal startup resets it. The confirmed paths are session upload progress, which is on by default and runs before &lt;code&gt;session_start()&lt;/code&gt;, and on PHP 8.5 the fatal error backtrace buffer.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Both run before &lt;code&gt;index.php&lt;/code&gt; is compiled. Any URL that maps to PHP is reachable. Updating WordPress does not help. &lt;code&gt;disable_functions&lt;/code&gt; does not help. PHP’s words: “There are no complete mitigations, updating is the only safe choice.”&lt;/p&gt;
&lt;p&gt;The leak had the location wrong. The early reports said use-after-free in the multipart parser. The multipart body is the trigger, not the bug. That matters, because it changes which workarounds help.&lt;/p&gt;
&lt;h2 id=&quot;how-i-mitigated-my-two-servers-then-ran-the-skill-on-them&quot;&gt;How I mitigated my two servers, then ran the skill on them&lt;/h2&gt;
&lt;p&gt;The morning work was by hand, on leaked information, because the servers were exposed and the fix was hours away. Once the official advisory was out I ran the skill against the same two servers from my laptop. It found that the first server runs PHP 8.1 from a PPA that no longer builds for its Ubuntu release, so no package will ever arrive, and that the second runs 8.5.11 in a Docker image whose patched base, &lt;code&gt;php:8.5.12-fpm&lt;/code&gt;, was not on Docker Hub yet. So it mitigated both with the official workarounds, verified every value on the serving process, blocked multipart at the edge on the first, and left the patch for when it becomes possible. The steps below are the morning sequence, with what the advisory changed noted where it matters.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Server 1&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Server 2&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;OS&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Ubuntu, PHP from the Ondřej Surý PPA&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Debian, Docker Compose&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;PHP&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;php8.3-fpm as a system service&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Official &lt;code&gt;php:8.3-fpm&lt;/code&gt; image, &lt;code&gt;app&lt;/code&gt; and &lt;code&gt;queue&lt;/code&gt; services&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Web server&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;nginx on the host&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;nginx container in front&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;In front&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cloudflare proxy&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cloudflare proxy&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Both run sites that accept uploads in one or two places and nowhere else.&lt;/p&gt;
&lt;h2 id=&quot;what-i-did-in-order&quot;&gt;What I did, in order&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;1. Inventory.&lt;/strong&gt; Which PHP binaries exist, which one serves traffic, and what &lt;code&gt;session.upload_progress.enabled&lt;/code&gt; is set to there. The CLI &lt;code&gt;php -i&lt;/code&gt; reads a different &lt;code&gt;php.ini&lt;/code&gt; than PHP-FPM. Its values are not evidence.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. The ini stopgap.&lt;/strong&gt; One drop-in file in &lt;code&gt;conf.d&lt;/code&gt;:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;ini&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;session.upload_progress.enabled&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; = 0&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;session.use_strict_mode&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; = 1&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first line turns off the session path that was being abused in the wild. The official advisory later confirmed it as the workaround for CVE-2026-109619, with two conditions: it must load from &lt;code&gt;php.ini&lt;/code&gt;, &lt;code&gt;conf.d&lt;/code&gt; or the FPM pool, not from &lt;code&gt;.user.ini&lt;/code&gt; or &lt;code&gt;ini_set()&lt;/code&gt;, and every worker must be restarted. The second line stops a client from choosing its own session ID. Hygiene, not in PHP’s list.&lt;/p&gt;
&lt;p&gt;After the advisory I added two more lines, also now in the skill’s template:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;ini&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;memory_limit&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; = -1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;fatal_error_backtraces&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; = 0&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;memory_limit = -1&lt;/code&gt; removes the predictable out-of-memory that CVE-2026-109618 relies on. PHP recommends it together with a container or cgroup memory limit, and warns never to use &lt;code&gt;RLIMIT_AS&lt;/code&gt; or &lt;code&gt;RLIMIT_DATA&lt;/code&gt; instead, because those cause the very allocation failure the bug needs. For FPM, &lt;code&gt;php_admin_value[memory_limit] = -1&lt;/code&gt; in the pool is stronger than the drop-in, because no application can put a finite limit back. &lt;code&gt;fatal_error_backtraces = 0&lt;/code&gt; only exists on PHP 8.5 and closes the confirmed mod_php path there.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;3. The edge block.&lt;/strong&gt; Multipart bodies are the trigger for the OOM bug and the only way into the upload progress path. So stop them reaching PHP except where uploads belong. In nginx:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;nginx&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;set &lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;$php2shell_block &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ($http_content_type &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;~* &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;multipart/form-data&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; set &lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;$php2shell_block &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ($request_uri &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;~* &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;^/(wp-admin/async-upload\.php|upload)&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; set &lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;$php2shell_block &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;0&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ($php2shell_block) { &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 403&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; }&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Uploads keep working on the two listed paths. Everywhere else a multipart POST gets a 403. Logins and normal forms use &lt;code&gt;application/x-www-form-urlencoded&lt;/code&gt;, so they are not affected. PHP also asks for a low &lt;code&gt;post_max_size&lt;/code&gt; (8M without uploads, 32M with) and body size limits at the proxy, including for requests with no Content-Length.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4. Close the origin.&lt;/strong&gt; A Cloudflare WAF rule is useless if the attacker connects to the server’s IP directly. I set &lt;code&gt;ufw&lt;/code&gt; to allow ports 80 and 443 from Cloudflare’s published ranges only, with SSH kept open.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;5. Verify on the serving process.&lt;/strong&gt; I wrote a small FastCGI client. It asks the running PHP-FPM to execute a one-line script and prints the effective &lt;code&gt;PHP_VERSION&lt;/code&gt; and ini values. Before the restart it said &lt;code&gt;session.upload_progress.enabled = &amp;#39;1&amp;#39;&lt;/code&gt;. After the restart it said &lt;code&gt;&amp;#39;0&amp;#39;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;6. Hunt.&lt;/strong&gt; Out-of-memory and timeout fatals in the PHP log, segfaults in the PHP-FPM log, shells with &lt;code&gt;php-fpm&lt;/code&gt; as parent, &lt;code&gt;.php&lt;/code&gt; files changed in the last 3 days, session files with &lt;code&gt;upload_progress_&lt;/code&gt; keys. Nothing found on either server. That does not prove they were not hit. PHP’s advisory says the same: clean logs do not prove safety.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;7. Patch, when it becomes possible.&lt;/strong&gt; The fix is out for all 4 supported branches, but neither server could take it on day one. Server 1 is on PHP 8.1, which PHP does not release, and its PPA dropped Ubuntu 20.04 last year. The routes are a source build from PHP’s backport branch, moving the site into a &lt;code&gt;php:8.3-fpm&lt;/code&gt; container, or an OS upgrade. Server 2 waits for Docker Hub to publish &lt;code&gt;php:8.5.12-fpm&lt;/code&gt;, then a rebuild of the app image. After each, the probe must report the fixed version on the serving process. Only then do the temporary blocks come off. The ini drop-in stays.&lt;/p&gt;
&lt;h2 id=&quot;what-broke&quot;&gt;What broke&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Server 1: the PPA was stale.&lt;/strong&gt; &lt;code&gt;apt update&lt;/code&gt; fetched the index but &lt;code&gt;apt-cache madison php8.3-fpm&lt;/code&gt; was empty. The source still pointed at &lt;code&gt;ppa.launchpad.net&lt;/code&gt;, and Launchpad moved to &lt;code&gt;ppa.launchpadcontent.net&lt;/code&gt;. Removing and re-adding the PPA with &lt;code&gt;add-apt-repository&lt;/code&gt; fixed it. Without that, the patch would have failed.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Server 2: 502 after recreating the container.&lt;/strong&gt; Adding the ini drop-in meant a bind mount in &lt;code&gt;compose.override.yml&lt;/code&gt; and a recreate of the &lt;code&gt;app&lt;/code&gt; service. The new container got a new IP. The nginx container had resolved &lt;code&gt;app&lt;/code&gt; at startup and kept the old one, so every request returned 502 Bad Gateway. A restart of the nginx container fixed it. The lesson: when you recreate a PHP container, restart or reload the proxy in the same change, then make one real request before you call it done.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Both: Cloudflare SSL mode.&lt;/strong&gt; Closing the origin to 443 only works if Cloudflare connects to the origin over HTTPS. With “Flexible” mode it uses plain HTTP, the firewall drops it, and the site is down. The mode must be “Full (strict)”. Check this before you touch the firewall.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Server 2: ufw does not see Docker.&lt;/strong&gt; Docker publishes ports through its own iptables chains, ahead of ufw. A ufw rule set that only allows Cloudflare does nothing for a container on port 443. The allow-list has to go in the &lt;code&gt;DOCKER-USER&lt;/code&gt; chain. This server already had one. The skill now checks for it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Server 2: the image overrode the drop-in.&lt;/strong&gt; The app image ships a &lt;code&gt;zz-app.ini&lt;/code&gt; that sets &lt;code&gt;memory_limit&lt;/code&gt;. PHP loads &lt;code&gt;conf.d&lt;/code&gt; alphabetically, so my &lt;code&gt;99-&lt;/code&gt; file lost. The probe showed 256M after the recreate. Renaming the mount to &lt;code&gt;zzz-&lt;/code&gt; fixed it. The skill now writes &lt;code&gt;zzz-&lt;/code&gt; and warns when a later file sets the same knob.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Server 1: a backup in the wrong folder.&lt;/strong&gt; I copied &lt;code&gt;sites-enabled/default&lt;/code&gt; to &lt;code&gt;default.bak&lt;/code&gt; in the same directory before editing. nginx includes that directory with a glob, loaded the copy too, and refused the config with “duplicate default server”. The reload failed safely and the old config kept serving. Backups go outside any included directory.&lt;/p&gt;
&lt;h2 id=&quot;the-skill&quot;&gt;The skill&lt;/h2&gt;
&lt;p&gt;Doing this twice by hand took a morning. The third time I wanted it to take 20 minutes. So I turned the sequence into a Claude Code skill: &lt;a href=&quot;https://github.com/SumonMSelim/skills/tree/main/php2shell-defense&quot;&gt;php2shell-defense on GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A skill is a folder with a &lt;code&gt;SKILL.md&lt;/code&gt; that tells the agent when to act and what steps to follow, plus scripts and reference notes it can use. This one has 6 scripts:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Script&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Changes anything?&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What it does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;php-inventory.sh&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every PHP binary, SAPI, version and the ini values that matter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;php-check-release.sh&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Compares a version against php.net, live, and the fixed versions&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;php-mitigate.sh&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Only with &lt;code&gt;--apply&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Writes the ini drop-in with PHP’s published workarounds. Dry-run by default. Never restarts&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;php-fpm-probe.py&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A temp file it deletes&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The FastCGI client. Proves the values on the serving process&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;cf-origin-lockdown.sh&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Only with &lt;code&gt;--apply&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Rebuilds &lt;code&gt;ufw&lt;/code&gt; to allow web ports from Cloudflare only&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;php-hunt.sh&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The exploitation hunt&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The reference notes cover the official facts and advisories, how the request startup and the session hook work, what each ini knob does and does not do, where the ini lines go for each distro and panel, patch commands per platform including PHP’s source backports for 7.4, 8.0 and 8.1, and detection rules for auditd, Falco and Loki.&lt;/p&gt;
&lt;p&gt;It handles both cases. If the fix is out for your branch and the package is really there, it patches: upgrade command, restart, and a version check over FastCGI afterwards. If the patch will take time, or your branch gets no package, it offers a ladder of temporary fixes and lets you pick how far to go: the ini change, the multipart block at the edge, the firewall or Cloudflare lockdown, and as a last resort taking PHP-FPM offline behind a maintenance page. Once the patch is verified it rolls back the blocks you want removed.&lt;/p&gt;
&lt;p&gt;Three rules are written into it. It never downloads or runs exploit code, even in Docker. It shows every dry-run and the exact command, then waits for your approval. It works on one host at a time and reports per host.&lt;/p&gt;
&lt;h2 id=&quot;install-and-use-it&quot;&gt;Install and use it&lt;/h2&gt;
&lt;p&gt;You do not need Claude on the server. Install the skill on your own machine and give it SSH access. The &lt;a href=&quot;https://github.com/SumonMSelim/skills/tree/main/php2shell-defense#readme&quot;&gt;README&lt;/a&gt; has the full details.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; clone&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; https://github.com/SumonMSelim/skills.git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ~/src/skills&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;mkdir&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; -p&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ~/.claude/skills&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;ln&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; -s&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ~/src/skills/php2shell-defense&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ~/.claude/skills/php2shell-defense&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Start a new Claude Code session and name the host:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;text&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span&gt;/php2shell-defense web-01 (ssh deploy@web-01) runs WordPress on PHP 8.3. Check exposure, mitigate, verify.&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The agent re-checks php.net, copies the scripts to the host with &lt;code&gt;scp&lt;/code&gt;, runs the inventory, and tells you whether to patch now or mitigate first. Each step is a dry-run, your yes, the change, and a probe of PHP-FPM to prove it. Then the patch after your approval, the hunt, and cleanup of the scripts from the host. If sudo needs a password, it gives you the command to run yourself.&lt;/p&gt;
&lt;p&gt;The scripts also work without Claude. The README has the same sequence as plain &lt;code&gt;ssh&lt;/code&gt; commands.&lt;/p&gt;
&lt;h2 id=&quot;what-to-do-today&quot;&gt;What to do today&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Patch. 8.2.35, 8.3.36, 8.4.27 or 8.5.12. Restart every worker. Re-check the version over FastCGI, not on the CLI.&lt;/li&gt;
&lt;li&gt;If the patch has to wait, add the ini lines from &lt;code&gt;php.ini&lt;/code&gt;, &lt;code&gt;conf.d&lt;/code&gt; or the pool, restart every worker, and verify on the serving process. &lt;code&gt;.user.ini&lt;/code&gt; and &lt;code&gt;ini_set()&lt;/code&gt; do not count.&lt;/li&gt;
&lt;li&gt;Block multipart at the edge for every path that does not take uploads. Set a low &lt;code&gt;post_max_size&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;If you are behind Cloudflare, close the origin, and check the SSL mode first. Cloudflare’s managed rules “Generic Rules - Anomalous Execution” have been on by default since 03:02 UTC on 21 October; on paid plans confirm the ruleset is in Block mode, and check Security Events for hits before your patch time. Details in &lt;a href=&quot;https://blog.cloudflare.com/php-vulnerabilities-waf-protection/&quot;&gt;Cloudflare’s post&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;PHP 8.1 and older get no release. Upgrade, use a vendor backport, build PHP’s own &lt;a href=&quot;https://github.com/php/php-src/tree/PHP-8.1-CVE-2026-109618-109619&quot;&gt;backport branches&lt;/a&gt;, or take it off the internet.&lt;/li&gt;
&lt;li&gt;mod_php is the highest-risk setup in PHP’s own words. Patch those first.&lt;/li&gt;
&lt;li&gt;Keep &lt;code&gt;session.upload_progress.enabled = 0&lt;/code&gt; after patching if you do not use the feature. PHP suggests the same.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The skill, the scripts and the notes are MIT licensed, provided as is, with no warranty. Read the dry-run before you apply anything.&lt;/p&gt;
&lt;h2 id=&quot;sources&quot;&gt;Sources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;PHP: &lt;a href=&quot;https://www.php.net/archive/2026.php#2026-10-21-5&quot;&gt;Security advisory: Critical remote code execution vulnerabilities, update now, 21 October 2026&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;PHP: &lt;a href=&quot;https://www.php.net/archive/2026.php#2026-10-20-1&quot;&gt;Upcoming Critical PHP Security Release, 20 October 2026&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href=&quot;https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w&quot;&gt;GHSA-w8hw-w9fx-j79w, RCE via OOM corruption, CVE-2026-109618&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href=&quot;https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp&quot;&gt;GHSA-6wmf-4rv5-p3rp, RCE via stale global state, CVE-2026-109619&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;watchTowr: &lt;a href=&quot;https://watchtowr.com/intelligence/php-cve-2026-109618-faq/&quot;&gt;PHP CVE-2026-109618 FAQ&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Sansec: &lt;a href=&quot;https://sansec.io/research/php2shell&quot;&gt;PHP2Shell research&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Hadrian: &lt;a href=&quot;https://hadrian.io/vulnerability-alerts/php2shell-leaked-critical-php-rce-cve-2026-109618-cve-2026-109619&quot;&gt;PHP2Shell vulnerability alert&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;UK NCSC: &lt;a href=&quot;https://www.ncsc.gov.uk/news/critical-security-issue-affecting-php&quot;&gt;Critical security issue affecting PHP&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Cloudflare: &lt;a href=&quot;https://blog.cloudflare.com/php-vulnerabilities-waf-protection/&quot;&gt;php2shell WAF protections&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Cloudflare IP ranges: &lt;a href=&quot;https://www.cloudflare.com/ips/&quot;&gt;cloudflare.com/ips&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;The skill: &lt;a href=&quot;https://github.com/SumonMSelim/skills/tree/main/php2shell-defense&quot;&gt;php2shell-defense&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content:encoded><category>PHP</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Running a URL Shortener on Cloudflare for $0 (Part 4): Operating It for Free</title><link>https://www.sumonselim.com/url-shortener-cloudflare-part4-operating-it-for-zero/</link><guid isPermaLink="true">https://www.sumonselim.com/url-shortener-cloudflare-part4-operating-it-for-zero/</guid><description>A service that costs nothing still needs a deploy pipeline, security headers, backups and a plan for failure. Part 4 covers Terraform with its state in R2, deploys from tags with API tokens instead of OIDC, the first deploy by hand, one CSP kept in three places, restore and regional failure, the bugs that only production showed, the files that make the API usable by agents, and when to start paying $5 a month.</description><pubDate>Thu, 08 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Zone settings are Terraform, with state in R2. Deploys run from a version tag only. The same Content Security Policy lives in three places, because static files never pass through the Worker. The first deploy is done once by hand, and D1 Time Travel is the backup. Four bugs only showed up on the real platform. The service pays $5 a month the day traffic reaches about 70% of the free quota, and not before.&lt;/p&gt;
&lt;h2 id=&quot;challenge-1-infrastructure-as-code-with-api-tokens&quot;&gt;Challenge 1: infrastructure as code with API tokens&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you run Terraform for Cloudflare from GitHub Actions?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Wrangler owns the Worker: its code, D1 binding, cron, assets and rate-limit binding. Terraform owns the zone:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;DNS. The apex record is a proxied &lt;code&gt;AAAA 100::&lt;/code&gt;, an address reserved for discarding traffic. Nothing should reach it, because the Worker route answers every request first.&lt;/li&gt;
&lt;li&gt;A redirect from &lt;code&gt;www&lt;/code&gt; to the apex.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;browser_cache_ttl = 0&lt;/code&gt;, HSTS with preload, and &lt;code&gt;nosniff&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The security-headers rule for static files.&lt;/li&gt;
&lt;li&gt;The create rate-limit rule.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;State is stored in an R2 bucket through Terraform’s S3 backend, with lock files.&lt;/p&gt;
&lt;p&gt;Cloudflare has no OIDC federation for its API, so GitHub Actions cannot trade a short-lived identity for credentials. The API token is a long-lived secret in a GitHub Environment. Everything else limits what that token can reach:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Two environments.&lt;/strong&gt; &lt;code&gt;production&lt;/code&gt; holds the write token and an R2 read-write key, and accepts only &lt;code&gt;v*.*.*&lt;/code&gt; tags. &lt;code&gt;production-plan&lt;/code&gt; holds a read-only token and an R2 read-only key. It runs &lt;code&gt;terraform plan&lt;/code&gt; on pull requests and posts the result as a comment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dependencies install without the token.&lt;/strong&gt; &lt;code&gt;npm ci&lt;/code&gt; runs in its own step, so no package install script ever sees the Cloudflare token.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Actions are pinned to commit SHAs.&lt;/strong&gt; Workflow permissions are read-only, and checkout does not keep its credentials.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A deploy is a tag push: Terraform apply, build the web UI, apply D1 migrations, &lt;code&gt;wrangler deploy&lt;/code&gt;. A merge to &lt;code&gt;main&lt;/code&gt; never deploys.&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-one-csp-in-three-places&quot;&gt;Challenge 2: one CSP in three places&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why does the same policy appear three times?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The site’s Content Security Policy is strict: scripts, styles, fonts and images only from the site itself, no inline code, no framing. There are three ways a response is made, and each needs its own copy:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Response&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Who sets the headers&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Note&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Worker responses: redirects, API, UI shell&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The Worker, on every response it returns&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One function wraps the router&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Static files: JS, CSS, fonts, prerendered pages&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A zone Transform Rule&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;These are served before the Worker runs, so the Worker never sees them&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The HTML page itself&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A &lt;code&gt;&amp;lt;meta&amp;gt;&lt;/code&gt; tag in &lt;code&gt;index.html&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Travels with the HTML, whoever serves it&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener-cloudflare/csp-layers.svg&quot; alt=&quot;Three places that set the same Content Security Policy&quot; title=&quot;Figure 1: Worker responses get the headers from the Worker. Static files skip the Worker, so a zone Transform Rule adds the same headers. The HTML page also carries the policy in a meta tag, without frame-ancestors, which browsers ignore there.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Three copies drift, and two changes showed how. Cloudflare adds its Web Analytics beacon at the edge, and the strict policy blocked it. The fix had to allow the same two hosts in all three copies. Later, &lt;code&gt;frame-ancestors&lt;/code&gt; was removed from the &lt;code&gt;&amp;lt;meta&amp;gt;&lt;/code&gt; copy only. Browsers ignore it in a meta tag and log a warning on every page. The header copies still block framing.&lt;/p&gt;
&lt;p&gt;Bot protection is turned off in Terraform for the same reason: its injected script would break the policy. In development, a Vite plugin swaps the meta tag for a looser one that allows inline scripts and the dev server’s WebSocket. The production build never sees it.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-the-first-deploy-backups-and-failure&quot;&gt;Challenge 3: the first deploy, backups and failure&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How does an empty account become a running service, and what happens when part of it fails?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;CI can only deploy what already exists, so the first deploy is done once, by hand, from a workstation:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;An account-owned API token,&lt;/strong&gt; limited to the permission groups the deploy needs: Workers scripts and routes, D1, DNS, zone settings, WAF, Transform Rules, redirect rules and cache purge.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An R2 bucket for Terraform state,&lt;/strong&gt; with its own R2 key that can reach only that bucket.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;terraform apply&lt;/code&gt;&lt;/strong&gt; for the zone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;wrangler d1 create&lt;/code&gt;,&lt;/strong&gt; then the new database ID goes into &lt;code&gt;wrangler.jsonc&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Secrets&lt;/strong&gt; with &lt;code&gt;wrangler secret put&lt;/code&gt;: the permutation key (32 or more random bytes), and an optional purge token that can only purge cache.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;make worker-deploy&lt;/code&gt;,&lt;/strong&gt; which applies the D1 migrations and deploys the Worker to the &lt;code&gt;mol.la/*&lt;/code&gt; route.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A smoke test:&lt;/strong&gt; the web UI loads, a create returns 201, and the new code returns 302.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;After that, the GitHub Environments get their tokens, and every later deploy is a tag.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Backups.&lt;/strong&gt; D1 Time Travel keeps 7 days of point-in-time history on the free plan, and 30 days on Workers Paid, with no setup. A mistake found after a week cannot be rolled back. A restore is in place and immediate, so the runbook says to note the current bookmark first. That makes it possible to roll forward again if the restore point was wrong.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Regional failure.&lt;/strong&gt; Workers run in every Cloudflare location, but D1 has one primary. If it fails, redirects already in a data center’s cache keep working for up to 60 seconds. Everything else returns 503. There is no automatic failover, and the runbook does not claim one.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-what-only-production-showed&quot;&gt;Challenge 4: what only production showed&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Which bugs did the tests miss?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Every one of these passed the test suite and failed on a staging hostname before launch, or in production:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Symptom&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Cause&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Fix&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Deep links in the web UI broke&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The assets layer answers &lt;code&gt;/app/index.html&lt;/code&gt; with a 307 to &lt;code&gt;/app/&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Ask for the directory form&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Deleted links stayed in browsers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The zone’s 4-hour Browser Cache TTL overrode &lt;code&gt;max-age=5&lt;/code&gt; (Part 2)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;browser_cache_ttl = 0&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Another app on the zone broke&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The security-headers rule matched &lt;code&gt;true&lt;/code&gt;, so the strict CSP reached &lt;code&gt;id.mol.la&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Scope every rule to &lt;code&gt;http.host eq &amp;quot;mol.la&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Analytics was blocked&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The edge-injected beacon was not in the CSP&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Allow its two hosts in all three copies&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Two configuration lessons came with them. The Page Rules API rejects account-owned tokens, so the &lt;code&gt;www&lt;/code&gt; redirect became a redirect rule. A zone has one ruleset per phase, so each new rule must join the existing ruleset.&lt;/p&gt;
&lt;h2 id=&quot;challenge-5-built-for-agents-too&quot;&gt;Challenge 5: built for agents too&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How does a script or an LLM agent learn to use the API?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A URL shortener is a natural tool for agents, so the API describes itself:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;File&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;/openapi.json&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;OpenAPI 3.1 contract. A test fails if it drifts from the handlers&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;/llms.txt&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A short guide for language models&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;/.well-known/api-catalog&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;RFC 9727 link set that points to the contract&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;/.well-known/security.txt&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;RFC 9116 contact file. Its expiry date must be renewed every year&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;robots.txt&lt;/code&gt;, &lt;code&gt;sitemap.xml&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Crawlers stay off short links, where every request is a click&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Every API response carries a &lt;code&gt;Link&lt;/code&gt; header with &lt;code&gt;rel=&amp;quot;service-desc&amp;quot;&lt;/code&gt; that points to the contract. Every error has the same shape, &lt;code&gt;{error, message, docs_url}&lt;/code&gt;, and a 429 carries &lt;code&gt;Retry-After&lt;/code&gt;. The About, Developers, Privacy and Terms pages are prerendered HTML, so an agent can read them without running JavaScript.&lt;/p&gt;
&lt;p&gt;On a free plan, where these files live matters. Most are static files, served without the Worker and without using quota. Only the two &lt;code&gt;/.well-known/&lt;/code&gt; documents are generated by the Worker, because they include the site’s own origin. They are cached for an hour.&lt;/p&gt;
&lt;h2 id=&quot;challenge-6-watching-a-hard-limit&quot;&gt;Challenge 6: watching a hard limit&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you know you are close to the edge?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The free plan fails closed, so the signal must come before the limit:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A Cloudflare notification&lt;/strong&gt; for Workers usage approaching its limit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Workers Logs&lt;/strong&gt; with structured JSON, 200,000 events a day, kept for 3 days. Every failed click count and failed lookup logs one line.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Database size.&lt;/strong&gt; One D1 database holds up to 500 MB on the free plan. The daily cron removes expired links and replay records, but click counters for removed links are never deleted, so that table only grows.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The upgrade trigger:&lt;/strong&gt; about 70,000 requests or 70,000 rows written in a day. At that point the $5 Workers Paid plan replaces the hard stop with per-use billing.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On Paid, the first 10 million requests and 50 million rows written each month are included. After that, it is $0.30 per million requests and $1 per million rows written. The code does not change.&lt;/p&gt;
&lt;h2 id=&quot;lessons&quot;&gt;Lessons&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What would I tell someone moving a small service to a free plan?&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Pick services with no fixed cost.&lt;/strong&gt; At small scale, anything billed by the hour is most of the bill.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Turn each quota into a cost per action.&lt;/strong&gt; A table of requests, rows read and rows written for every action showed the real limit. It was writes, not reads.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Measure the database’s counting, not the docs’ summary.&lt;/strong&gt; Index entries tripled the cost of a create. A one-minute local test found it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Short cache lifetimes are a correctness tool.&lt;/strong&gt; A 60-second cache needs no tombstones, versioned records or stale-serving rules. The guarantees are weaker, and they are written down.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pin what must never change.&lt;/strong&gt; Fixed test vectors make sure a refactor cannot map old IDs to new codes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Know every path a response can take.&lt;/strong&gt; Static files skip the Worker, so headers set only in the Worker miss them.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A free plan turns a traffic spike into an outage, not a bill.&lt;/strong&gt; For a hobby project that is the right trade. Know the trigger at which it stops being the right trade.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;mol.la now serves the same links with the same codes, on a platform that costs nothing until it is worth paying for.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Running a URL Shortener on Cloudflare for $0 (Part 3): Writes and Abuse on a Free Plan</title><link>https://www.sumonselim.com/url-shortener-cloudflare-part3-writes-and-abuse-on-a-free-plan/</link><guid isPermaLink="true">https://www.sumonselim.com/url-shortener-cloudflare-part3-writes-and-abuse-on-a-free-plan/</guid><description>Creating a link on mol.la is one validation pass, one ID from a leased block, a keyed Feistel permutation in WebCrypto, and one D1 batch. Part 3 explains each step, what a create really costs in D1 rows, and why rate limits on a free plan protect against floods but not against a patient client using up the day&apos;s write quota.</description><pubDate>Wed, 07 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; A create request is validated without ever fetching the destination. The Worker takes the next ID from a block of 100 leased from a D1 counter, and turns it into a 7-character code with a keyed Feistel permutation. It writes the link and its optional idempotency record in one D1 batch. Abuse control has two layers: a zone WAF rule that blocks floods before the Worker runs, and a rate-limit binding inside the Worker. Neither one fully protects the daily write quota, and this part explains why.&lt;/p&gt;
&lt;h2 id=&quot;the-create-path&quot;&gt;The create path&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What happens inside &lt;code&gt;POST /api/v1/links&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The body has three fields: &lt;code&gt;long_url&lt;/code&gt;, an optional &lt;code&gt;alias&lt;/code&gt;, and an optional &lt;code&gt;expires_in&lt;/code&gt; in seconds. Validation is pure code with no I/O:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Input&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Rule&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Body&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;At most 16 KiB, checked against &lt;code&gt;Content-Length&lt;/code&gt; and again against the bytes read&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;long_url&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;At most 2,048 characters, &lt;code&gt;http&lt;/code&gt; or &lt;code&gt;https&lt;/code&gt;, a non-empty host, no user or password, no control characters&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;alias&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;3 to 32 characters from &lt;code&gt;A-Z a-z 0-9 _ -&lt;/code&gt;. &lt;code&gt;api&lt;/code&gt; and &lt;code&gt;app&lt;/code&gt; are reserved&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;expires_in&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;60 seconds to 5 years. The default is 5 years&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;Idempotency-Key&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Optional, 1 to 128 printable ASCII characters&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The URL is parsed but never fetched, resolved or previewed. A write path with no outbound requests cannot be used to reach an internal address. It also keeps the Worker far from the free plan’s limit of 50 outbound requests per invocation.&lt;/p&gt;
&lt;p&gt;A valid request then gets a code, unless it brought its own alias, and goes to D1.&lt;/p&gt;
&lt;h2 id=&quot;challenge-1-codes-without-a-coordinator&quot;&gt;Challenge 1: codes without a coordinator&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do many isolates hand out unique codes with one counter?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;There are four common ways to make short codes:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Problem here&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Random 7 characters&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every create risks a collision, and the risk grows as the table fills&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A counter update per create&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One more D1 write for every create, all on one hot row&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Snowflake-style IDs&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;They need a stable worker ID, and a Worker isolate has none&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A leased block of IDs, then a keyed permutation (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One counter write per 100 creates. The permutation hides the order&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The lease is one statement:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;UPDATE&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; counters &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;SET&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; counter&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; counter&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; +&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 100&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; WHERE&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; region &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;#39;global&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; RETURNING &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;counter&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The isolate keeps the block &lt;code&gt;[counter - 100, counter)&lt;/code&gt; in module memory and hands out IDs from it. When the block runs out, it leases another. If an isolate is evicted, the rest of its block is skipped. That leaves gaps but never duplicates. A block of 100 is small enough that an evicted isolate wastes little, and large enough that the counter costs one write per 100 creates.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener-cloudflare/code-generation.svg&quot; alt=&quot;From a leased block to a 7-character code&quot; title=&quot;Figure 1: An isolate leases 100 IDs with one D1 update. Each ID goes through a 6-round Feistel network over 42 bits, keyed with HMAC-SHA256. Results of 62^7 or more are permuted again until they fit. The result is Base62-encoded into exactly 7 characters.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Sequential IDs would make codes guessable. A permutation fixes that: it maps every number in a range to a different number in the same range, so it never collides. mol.la uses a Feistel network, a construction that turns any round function into a permutation:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;ts&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;private async &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;permute42&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(value: bigint): &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;Promise&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;bigint&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;  let left &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; value &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 21&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;n&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;  let right &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; value &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; HALF_MASK&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;                  // two 21-bit halves&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;  for&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;let&lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt; round&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 0&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; &lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;round&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; &amp;lt; 6; &lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;round&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;++) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    const&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; next&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; left &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;^&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;await&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; this&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;round&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(round, right))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    left &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; right&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    right &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; next&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;  }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;  return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;left&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; &amp;lt;&amp;lt; 21n) | right&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The round function is HMAC-SHA256 over the round number and the right half, cut to 21 bits. The key is a Workers secret. Seven Base62 characters give 62^7, about 3.52 trillion codes. The Feistel network works on 42 bits, about 4.40 trillion values. A result outside the code space is permuted again (“cycle walking”). About 80% of IDs fit on the first pass.&lt;/p&gt;
&lt;p&gt;Two details are specific to Workers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;WebCrypto is async.&lt;/strong&gt; Each round awaits &lt;code&gt;crypto.subtle.sign&lt;/code&gt;, so one code is six or more awaited HMACs. That takes microseconds, far below the 10 ms CPU limit. The imported key is cached in module memory, so &lt;code&gt;importKey&lt;/code&gt; runs once per isolate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fixed vectors pin the output.&lt;/strong&gt; A test checks the codes for fixed IDs and a fixed key, so a change to the permutation cannot quietly map old IDs to new codes.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A generated code can still hit an existing custom alias, because aliases come from the same alphabet. The primary key catches it, and the create tries the next ID, up to 32 times.&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-one-batch-three-outcomes&quot;&gt;Challenge 2: one batch, three outcomes&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How does a retried request get the same answer as the first one?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The web UI sends a fresh &lt;code&gt;crypto.randomUUID()&lt;/code&gt; as the &lt;code&gt;Idempotency-Key&lt;/code&gt; with every create. If the network fails after the server has written the link, the retry must return that link, not make a second one.&lt;/p&gt;
&lt;p&gt;The link and the idempotency record are written in one &lt;code&gt;db.batch&lt;/code&gt;, which D1 runs as a transaction:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;ts&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;try&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  await&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; this&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.db.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;batch&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(statements)        &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// INSERT link; INSERT idempotency&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; link&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;} &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (err) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;isUniqueViolation&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(err)) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;throw&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; new&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; PlatformError&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;dependency&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, err)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (idem &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!==&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; null&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; this&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;replayIdempotency&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(link.ownerID, idem)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  throw&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; new&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; PlatformError&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;collision&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A unique-constraint failure has three meanings:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What collided&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Same request hash?&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Result&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The idempotency key&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Yes&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Return the original link. This is the retry&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The idempotency key&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;409 &lt;code&gt;IDEMPOTENCY_CONFLICT&lt;/code&gt;. The key was reused for a different request&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The short code only&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;n/a&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Try the next ID, or 409 &lt;code&gt;ALIAS_TAKEN&lt;/code&gt; for a custom alias&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The request hash is SHA-256 over the three body fields, in a fixed field order. Replay records last 24 hours.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-what-a-create-really-costs&quot;&gt;Challenge 3: what a create really costs&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How many D1 rows does one create write?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I measured each statement against local D1:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Statement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Rows written&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Insert the link&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;3: the row, the text primary key’s index, the &lt;code&gt;purge_at&lt;/code&gt; index&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Insert the idempotency record&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;3: the row, its primary key index, the &lt;code&gt;ttl&lt;/code&gt; index&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Lease a new block&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1, once per 100 creates&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;First click on the new code&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;2: the stats row and its primary key index&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So a create from the web UI writes 6 rows. A create through the API without a key writes 3. A takedown writes 2. A link in this schema costs more to create than to click, and the cost comes from the index entries.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-abuse-without-accounts&quot;&gt;Challenge 4: abuse without accounts&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you protect a public API when the limit is a daily quota?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;There is no sign-up and no API key, so limits are per client IP. There are two layers:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Layer&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Limit&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Where it runs&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Quota it saves&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Zone WAF rate-limit rule&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;3 creates per 10 s per IP and data center, then a 10 s block&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Before the Worker&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Requests and D1 writes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Worker rate-limit binding&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;10 creates per 60 s per IP, per data center&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Inside the Worker, before D1&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;D1 writes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The WAF rule is the important one. A blocked request never runs the Worker, so a flood costs nothing. The free plan allows one such rule, with a 10-second period, a 10-second block, and &lt;code&gt;cf.colo.id&lt;/code&gt; (the data center) as a required part of the key. The binding is the finer layer. It returns 429 with &lt;code&gt;Retry-After: 60&lt;/code&gt; and costs one Worker request. Cloudflare describes it as approximate and per data center by design.&lt;/p&gt;
&lt;p&gt;Then the arithmetic. The binding lets one IP make 10 creates a minute, or 14,400 a day. At 6 rows each, that is 86,400 rows: most of the 100,000-row daily quota, from one client staying under every limit. Two such clients would stop all writes, including click counts, until 00:00 UTC.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Rate limits stop floods. They do not stop someone patient.&lt;/strong&gt; That is the main weakness of a free-plan design with no accounts. When it happens, the result is an outage until midnight, not a bill, and the runbook’s upgrade trigger fires long before. The fixes are small: tighten the binding to a few creates a minute, or add a daily cap per IP. I have not done either yet, because real traffic is far from this point.&lt;/p&gt;
&lt;p&gt;There is also &lt;strong&gt;no bot challenge&lt;/strong&gt;. Cloudflare’s bot protection injects a JavaScript check that the site’s strict CSP (&lt;code&gt;script-src &amp;#39;self&amp;#39;&lt;/code&gt;) would block, so Terraform turns it off.&lt;/p&gt;
&lt;h2 id=&quot;challenge-5-cleanup&quot;&gt;Challenge 5: cleanup&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What removes old rows?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A cron trigger runs once a day at 03:17 UTC and runs one batch:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;DELETE&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; FROM&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; idempotency &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ttl &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ?;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;DELETE&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; FROM&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; links &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;WHERE&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; purge_at &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ?;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;purge_at&lt;/code&gt; is the link’s &lt;code&gt;expires_at&lt;/code&gt;, or 30 days after a takedown. Deletes count as rows written too, so a day with many expiring links shows up in the write quota. Click counters for purged links are not deleted yet. Today that costs only storage.&lt;/p&gt;
&lt;h2 id=&quot;how-it-is-tested&quot;&gt;How it is tested&lt;/h2&gt;
&lt;p&gt;The Worker tests run inside workerd, the real Workers runtime, through &lt;code&gt;@cloudflare/vitest-pool-workers&lt;/code&gt;. D1 migrations are applied in the test setup, so every test runs against real SQLite with the real schema. The suite covers create, the idempotency replay and conflict cases, the rate limiter, redirects through the edge cache with click counting, and the cron purge. A separate test fails if the OpenAPI document drifts from the handlers. There is no load test, because any sustained load would use up the quota it was meant to measure.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 4 covers deploying and running it: Terraform with its state in R2, deploys from tags, the first deploy by hand, one CSP kept in three places, backups and failure, and the bugs that only production showed.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Running a URL Shortener on Cloudflare for $0 (Part 2): The Redirect at the Edge</title><link>https://www.sumonselim.com/url-shortener-cloudflare-part2-the-redirect-at-the-edge/</link><guid isPermaLink="true">https://www.sumonselim.com/url-shortener-cloudflare-part2-the-redirect-at-the-edge/</guid><description>A click on mol.la is answered by the browser cache, a Cache API entry in the nearest Cloudflare data center, or one D1 read. Part 2 explains why the Cache API and not Workers Cache, why one response carries two cache lifetimes, how a removed link stops working without a versioned cache, which guarantees that relaxes, and how a click is counted after the response.</description><pubDate>Mon, 05 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; A click on mol.la is answered by the first of three places that has it: the browser for 5 seconds, the Cache API in that Cloudflare data center for 60 seconds, then D1. The click is counted after the response, with one D1 upsert, on cache hits and misses alike.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The Cache API, not Workers Cache.&lt;/strong&gt; With Workers Cache, a cache hit never runs the Worker, so the click could not be counted. The Cache API keeps the Worker in the path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Two lifetimes in one response.&lt;/strong&gt; The stored copy says &lt;code&gt;s-maxage=60&lt;/code&gt; for the edge. The browser only ever sees &lt;code&gt;max-age=5&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Short lifetimes instead of a versioned cache.&lt;/strong&gt; Nothing is cached for longer than 60 seconds, so removing a link needs no cache versions or tombstones. The worst case is bounded by time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Some guarantees are relaxed.&lt;/strong&gt; A 404 is cached, and an expired link can redirect for up to a minute. Both are accepted trade-offs.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;the-handler&quot;&gt;The handler&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What happens inside one click?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The Worker matches &lt;code&gt;/{code}&lt;/code&gt; for &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;HEAD&lt;/code&gt;. The code is checked against the alias rule first: 3 to 32 characters from letters, digits, hyphen and underscore. Anything else is a 404 with &lt;code&gt;no-store&lt;/code&gt; before any lookup. Then:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;ts&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; cached&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; await&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; deps.cache.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;match&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(cacheKey)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (cached &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!==&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; undefined&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (cached.status &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;===&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 302&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) ctx.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;waitUntil&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;countClick&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(deps.stats, code, now))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  const&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; out&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; new&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; Response&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, cached)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;  out.headers.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;set&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;Cache-Control&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;BROWSER_CACHE&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)      &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// &amp;#39;public, max-age=5&amp;#39;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; out&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; link&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; await&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; deps.store.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;get&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(code)                 &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// one row, by primary key&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; decision&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; decideRedirect&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(link, now)              &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// active and not expired?&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// 302 with Location, or 404. A D1 error returns 503 with no-store.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;const&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; stored&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; new&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; Response&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;null&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, response)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;stored.headers.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;set&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;Cache-Control&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;`${&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;BROWSER_CACHE&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;}, s-maxage=${&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;EDGE_TTL_SECONDS&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;}`&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;ctx.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;waitUntil&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(deps.cache.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;put&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(cacheKey, stored))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; response&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The cache key is the code alone. The query string is removed and the method is set to &lt;code&gt;GET&lt;/code&gt;, so &lt;code&gt;/abc?utm=x&lt;/code&gt; and &lt;code&gt;HEAD /abc&lt;/code&gt; share one entry. &lt;code&gt;decideRedirect&lt;/code&gt; is a pure function from the core: a link is found only if it is active and &lt;code&gt;now&lt;/code&gt; is before &lt;code&gt;expires_at&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener-cloudflare/redirect-path.svg&quot; alt=&quot;The redirect path: browser, Cache API in one data center, then D1, with the click counted after the response&quot; title=&quot;Figure 1: A click is answered by the browser for 5 seconds, by the data center&apos;s Cache API for 60 seconds, and by D1 only on a miss. On a 302, from cache or from D1, the click is written to D1 after the response with waitUntil.&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;challenge-1-a-cache-that-lets-the-worker-run&quot;&gt;Challenge 1: a cache that lets the Worker run&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why the Cache API and not Workers Cache or a CDN rule?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Cloudflare offers three ways to cache a Worker’s response:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;On a hit&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Problem for mol.la&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Zone cache rules&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No hit at all&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The zone cache does not store a response the Worker generates itself&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Workers Cache&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The Worker does not run&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No code runs on a hit, so the click is lost. The hit is still billed as a request&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Cache API (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The Worker runs, reads the cache, answers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One request per hit, but the Worker can count the click&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The Cache API is the only option in which my code runs on every click. It costs one Worker request per hit, which Workers Cache also does. It saves D1 reads, not requests.&lt;/p&gt;
&lt;p&gt;The Cache API has two properties a CDN does not. It is &lt;strong&gt;per data center&lt;/strong&gt;: a &lt;code&gt;put&lt;/code&gt; in Amsterdam does not exist in Frankfurt. It also does &lt;strong&gt;not&lt;/strong&gt; use tiered caching. Each data center fills its own copy on its first miss. A popular code clicked in 50 data centers costs up to 50 D1 reads a minute, not one. With 5 million free rows read a day, that is fine. Reads were never the limit; writes were.&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-two-lifetimes-in-one-response&quot;&gt;Challenge 2: two lifetimes in one response&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why does the stored copy say 60 seconds and the browser copy 5?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The two caches have different jobs.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The browser&lt;/strong&gt; cannot be reached once it has a copy. Whatever lifetime it gets is how long a deleted link can stay live for that user. So it gets 5 seconds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The edge&lt;/strong&gt; can be cleared. It is there to protect D1, and 60 seconds means one D1 read per code per data center per minute at most.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So the response stored in the cache says &lt;code&gt;public, max-age=5, s-maxage=60&lt;/code&gt;. &lt;code&gt;s-maxage&lt;/code&gt; applies only to shared caches such as the edge. On a hit, the Worker builds a new response and sets &lt;code&gt;Cache-Control&lt;/code&gt; back to &lt;code&gt;max-age=5&lt;/code&gt;. The first version returned the stored copy as it was, which sent &lt;code&gt;s-maxage&lt;/code&gt; to the client. A proxy between the user and Cloudflare could then keep the redirect for a minute.&lt;/p&gt;
&lt;p&gt;A zone setting broke this too. Cloudflare’s default Browser Cache TTL on the zone is 4 hours, and it can override the &lt;code&gt;max-age&lt;/code&gt; a Worker sets. On a staging hostname before launch, a removed link stayed in the browser for hours. The fix was one line of Terraform: &lt;code&gt;browser_cache_ttl = 0&lt;/code&gt;, which means “respect the existing headers”. Part 4 has more bugs that only production showed.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-removing-a-link-without-a-versioned-cache&quot;&gt;Challenge 3: removing a link without a versioned cache&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you keep a removed link dead without versions or tombstones?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A long-lived cache needs extra machinery to stay correct. If entries live for hours, a late cache write can undo a delete. Then every entry needs a version, every write must compare versions, and removed links must be cached as tombstones.&lt;/p&gt;
&lt;p&gt;mol.la avoids all of that by keeping lifetimes short. The longest anything is cached is 60 seconds at the edge plus 5 seconds in the browser. Removing a link does three things in order:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Soft delete in D1&lt;/strong&gt; with a version check: &lt;code&gt;UPDATE ... SET is_active = 0, version = version + 1 ... WHERE is_active = 1 AND version = ?&lt;/code&gt;. From this moment, every cache miss answers 404.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Delete the cache entry&lt;/strong&gt; in the data center that served the request.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Purge the URL across the zone&lt;/strong&gt; through the Cloudflare API, if a purge token is configured. It is optional: without it, the 60-second edge lifetime bounds how long other data centers serve the link.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener-cloudflare/takedown-windows.svg&quot; alt=&quot;What removing a link leaves behind in each cache&quot; title=&quot;Figure 2: After the soft delete, D1 answers 404. With a zone purge, every data center drops its copy. Without one, a data center that cached the 302 serves it until its 60 seconds run out. A browser that saw the 302 keeps it for up to 5 seconds.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The worst case does not depend on steps 2 and 3 working: 60 seconds at the edge plus 5 in the browser. One race remains. A redirect that read the active row just before the soft delete can store a 302 just after it. That entry lives its full 60 seconds. The time limit, not a version check, bounds it.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-what-is-cached-and-what-that-breaks&quot;&gt;Challenge 4: what is cached, and what that breaks&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Which guarantees does a 60-second cache relax?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Three guarantees matter for a redirect. Here is what holds for each:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Guarantee&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What holds&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A removed link stops redirecting&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Within 60 s at the edge without a purge, plus 5 s in the browser&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A new link works at once&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Not always: a 404 is cached for 60 s in the data center that served it&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;An expired link is not served&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A cached 302 can outlive &lt;code&gt;expires_at&lt;/code&gt; by up to 60 s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The second row is the one users can notice. If someone tries &lt;code&gt;mol.la/launch&lt;/code&gt;, gets a 404, and then creates the alias &lt;code&gt;launch&lt;/code&gt;, that data center can keep answering 404 for up to a minute. Caching 404s protects D1 from scanning, but scanning is already cheap: malformed codes never reach D1, and a well-formed miss costs at most one row read. Capping the edge lifetime at the link’s remaining life, and not caching 404s, would both be small changes.&lt;/p&gt;
&lt;p&gt;A D1 failure is never cached. It returns 503 with &lt;code&gt;no-store&lt;/code&gt;, so the next click tries again. Cached redirects keep working during a D1 outage for whatever is left of their 60 seconds. There is no stale fallback beyond that.&lt;/p&gt;
&lt;h2 id=&quot;challenge-5-counting-the-click&quot;&gt;Challenge 5: counting the click&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you write to a database on every click without slowing the click?&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;ts&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;async&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; function&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; countClick&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;stats&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt; StatsStore&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;code&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; string&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;now&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; number&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  try&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    await&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; stats.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;increment&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(code, &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, now)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;  } &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;catch&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (err) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    console.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;click count failed&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, { short_code: code, error: &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;String&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(err) })&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;  }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;increment&lt;/code&gt; is one statement:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;sql&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;INSERT INTO&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; stats&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (short_code, clicks, last_click_at) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;VALUES&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; (?, &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, ?)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;ON&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; CONFLICT (short_code) DO &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;UPDATE&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  SET&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; clicks &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; clicks &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;+&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; excluded&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;clicks&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;      last_click_at &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; max&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(last_click_at, &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;excluded&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;last_click_at&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It runs inside &lt;code&gt;ctx.waitUntil&lt;/code&gt;, which lets the Worker keep running after the response is sent. The response does not wait for the write. The runtime keeps the isolate alive until the write settles. Without &lt;code&gt;waitUntil&lt;/code&gt;, the write would have to finish before the response, and every click would wait for D1.&lt;/p&gt;
&lt;p&gt;Counts are approximate. A failed write is logged and not retried. A click served from the browser cache never reaches the Worker. The architecture review lists the counts as an accepted risk: fine for a stats page, not fit for billing.&lt;/p&gt;
&lt;p&gt;Every click is also a D1 write, so anything that requests short links uses the write quota. &lt;code&gt;robots.txt&lt;/code&gt; blocks every path except the site’s own pages and discovery files.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 3 follows a link from creation. It covers how a short code is made from a leased block and a keyed permutation in WebCrypto, how a link and its idempotency key are written in one D1 batch, and how a public API with no accounts is protected when the limit is a daily quota, not a bill.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Running a URL Shortener on Cloudflare for $0 (Part 1): The Architecture</title><link>https://www.sumonselim.com/url-shortener-cloudflare-part1-the-architecture/</link><guid isPermaLink="true">https://www.sumonselim.com/url-shortener-cloudflare-part1-the-architecture/</guid><description>mol.la is an open-source URL shortener that runs on one Cloudflare Worker and one D1 database for $0 a month. Part 1 explains the requirements, which free-plan quota really limits the design, why KV, Queues and Durable Objects were left out, what every action costs in requests and rows written, and how the code keeps the platform at the edges.</description><pubDate>Sun, 04 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; &lt;a href=&quot;https://mol.la&quot;&gt;mol.la&lt;/a&gt; is an open-source URL shortener. It runs on one Cloudflare Worker, one D1 database and the edge cache, and it costs $0 a month on the Workers Free plan. The whole design follows three rules.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;the redirect touches as little as possible&lt;/strong&gt;. A click is answered by the browser cache, then by the cache in the nearest Cloudflare data center, and only then by D1. The click is counted after the response, never inside it.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;each free quota is a budget&lt;/strong&gt;. The question is not “what does this cost?” but “which daily quota does this use?” For mol.la the scarcest one is D1 rows written, not requests.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;the core is pure code, and the platform stays at the edges&lt;/strong&gt;. Code generation, validation and the redirect decision import nothing from Cloudflare. Everything that touches D1 or the cache sits behind a small interface, so every handler can be tested in the real Workers runtime with no account.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does a URL shortener have to do well?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A URL shortener looks like a key-value lookup. The requirements make it harder:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What it means for the design&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Short codes that cannot be guessed&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;7 characters, not sequential, never reused&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Custom aliases&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A user may pick &lt;code&gt;mol.la/launch&lt;/code&gt;, so codes and aliases share one namespace&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Expiry&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every link has an end date, 5 years by default&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Fast redirects everywhere&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The common case must be answered near the user, without a database round trip&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Removed links stop working quickly&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A cache must not keep serving a link after it is removed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Click counts&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Useful, but approximate is fine&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A public API with no accounts&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Abuse control has to work per client IP&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;$0 a month&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every component must fit a free plan&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The last row decides most of the others.&lt;/p&gt;
&lt;h2 id=&quot;the-constraint&quot;&gt;The constraint&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does the Workers Free plan give you?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Resource&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Free per day&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Note&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Worker requests&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;100,000&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Over the limit, the route returns error 1027&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;CPU time&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;10 ms per request&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Waiting on I/O does not count&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Static asset requests&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Unlimited&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Served before the Worker runs&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;D1 rows read&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;5,000,000&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;D1 rows written&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;100,000&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Each index touched by a write adds one more row&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;D1 storage&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;500 MB per database&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Up to 10 databases and 5 GB per account&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;KV writes&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1,000&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Queues operations&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;10,000&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;About 3 per message&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;All daily limits reset at 00:00 UTC. Since 1 September 2026, D1 queries fail when an account goes over its daily row limits.&lt;/p&gt;
&lt;p&gt;This sets the failure mode. Too much traffic does not create a bill. It stops the service until midnight UTC. For a hobby project, I prefer an outage I can see to a bill I did not expect.&lt;/p&gt;
&lt;h2 id=&quot;challenge-1-which-products&quot;&gt;Challenge 1: which products&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why one Worker and one database, and not KV, Durable Objects or Queues?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Each product was checked against the quota it would use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;KV as a redirect cache.&lt;/strong&gt; Every cache fill is a KV write, and the free plan has 1,000 writes a day. Clicks on 1,000 different codes would use up the quota.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Queues for clicks.&lt;/strong&gt; A message costs about three operations: write, read and delete. 10,000 operations is about 3,300 clicks a day, far below the Worker’s 100,000 requests.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Durable Objects.&lt;/strong&gt; The free plan only offers SQLite-backed objects, with the same row limits as D1. They would add a second storage model and no extra quota.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Cache API.&lt;/strong&gt; It has no quota of its own. A Worker can store and read responses in the cache of the data center that is serving the request. It is the redirect cache.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Static Assets.&lt;/strong&gt; The web UI is plain files. Requests that match a file are served before the Worker runs, for free.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;D1.&lt;/strong&gt; One SQLite database holds links, idempotency records, the ID counter and click counts. Every lookup is by primary key.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;What is left is one Worker that serves redirects, the JSON API and the UI shell. It has one D1 database, one cron trigger, and one rate-limit binding.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener-cloudflare/architecture.svg&quot; alt=&quot;mol.la on Cloudflare: one Worker, one D1 database and the edge cache&quot; title=&quot;Figure 1: Every request reaches Cloudflare&apos;s edge. Static files are served without the Worker. Everything else runs in one Worker. It reads the edge cache first, then D1. The only scheduled job is a daily cleanup.&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-where-the-budget-goes&quot;&gt;Challenge 2: where the budget goes&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does one click cost?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The question is not about dollars. It is about which quotas each action uses:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Action&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Worker requests&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;D1 rows written&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;D1 rows read&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Redirect, edge cache hit&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1 (2 on a code’s first click)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Redirect, cache miss&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1 (2 on a code’s first click)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Create a link from the web UI&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;6&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Lease a new block of 100 IDs&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Stats API call for a link&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Static page or asset&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Two things in this table shaped the design.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;An edge cache hit is not free.&lt;/strong&gt; The cache lives inside the Worker, so every hit still uses a request. The hit also writes a click to D1, so cached redirects still use writes. Requests and writes run out at about the same point: 100,000 clicks a day.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Indexes cost writes.&lt;/strong&gt; D1 counts each index entry a write touches as another row written. A new link writes its row, the automatic index behind its text primary key, and its &lt;code&gt;purge_at&lt;/code&gt; index entry: 3 rows. The web UI always sends an idempotency key, and that record costs 3 more. I measured these numbers against local D1. A create costs six times as much as a click. Clicks are still the bigger total, because there are far more of them.&lt;/p&gt;
&lt;p&gt;The upgrade trigger is about 70,000 requests or 70,000 rows written in a day. Above that, the Workers Paid plan costs $5 a month. It turns the hard stop into per-use billing and includes 10 million requests and 50 million D1 rows written each month.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-keep-the-platform-at-the-edges&quot;&gt;Challenge 3: keep the platform at the edges&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How is the code laid out so the design can be tested?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The Worker is one bundle under 100 KB, in four layers:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Layer&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Files&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Depends on Cloudflare?&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Core&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;core/&lt;/code&gt;: Base62, the code permutation, URL and alias validation, the redirect decision&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No. Pure functions&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Handlers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;handlers/&lt;/code&gt;: redirect, create, stats&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Only through interfaces passed in&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Adapters&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;store.ts&lt;/code&gt; for D1, the purge client&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Router&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;index.ts&lt;/code&gt;: matches paths and wires adapters into handlers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;A handler never reaches for a global. The redirect handler gets a link store, a stats store and a cache as arguments. The tests run inside workerd, the Workers runtime, with a local D1 and the Cache API, so the real SQL runs against SQLite in the same runtime as production.&lt;/p&gt;
&lt;p&gt;Two things live in module memory, so they survive between requests in the same isolate: the imported HMAC key for code generation, and the current block of leased IDs. Both are cheap to lose. A new isolate imports the key again and leases a new block.&lt;/p&gt;
&lt;p&gt;A test file of fixed vectors pins the code generator. For example, ID 0 with the test key must encode to &lt;code&gt;UIiAFaQ&lt;/code&gt;. Any change to the permutation, the alphabet or the code length fails that test before it can change which code an ID maps to.&lt;/p&gt;
&lt;h2 id=&quot;what-it-gives-up&quot;&gt;What it gives up&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Which risks are accepted?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A ceiling.&lt;/strong&gt; The free plan stops at about 100,000 redirects a day, or about 3 million a month.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One database location.&lt;/strong&gt; D1 has one primary. If it is down, redirects already in a data center’s cache keep working for up to 60 seconds. Everything else returns 503. There is no automatic failover.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No load tests.&lt;/strong&gt; Any sustained load test would use up the day’s quota.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Short staleness windows.&lt;/strong&gt; A removed link can still redirect for about a minute in some data centers. Part 2 explains why that is the chosen trade-off.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Approximate clicks.&lt;/strong&gt; A failed click write is logged, not retried.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Most of these are listed as accepted risks in the project’s architecture review. At this traffic, closing them would cost more than the service is worth.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 2 follows one click through the edge. It covers why the Cache API and not Workers Cache, why one response carries two different cache lifetimes, how a removed link stops working without a versioned cache, and how a click is counted after the redirect is sent.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a URL Shortener in AWS (Part 3): Writes, Clicks, and the Slow Path</title><link>https://www.sumonselim.com/url-shortener-part3-writes-clicks-and-the-slow-path/</link><guid isPermaLink="true">https://www.sumonselim.com/url-shortener-part3-writes-clicks-and-the-slow-path/</guid><description>A redirect is only half the system. Part 3 follows a link from creation to its click count: validation that never fetches the destination, an idempotency key and a generated code written in one DynamoDB transaction, a Kinesis click pipeline that never slows a redirect, abuse controls for a public API with no accounts, and a test strategy that needs no cloud account.</description><pubDate>Sat, 03 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Update, 4 October 2026:&lt;/strong&gt; mol.la no longer runs on AWS. On 1 October I moved it to one Cloudflare Worker and one D1 database, and it now runs for $0 a month. This series still describes the AWS design as it was built. The Cloudflare version is covered in &lt;a href=&quot;https://www.sumonselim.com/series/running-a-url-shortener-on-cloudflare-for-0/&quot;&gt;Running a URL Shortener on Cloudflare for $0&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; The write path does exactly three things: validate the request without touching the network, mint a code, and write the link and its optional idempotency record in &lt;strong&gt;one DynamoDB transaction&lt;/strong&gt;. A retry with the same &lt;code&gt;Idempotency-Key&lt;/code&gt; returns the original link; the same key with a different body returns a conflict. The handler never fetches, resolves or previews the destination, which is the entire defence against being used to reach internal addresses.&lt;/p&gt;
&lt;p&gt;Clicks are written as items to a &lt;strong&gt;DynamoDB &lt;code&gt;Clicks&lt;/code&gt; table&lt;/strong&gt; after the redirect is written, and the table’s &lt;strong&gt;stream&lt;/strong&gt; feeds an aggregation Lambda that folds a batch into one write per code on a separate stats table. The first deployed version used Kinesis. At hobby scale the idle stream and its VPC interface endpoint were most of the bill, so four ways of moving clicks were priced against each other and the one with no fixed cost won. The redirect never writes a counter. Counts are stated to be approximate: edge hits never reach Lambda, and at-least-once delivery can add a retry.&lt;/p&gt;
&lt;p&gt;The public API has no accounts in this release, so abuse control is two independent layers: Cloudflare rate-limits link creation per IP, and API Gateway caps aggregate throughput. Takedown is an IAM-authenticated CLI, never an API key.&lt;/p&gt;
&lt;p&gt;The whole codebase is split into a provider-neutral core, small port interfaces, and per-provider adapters. Every package tests against in-memory fakes with no cloud account, no network and no emulator, which is how the design was checked before it was ever deployed.&lt;/p&gt;
&lt;h2 id=&quot;the-create-path&quot;&gt;The create path&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What happens inside &lt;code&gt;POST /api/v1/links&lt;/code&gt;?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/create-flow.svg&quot; alt=&quot;The create path, from validation to one DynamoDB transaction&quot; title=&quot;Figure 1: Validation is local and cheap. A custom alias goes straight to the transaction. A generated code comes from a leased integer, permuted and Base62-encoded. The transaction writes the link and the idempotency record together, or neither.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The request is a JSON body with one required field, &lt;code&gt;long_url&lt;/code&gt;, and two optional ones, &lt;code&gt;alias&lt;/code&gt; and &lt;code&gt;expires_in&lt;/code&gt;. The handler does the following, in order:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Bound the body&lt;/strong&gt; at 16 KiB before decoding. A URL is at most 2,048 characters, so a larger body is never legitimate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Validate the URL&lt;/strong&gt; without a network call. It must parse, use &lt;code&gt;http&lt;/code&gt; or &lt;code&gt;https&lt;/code&gt;, have a non-empty host, carry no userinfo and no control characters, and fit in 2,048 characters. Anything else is &lt;code&gt;400 INVALID_URL&lt;/code&gt;. The scheme allowlist is what keeps &lt;code&gt;javascript:&lt;/code&gt;, &lt;code&gt;data:&lt;/code&gt; and &lt;code&gt;file:&lt;/code&gt; out of a &lt;code&gt;Location&lt;/code&gt; header.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Validate the alias&lt;/strong&gt;, if given: 3 to 32 characters from letters, digits, hyphen and underscore, and not &lt;code&gt;api&lt;/code&gt; or &lt;code&gt;app&lt;/code&gt;, which are routing prefixes at the edge.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Validate the lifetime&lt;/strong&gt;: 60 seconds to 5 years, with 5 years as the default.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Validate the idempotency key&lt;/strong&gt;, if the header is present: 1 to 128 visible ASCII characters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mint the code&lt;/strong&gt;: the alias as given, or a leased integer permuted and encoded as described in Part 1.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Write one transaction&lt;/strong&gt; and map its outcome to a response.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;The handler never fetches the target URL.&lt;/strong&gt; No liveness check, no &lt;code&gt;HEAD&lt;/code&gt; request, no preview. A service that never makes an outbound request to a user-supplied URL cannot be tricked into fetching the instance metadata endpoint or an internal address on the caller’s behalf, because it never fetches anything at all. Malicious destinations are therefore an asynchronous, post-creation concern (see Abuse below), not a write-path gate. This is also why the API function needs no VPC and no NAT gateway.&lt;/p&gt;
&lt;h2 id=&quot;challenge-1-one-transaction-three-outcomes&quot;&gt;Challenge 1: one transaction, three outcomes&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How does a retry get the same answer as the original?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Clients retry. A mobile app that times out on create will send the same request again, and without help it will create a second link. The standard answer is an &lt;code&gt;Idempotency-Key&lt;/code&gt; header, and the interesting part is what it is scoped to and what it is compared against.&lt;/p&gt;
&lt;p&gt;I compared three designs.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Problem&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Store the key in the link item and query by it&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Needs a secondary index on every link for a field most links do not have, and a race between two concurrent requests with the same key can still create two links.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Write the idempotency record first, then the link&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;If the process dies between the two writes, the key points at a link that does not exist, and every retry returns a 404 for a link the client thinks it created.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;One transaction over both items (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;TransactWriteItems&lt;/code&gt; puts the link on the condition that the code is absent, and the idempotency record on the condition that the key is absent. Both succeed or neither does. There is no state in which the key exists without the link.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The idempotency record holds the short code, a 24-hour TTL, and a hash of the request. The hash is SHA-256 over the validated &lt;code&gt;{long_url, alias, expires_in}&lt;/code&gt; struct with defaults filled in, never over the raw JSON bytes, so whitespace and key order do not matter but a changed body does.&lt;/p&gt;
&lt;p&gt;A cancelled transaction has to be classified, and a guess is not good enough:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/idempotency-classification.svg&quot; alt=&quot;How a cancelled transaction is classified&quot; title=&quot;Figure 2: When the transaction is cancelled and an idempotency key was given, the adapter reads the stored record with a consistent read. The same hash replays the original link. A different hash is a conflict. No record means the link condition failed, which is a code collision.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;No idempotency key on the request:&lt;/strong&gt; the only condition that can fail is the link’s. For an alias that is &lt;code&gt;409 ALIAS_TAKEN&lt;/code&gt;. For a generated code it is a collision with an alias someone chose earlier, so the handler takes the next integer from its block and tries again, up to 32 times.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Key given, record found with the same hash:&lt;/strong&gt; a retry. Read the stored link and return the original &lt;code&gt;201&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Key given, record found with a different hash:&lt;/strong&gt; the same key reused for a different request. &lt;code&gt;409 IDEMPOTENCY_CONFLICT&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Key given, no record:&lt;/strong&gt; the idempotency put succeeded in some earlier attempt that we never heard about? No: if it had, the record would be there. So the link put is what failed, and the outcome is a collision, handled as above.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The read after the cancel is strongly consistent. An eventually consistent read could miss a record written milliseconds earlier and turn a legitimate retry into a false collision.&lt;/p&gt;
&lt;p&gt;In the current release the API is public and has no accounts, so the idempotency scope is effectively global. The record key is built as &lt;code&gt;{owner_id}#{key}&lt;/code&gt; with an empty owner, so that when authenticated ownership returns, the scope narrows to one caller without a data migration.&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-clicks-off-the-hot-path&quot;&gt;Challenge 2: clicks off the hot path&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you count 10 billion clicks a month without a counter on the hot row?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Part 1 explained why the click counter is not on the link item. Something has to carry each click from the redirect to a batch writer, and the choice of that something turned out to be the most expensive decision in the deployed system, in the least expected direction.&lt;/p&gt;
&lt;p&gt;The first deployed version used the textbook shape: the redirect published each click to a &lt;strong&gt;Kinesis Data Streams&lt;/strong&gt; stream, an aggregation Lambda consumed it, and &lt;strong&gt;Firehose&lt;/strong&gt; archived the raw events to S3. It worked. Then the first month’s bill arrived, and the Kinesis line was larger than every other line combined. Not because of traffic, which rounded to zero, but because an on-demand stream bills about $0.04 an hour for existing, and the redirect Lambda, being inside a VPC, needed a Kinesis &lt;strong&gt;interface endpoint&lt;/strong&gt; at about $7.30 per AZ-month just to reach it. About $36 a month of fixed cost to carry a few hundred clicks.&lt;/p&gt;
&lt;p&gt;That prompted a proper comparison. Four ways to move a click, priced at the two scales that matter: the deployed hobby scale, where volume is near zero and fixed cost is everything, and the design target of 5 billion clicks a month reaching Lambda, where cost per event is everything.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Fixed cost per month&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Cost at 5B clicks a month&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What you get, and what you give up&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Kinesis Data Streams&lt;/strong&gt; plus Firehose archive&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$36 (on-demand stream hours plus one interface endpoint)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$250&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Ordered, multi-consumer, built for this volume. Partial-batch failure handling in the event source mapping. Needs an interface endpoint from a VPC function, and bills for existing.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;SQS standard&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$7 (interface endpoint; SQS has no gateway endpoint)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$2,000 (one request per click plus receives)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Simple and near-free per message, but a VPC function still needs an interface endpoint. One consumer only, so no archive.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;DynamoDB &lt;code&gt;Clicks&lt;/code&gt; table plus DynamoDB Streams&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;$0 (gateway endpoint is free; Lambda reads from Streams are free)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$6,250 (one on-demand write per click)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Keeps the batch aggregator unchanged. The items are the archive, expiring by TTL. Highest cost per click by far.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Direct &lt;code&gt;UpdateItem ADD&lt;/code&gt; on &lt;code&gt;LinkStats&lt;/code&gt;&lt;/strong&gt; from the redirect&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;$0&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$6,250 (one write per click)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No pipeline at all. But a per-click write on the hot path, no batching to smooth a viral spike onto one item, no raw events, and no way to add a second consumer later.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose the DynamoDB table with Streams.&lt;/strong&gt; At the scale the system actually runs, the two zero-fixed-cost options cost nothing, and the table wins between them because it keeps everything the aggregator was built to do: batching per code, partial-batch retries, bisecting on error, and the on-failure queue. The raw items also replace the S3 archive, queryable for 90 days and then gone by TTL. The whole change was one adapter, one Lambda entrypoint, and one Terraform module, which is what the port structure described in Challenge 4 is for.&lt;/p&gt;
&lt;p&gt;The trade is honest and it is written into the design document: at the design target, one write per click costs about 25 times what Kinesis would. If real traffic ever approaches the envelope, the Kinesis shape is the right one again, and switching back is the same one-adapter change. A design that is right for 5 billion clicks and wrong for 500 is not the right design to deploy for 500.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/click-pipeline.svg&quot; alt=&quot;The click pipeline&quot; title=&quot;Figure 3: The redirect writes one item per click, after the 302, through the free gateway endpoint. The table&apos;s stream, filtered to inserts, feeds an aggregation Lambda that folds a batch into one UpdateItem per code. Failures go to an on-failure queue with an alarm. TTL removes raw items after 90 days without invoking anything.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The details that matter:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The item is small and private.&lt;/strong&gt; &lt;code&gt;{event_id, short_code, occurred_at, source_ip_hash, ttl}&lt;/code&gt;. The source address is HMAC-SHA-256 hashed with a key that changes daily, before it leaves the function, so the same visitor can be counted within a day but never linked across days. No user agent, no referrer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The write has a 500 ms budget and happens after the 302.&lt;/strong&gt; A warm call through the VPC endpoint takes about 20 ms. A cold container’s first call, TLS handshake included, was observed to exceed 100 ms and drop the click, which is why the budget is 500 ms rather than 100. The redirect decision is already made and written by then; a failed write is logged and lost, never retried inside the request, and never turned into an error for the user.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The stream carries inserts only.&lt;/strong&gt; The event source mapping filters on &lt;code&gt;eventName = INSERT&lt;/code&gt;, so the TTL sweep’s &lt;code&gt;REMOVE&lt;/code&gt; records, which arrive on the same stream 90 days later, never invoke the function or count anything. The function checks the event name again anyway.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The aggregator folds a batch into one write per code.&lt;/strong&gt; It reads up to 100 records or 5 seconds’ worth, groups them by the &lt;code&gt;short_code&lt;/code&gt; in each item’s image, and issues &lt;code&gt;UpdateItem ADD clicks :n SET last_click_at&lt;/code&gt; once per code. A million clicks on one link in five minutes become a few hundred writes. It returns partial-batch failures so only the failed records are retried, with two retries, bisecting the batch on error, and an encrypted SQS on-failure queue that alarms on a single message.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The event ID is the partition key&lt;/strong&gt; of the Clicks table, so writes spread evenly and a viral code cannot make one hot partition. Nothing reads the table by code; the stream is the only reader.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Counts are approximate, and the API says so.&lt;/strong&gt; CloudFront hits never invoke Lambda, so popular links are undercounted. Streams delivery to Lambda is at-least-once, so a retried batch can count a click twice. A per-click deduplication check would double the writes and undo the point of the pipeline. The stats endpoint promises an eventually consistent operational estimate, not a billing-grade count. Reconciling against CloudFront logs is follow-up work.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-abuse-controls-without-accounts&quot;&gt;Challenge 3: abuse controls without accounts&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you protect a public API that has no callers to identify?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The first design had API keys: a credentials table, hashed tokens, per-owner quotas through API Gateway usage plans, and an owner check on stats and delete. The scaffolding for that is still in the code. The deployed release removed the requirement, because a shortener that needs a key before it will shorten a URL is not useful to a visitor with a link to share. That decision moves every abuse control to layers that do not need an identity.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Layer&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What it controls&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why it is there&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cloudflare rate limit&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;POST /api/v1/links&lt;/code&gt; per client IP: a handful of requests per 10-second window, then blocked for 10 seconds&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The real control on anonymous creation. The zone is on the free plan, which allows one rule with a fixed window, so it is tuned tight, and a blocked request never reaches AWS at all.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cloudflare WAF&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Managed rules on every request&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Drops known-bad traffic at the edge before it is billed anywhere else.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;API Gateway stage throttle&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Total requests per second and burst across all callers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A blunt aggregate ceiling that protects the Lambda concurrency pool and the DynamoDB counter. It is not per-IP.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Strict input validation&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Code charset and length on every redirect, body size and URL rules on every create&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Bounds what probing and junk can cost before any storage access.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Operator takedown&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Soft delete plus tombstone, by an IAM-authenticated CLI with a mandatory reason&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The response to a malicious destination. Identity comes from STS, never from a flag or a key.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;What is deliberately missing is automated reputation checking. The service does not look up destinations against a blocklist, and it does not fetch them. Both would be asynchronous consumers of a creation event, outside the write path, and both are follow-up work. The first release provides the rate controls, the audit trail and a tested takedown, and states that.&lt;/p&gt;
&lt;p&gt;The stats endpoint has one small rule that is easy to miss. A taken-down link returns 404 from stats, not its click history. Confirming that a deleted code once existed, and how popular it was, is information a taken-down link should not give away.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-a-codebase-that-can-be-tested-without-a-cloud&quot;&gt;Challenge 4: a codebase that can be tested without a cloud&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How was this checked before it was deployed?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The seat reservation system had a launch date, months of load tests, and a mock payment gateway. This project had none of those, and one person. The strategy that replaced them is structural: make every piece of logic testable with no cloud account, and make the cloud-specific parts as thin as possible.&lt;/p&gt;
&lt;p&gt;The code is split into three kinds of package:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;core&lt;/code&gt;&lt;/strong&gt; holds the pure logic: Base62 encoding, the keyed permutation, validation, click aggregation, and the redirect decision. It imports nothing outside the standard library.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;platform&lt;/code&gt;&lt;/strong&gt; declares small interfaces, called ports: the link store, the stats store, the cache, the cache invalidator, the event publisher, the ID allocator, the audit sink, and a clock. Nothing here talks to a cloud.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;handlers&lt;/code&gt;&lt;/strong&gt; implements the HTTP contract as plain &lt;code&gt;net/http&lt;/code&gt; handlers that depend only on the ports. They never import a Lambda type or an AWS SDK.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Everything AWS-specific lives in adapters that implement the ports, and in two thin Lambda entrypoints that wire adapters into handlers. The same handlers run in a single local process with in-memory adapters, which is what the web UI is developed against.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/testing-layers.svg&quot; alt=&quot;The testing layers, from pure functions to the live stack&quot; title=&quot;Figure 4: The layers of testing. The first four run in Docker or CI with no cloud credentials. The last two need a deployed non-production stack and an operator.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Each layer answers a different question:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Core tests&lt;/strong&gt; are table-driven: known Base62 vectors, round-trips over a range of integers, the permutation’s bijectivity on a sampled range plus the boundaries &lt;code&gt;0&lt;/code&gt; and &lt;code&gt;62^7 - 1&lt;/code&gt;, every validation edge, and every redirect branch. A benchmark covers permute-plus-encode, the allocator’s hot path.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Handler tests&lt;/strong&gt; run every endpoint end to end against the in-memory fakes: create with and without an alias, create with a retried key, a conflicting key, a code collision that retries, every cache outcome from Part 2 including a failing store, and a takedown whose invalidation fails and then succeeds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Adapter tests&lt;/strong&gt; run against local fakes in-process: a small fake DynamoDB server that returns the same cancellation reasons the real one does, and a fake Redis server for the version script and the tombstone shape. The click store and the stream consumer are tested the same way: the item written, the TTL on it, and a batch with a malformed record, a failing code and a TTL removal in it. Nothing in the default test run needs DynamoDB Local, LocalStack or a network.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Infrastructure checks&lt;/strong&gt; run on every pull request: formatting, validation of every module and environment root with no backend and no credentials, and a read-only Terraform plan posted as a comment on any pull request that touches the AWS directory. Apply runs only from a version tag, through an OIDC role, never from a merge.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The load envelope&lt;/strong&gt; is two k6 scripts, one for 15,432 redirects a second and one for 154 creates a second, each with p99 and error-rate thresholds that abort the run. They run only from an operator workstation against a non-production stack. They are the envelope the design was sized for, and the runbook says so; they are not a record of a launch.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An audit of the live stack&lt;/strong&gt; closed the gaps that only a deployment shows: a Function URL that needed a second IAM permission the documentation did not mention, a KMS key policy that had to name CloudFront before the UI bucket would serve, reserved words in a DynamoDB update expression, and the origin check that has to answer 403 on the bare CloudFront hostname before the domain is switched over.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The deployed system is sized for hobby scale, not for the design targets: no provisioned concurrency, one Redis node, on-demand Kinesis, point-in-time recovery off, and the smallest instance sizes throughout. Every module has the production sizes as documented alternatives, and the runbook lists what to raise, in what order, if traffic ever approaches the envelope.&lt;/p&gt;
&lt;h2 id=&quot;lessons&quot;&gt;Lessons&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What would I tell someone building this next?&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Decide the hot path first, and keep everything else out of it.&lt;/strong&gt; A redirect is one cache read, one table read on a miss, and one event after the response. Anything that wants to be inside that request has to justify itself against the p99 target, and a click counter never will.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check the assumptions of the standard answer against your runtime.&lt;/strong&gt; Snowflake IDs are the textbook choice, and they are wrong on Lambda because Lambda has no stable worker ID. Block leasing with a permutation is less famous and fits.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Give every cache record a version, and compare it in the same atomic step as the write.&lt;/strong&gt; A cache that can be overwritten by a late writer will eventually serve something you deleted. A tombstone is only as good as the write that protects it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Serve stale only inside a window you can defend, and never over a positive “no”.&lt;/strong&gt; Availability during a database failure is worth 15 minutes of bounded staleness. It is not worth resurrecting a link that was taken down.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Make the delete finish in the cache.&lt;/strong&gt; The durable write is not the end of a delete. The operation is done when every tier that could still answer “yes” has been told “no”, and until then it should say so.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Never fetch what the user gave you.&lt;/strong&gt; The simplest defence against server-side request forgery is a write path that makes no outbound requests at all. It also removes a NAT gateway from the bill.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Say what the numbers mean.&lt;/strong&gt; Click counts here are estimates, and the stats API says so. A design that hides its accuracy bounds gets a reconciliation project later, under pressure.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Structure the code so the cloud is optional.&lt;/strong&gt; Ports, fakes and pure functions meant every correctness property in this series was tested before an account existed. The live stack still found things, but they were configuration gaps, not logic bugs. The same structure is what made swapping the click pipeline a one-adapter change.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Price the design at the scale you will actually run, not only the scale you designed for.&lt;/strong&gt; The textbook click pipeline was the cheapest per event and the most expensive per month. Fixed costs dominate a small system the way per-request costs dominate a large one, and the bill is the only test that catches it.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The result is a system whose design targets are 10 billion redirects a month with a p99 under 50 ms, running today at a fraction of that on the smallest sizes of every service, with the same code and the same tests.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a URL Shortener in AWS (Part 2): Never Serve a Dead Link</title><link>https://www.sumonselim.com/url-shortener-part2-never-serve-a-dead-link/</link><guid isPermaLink="true">https://www.sumonselim.com/url-shortener-part2-never-serve-a-dead-link/</guid><description>A cache that is fast but wrong is worse than no cache. Part 2 explains the Redis record behind every redirect: three timestamps instead of one TTL, a version number on every write, tombstones that carry no destination, the narrow case in which a stale URL may still be served, and how an operator takedown propagates through DynamoDB, Redis and the edge in that order.</description><pubDate>Fri, 02 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Update, 4 October 2026:&lt;/strong&gt; mol.la no longer runs on AWS. On 1 October I moved it to one Cloudflare Worker and one D1 database, and it now runs for $0 a month. This series still describes the AWS design as it was built. The Cloudflare version is covered in &lt;a href=&quot;https://www.sumonselim.com/series/running-a-url-shortener-on-cloudflare-for-0/&quot;&gt;Running a URL Shortener on Cloudflare for $0&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; The redirect path serves almost every click from cache, so the cache has to be right about two things: a new link must be visible on its first click, and a deleted link must never come back. Both come down to what a cache record holds and how it is written.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Three timestamps, not one TTL.&lt;/strong&gt; A record is fresh for up to 24 hours, then stale for 15 minutes more, and the Redis key itself never outlives the link’s own expiry. Stale means “check DynamoDB first”, not “serve it”.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Every write compares versions.&lt;/strong&gt; DynamoDB increments the link’s version on every state change. A Redis write is one Lua script that refuses to overwrite a record with a higher version. A slow populate can never undo a tombstone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tombstones carry no destination.&lt;/strong&gt; A deleted link is cached as &lt;code&gt;deleted&lt;/code&gt; with its version and a 24-hour lifetime. It answers 404 without touching the table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stale is a fallback, not a feature.&lt;/strong&gt; A stale active record is served only when DynamoDB fails, only within the 15-minute grace, and never over a tombstone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Takedown finishes in Redis, not in DynamoDB.&lt;/strong&gt; The durable soft delete happens first. The operation is not reported as done until a tombstone with that version is in the cache. The edge entry ages out on its own within 5 seconds.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;the-invariants&quot;&gt;The invariants&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What exactly does “never serve a dead link” mean?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Before writing the cache, I wrote down three invariants (rules that must always be true). Everything in this post exists to keep them true.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;A deleted link stays deleted.&lt;/strong&gt; Once a delete or takedown is reported as successful, no later click is redirected to that destination, apart from a 302 already cached at the edge for at most 5 seconds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A new link is visible at once.&lt;/strong&gt; The first click after creation, including a custom alias created a moment after someone tried it, is served, never hidden behind a cached miss.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An expired link is not served.&lt;/strong&gt; The link’s own &lt;code&gt;expires_at&lt;/code&gt; is checked on every path, in the cache and in the table, and never delegated to a background cleanup.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Invariant 1 is the one that a naive cache breaks most easily. Invariant 2 is the reason unknown codes are never cached. Invariant 3 is the reason DynamoDB TTL is treated as cleanup, not as a correctness gate.&lt;/p&gt;
&lt;h2 id=&quot;the-state&quot;&gt;The state&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What lives in DynamoDB, and what lives in Redis?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;DynamoDB is authoritative. Redis is disposable: it can be flushed at any time and rebuilt from the table by ordinary traffic. Neither of those statements is true unless the record formats make them true.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Links item.&lt;/strong&gt; One item per code, no sort key, so every redirect is a single-digit-millisecond &lt;code&gt;GetItem&lt;/code&gt; on the exact key.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Attribute&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;short_code&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Partition key. A generated code or a custom alias.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;long_url&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The validated destination. Immutable after creation.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;is_active&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;False once deleted.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;version&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Starts at 1. Incremented atomically on every state change. This is what makes cache writes safe.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;expires_at&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The link’s logical end. Checked on every read.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;purge_at&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The DynamoDB TTL attribute. Equals &lt;code&gt;expires_at&lt;/code&gt; for active links, and &lt;code&gt;deleted_at&lt;/code&gt; plus 30 days for deleted ones.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;DynamoDB deletes expired items on a best-effort schedule, sometimes days late. So &lt;code&gt;purge_at&lt;/code&gt; is cleanup only. The read path also requires &lt;code&gt;now &amp;lt; expires_at&lt;/code&gt; and &lt;code&gt;is_active&lt;/code&gt;, every time.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The Redis record.&lt;/strong&gt; Key &lt;code&gt;url:{code}&lt;/code&gt;, a small JSON document:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Field&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;state&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;active&lt;/code&gt; or &lt;code&gt;deleted&lt;/code&gt;.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;long_url&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Present only on active records. A tombstone never carries a destination.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;version&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Copied from the DynamoDB item at the time of the write.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;expires_at&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The link’s own end, copied from the item.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;fresh_until&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Serve from cache alone until this moment. At most 24 hours after populate, and never past &lt;code&gt;expires_at&lt;/code&gt;.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;stale_until&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The Redis key’s own TTL. 15 minutes after &lt;code&gt;fresh_until&lt;/code&gt; for active records, 24 hours after &lt;code&gt;deleted_at&lt;/code&gt; for tombstones.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/cache-record-timeline.svg&quot; alt=&quot;The lifetime of one cache record&quot; title=&quot;Figure 1: An active record is fresh for up to 24 hours, then stale for 15 minutes, then gone. The key&apos;s TTL is capped at the link&apos;s own expiry, so the record cannot outlive the link. A tombstone lives 24 hours and carries no URL.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Why three timestamps instead of one TTL? Because they answer three different questions. &lt;code&gt;expires_at&lt;/code&gt; asks whether the link is alive. &lt;code&gt;fresh_until&lt;/code&gt; asks whether the cache may answer alone. &lt;code&gt;stale_until&lt;/code&gt; asks whether the cache is allowed to hold anything at all. Folding them into one number forces one of two bad trade-offs: either a short TTL that sends most clicks to the table, or a long TTL that serves a deleted link for its whole length.&lt;/p&gt;
&lt;h2 id=&quot;the-lookup&quot;&gt;The lookup&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does the redirect do with each cache outcome?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/cache-lookup-flow.svg&quot; alt=&quot;What the redirect handler does with each cache outcome&quot; title=&quot;Figure 2: The cache read has five outcomes. Only fresh and deleted are answered from Redis alone. Stale, miss and a Redis error all go to DynamoDB, whose answer decides what to cache and what to return. A read failure has one narrow fallback.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The handler first checks the code against the alias rule (3 to 32 characters, letters, digits, hyphen, underscore). Anything else is a 404 before any lookup, which bounds what probing can cost. Then it reads Redis and classifies the record against the current time:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Fresh active:&lt;/strong&gt; return 302 with &lt;code&gt;Cache-Control: public, max-age=5&lt;/code&gt;. This is the common case and the only path that costs one round trip.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deleted:&lt;/strong&gt; return 404 with &lt;code&gt;no-store&lt;/code&gt;. No table read. A tombstone is a positive answer, not a miss.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stale active:&lt;/strong&gt; revalidate. Read DynamoDB and apply whatever it says.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Miss, or expired by its own timestamps:&lt;/strong&gt; read DynamoDB.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Redis error or timeout:&lt;/strong&gt; treat as a miss. The Redis client has a 150 ms budget and retries disabled, so a failover costs at most 150 ms before the table read starts.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After a DynamoDB read, the outcome is decided once, in one pure function, from the item’s &lt;code&gt;is_active&lt;/code&gt;, &lt;code&gt;expires_at&lt;/code&gt; and the current time:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Active and not expired:&lt;/strong&gt; populate Redis with an active record and return 302.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unknown or expired:&lt;/strong&gt; return 404 and cache nothing. This is invariant 2. A cached miss would hide an alias created a second later. Expired links are not cached either, because a tombstone for a link that simply ran out would be a 24-hour entry for nothing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Inactive:&lt;/strong&gt; write a tombstone and return 404. From now on the table is not consulted for this code for 24 hours.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Everything above is deterministic. The one judgement call is what to do when DynamoDB itself fails.&lt;/p&gt;
&lt;h2 id=&quot;failure-mode-1-the-database-is-down-and-the-cache-is-old&quot;&gt;Failure mode 1: the database is down and the cache is old&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;When is it safe to serve a stale destination?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;DynamoDB is very reliable, but the redirect function talks to it through a VPC endpoint with a 1-second budget, and throttles or a slow partition on a viral key are real. When the revalidation read fails, there are three options.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Problem&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Return 503&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every click on a link whose cache entry passed &lt;code&gt;fresh_until&lt;/code&gt; in the last few minutes fails, while a perfectly good destination sits in Redis.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Serve the stale record, whatever it is&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A deleted link whose tombstone was never written, or whose cache entry is from before the delete, redirects again. That breaks invariant 1.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Serve the stale record only inside a bounded window (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The stale destination is served only if the record is &lt;code&gt;active&lt;/code&gt;, &lt;code&gt;now &amp;lt; stale_until&lt;/code&gt;, and &lt;code&gt;now &amp;lt; expires_at&lt;/code&gt;. A tombstone is always a 404. Anything else is 503 with &lt;code&gt;no-store&lt;/code&gt;.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The window is the 15 minutes between &lt;code&gt;fresh_until&lt;/code&gt; and &lt;code&gt;stale_until&lt;/code&gt;. Within it, the worst case is that a link deleted in the last 15 minutes, whose tombstone write also failed, is served during a DynamoDB outage. That is a double failure of two independent systems inside a short window, and the alternative is failing every revalidating click for the length of the outage. I accepted it, and the handler logs a warning on every stale serve so the count is visible.&lt;/p&gt;
&lt;p&gt;What the window never does is override a tombstone. If Redis says &lt;code&gt;deleted&lt;/code&gt;, the answer is 404 no matter what DynamoDB is doing. The tombstone is a positive fact, and the stale path only ever fills in for a missing one.&lt;/p&gt;
&lt;h2 id=&quot;failure-mode-2-the-slow-writer&quot;&gt;Failure mode 2: the slow writer&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Can a cache populate undo a delete?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Yes, if writes are plain &lt;code&gt;SET&lt;/code&gt;s. The redirect function and the invalidation function both write the same key, and they are not coordinated. Consider a click and a takedown that overlap:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/tombstone-vs-late-populate.svg&quot; alt=&quot;A late cache populate overwrites a tombstone unless writes compare versions&quot; title=&quot;Figure 3: Left: a redirect reads the active item from DynamoDB, a takedown writes the tombstone, then the redirect&apos;s populate lands and replaces it. The deleted link redirects for up to 24 hours. Right: every write runs one Lua script that rejects a lower version, so the tombstone survives.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The redirect read the item while it was still active. The takedown ran, wrote the DynamoDB update and the Redis tombstone. Then the redirect’s populate, carrying the old active record, arrived and overwrote the tombstone. The link is dead in the table and alive in the cache for the next 24 hours. Every click is a cache hit, so nothing ever asks the table again.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The fix is a version on every record and a compare on every write.&lt;/strong&gt; DynamoDB increments &lt;code&gt;version&lt;/code&gt; in the same conditional update that flips &lt;code&gt;is_active&lt;/code&gt;. Both the redirect and the invalidation function copy that version into the record they write. The write itself is one Lua script:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;lua&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; existing &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;GET&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;])&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; existing &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ok, decoded &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; pcall&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(cjson.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#79C0FF&quot;&gt;decode&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, existing)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ok &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;and&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; type&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(decoded) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;#39;table&amp;#39; &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;and&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; decoded[&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;version&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(decoded[&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;version&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;]) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;]) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;      return&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 0&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;                                  -- stored record is newer: keep it&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;SET&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;PX&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;]))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 1&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Redis runs a script from start to finish before anything else, so the read and the write cannot be separated by another writer. A separate &lt;code&gt;GET&lt;/code&gt; followed by a &lt;code&gt;SET&lt;/code&gt; in Go would reopen exactly the race in the figure. Equal versions are allowed to overwrite, so a retried write is idempotent (safe to run more than once, with the same result), and an active populate carrying the same version as the stored active record simply refreshes its timestamps.&lt;/p&gt;
&lt;p&gt;The rule I took from this is the same one that decided the seat reservation system’s admission script: &lt;strong&gt;a guard and the action it guards must live in the same atomic step.&lt;/strong&gt; A check followed by a separate write is a race, and under load every race is lost sooner or later.&lt;/p&gt;
&lt;h2 id=&quot;failure-mode-3-the-delete-that-only-half-happened&quot;&gt;Failure mode 3: the delete that only half happened&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What if the table is updated but the cache is not?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A delete has two writes in two systems, and the second one can fail: the invalidation function can time out, Redis can be mid-failover, the invoke can be throttled. If the operation reports success anyway, the link is dead in DynamoDB and alive in Redis for up to 24 hours. That is invariant 1 broken by a partial failure rather than by a race.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/takedown-flow.svg&quot; alt=&quot;An operator takedown, end to end&quot; title=&quot;Figure 4: The admin CLI takes its identity from STS, soft-deletes the item with a conditional update, then synchronously invokes the invalidation function, which writes the versioned tombstone. Only then is the audit event recorded as a success. If invalidation fails, the call returns 503 and must be retried.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The order is deliberate, and each step is idempotent:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identity comes from AWS, not from a flag.&lt;/strong&gt; The admin CLI calls &lt;code&gt;GetCallerIdentity&lt;/code&gt; and uses the returned ARN as the actor. There is no &lt;code&gt;--actor&lt;/code&gt; option to forge. A reason is mandatory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The durable delete is a conditional update.&lt;/strong&gt; &lt;code&gt;is_active&lt;/code&gt; becomes false and &lt;code&gt;version&lt;/code&gt; becomes &lt;code&gt;old + 1&lt;/code&gt;, on the condition that the item is still active with the old version. A retry after a partial failure finds the item already inactive and returns the stored deletion, with its version and timestamps, instead of failing. A retry by a different actor is refused.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Invalidation is synchronous.&lt;/strong&gt; The API role and the operator role are the only principals allowed to invoke the invalidation function, and they invoke it with &lt;code&gt;RequestResponse&lt;/code&gt; and wait. The payload is &lt;code&gt;{short_code, version, deleted_at}&lt;/code&gt;. Success means the tombstone with that version is in Redis. An older invalidation can never overwrite a newer record, because of the script above.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A failed invalidation is a failed delete.&lt;/strong&gt; The operation returns 503, records an audit event with outcome &lt;code&gt;invalidate_failed&lt;/code&gt;, and raises the alarm that security owns. The caller retries. The retry skips the state change, reissues the same tombstone, and returns success once it lands. The item is never reported deleted while a known positive cache entry may remain.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The edge takes care of itself.&lt;/strong&gt; CloudFront caches a 302 for 5 seconds and nothing else. There is no invalidation API call, no distribution-wide purge, and no &lt;code&gt;stale-while-revalidate&lt;/code&gt; that could extend the window.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The same service runs an owner’s own delete when authenticated ownership returns. In the current release, create and stats are public, so there is no owner to authorise, and the only delete is the operator’s.&lt;/p&gt;
&lt;h2 id=&quot;why-not-dax-and-why-not-a-simpler-redis&quot;&gt;Why not DAX, and why not a simpler Redis&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Was all of this necessary?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Part 1 listed the reasons DAX could not replace Redis here: no explicit deleted state, no version comparison, no bounded stale window. It is worth restating them from this side, because each one maps to an invariant.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Invariant&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What the cache must support&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;DAX&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Redis with this record&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A deleted link stays deleted&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A positive “deleted” answer that survives late writers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No: a deleted item is just a miss, and a miss goes to the table&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Tombstone plus version compare&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A new link is visible at once&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No negative caching of misses&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Item cache only, so misses are not cached, which is fine&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Unknown codes are never written&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;An expired link is not served&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The record carries the link’s own expiry and the read checks it&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The item carries it, but the cache TTL is separate&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;expires_at&lt;/code&gt; in the record, checked on every read, and the key TTL is capped at it&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;A simpler Redis layout would also have worked for the first two rows, using two keys per code or a plain &lt;code&gt;SET&lt;/code&gt; with a short TTL. The third row and Failure mode 2 are what forced the versioned single record. Once every write is one script that compares versions, the tombstone, the stale window and the takedown retry all fall out of the same mechanism.&lt;/p&gt;
&lt;p&gt;Two configuration details finish the picture. Redis runs with in-transit and at-rest encryption and an AUTH token held in an encrypted parameter. And eviction is allowed: any record can be evicted under memory pressure, because eviction is just a miss, and a miss goes to DynamoDB. That is the opposite of the seat reservation cache, where eviction would have lost the source of truth. Here the source of truth is the table, and the cache is only ever a copy.&lt;/p&gt;
&lt;h2 id=&quot;how-it-is-tested&quot;&gt;How it is tested&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you convince yourself a cache is right?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The redirect decision is a pure function&lt;/strong&gt; with a table test for every branch: active and not expired, active and expired, inactive, unknown.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The handler is tested against in-memory fakes&lt;/strong&gt; of the store, the cache and the publisher, for every outcome in Figure 2: fresh, stale with a healthy table, stale with a failing table inside and outside the grace window, tombstone with a failing table, miss, and a Redis error.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Redis adapter is tested against a fake Redis server in-process.&lt;/strong&gt; The tests cover the version script directly: a lower version is rejected, an equal version is accepted, a tombstone survives a late active write, and the key TTL never exceeds the link’s own expiry.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The takedown path is tested for partial failure:&lt;/strong&gt; a delete whose invalidation fails returns a dependency error, records the failed-invalidation audit event, and succeeds on retry without a second state change.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;None of these tests needs a cloud account, a network, or a running emulator. Part 3 explains why the code is structured to make that possible.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 3 follows a link from creation to its click count. It covers how a create request is validated without ever fetching the destination, how an idempotency key and a generated code are written in one transaction, how the click stream is kept off the redirect and aggregated in batches, what the abuse controls are for a public API with no accounts, and how the whole thing is tested in layers without a cloud account.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a URL Shortener in AWS (Part 1): The Architecture</title><link>https://www.sumonselim.com/url-shortener-part1-architecture-for-redirects/</link><guid isPermaLink="true">https://www.sumonselim.com/url-shortener-part1-architecture-for-redirects/</guid><description>A URL shortener is a read-heavy system with one hot path: the redirect. Part 1 explains the traffic shape (100 reads for every write), why the short code comes from a leased block of integers and a keyed permutation instead of a Snowflake ID, how three cache tiers keep most clicks away from the database, and why the redirect origin is a Lambda Function URL behind Cloudflare and CloudFront rather than API Gateway.</description><pubDate>Thu, 01 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Update, 4 October 2026:&lt;/strong&gt; mol.la no longer runs on AWS. On 1 October I moved it to one Cloudflare Worker and one D1 database, and it now runs for $0 a month. This series still describes the AWS design as it was built. The Cloudflare version is covered in &lt;a href=&quot;https://www.sumonselim.com/series/running-a-url-shortener-on-cloudflare-for-0/&quot;&gt;Running a URL Shortener on Cloudflare for $0&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; &lt;a href=&quot;https://mol.la&quot;&gt;mol.la&lt;/a&gt; is an open-source URL shortener I built in Go on AWS. The design target is 100 million new links a month with a 100:1 read-to-write ratio, a p99 redirect under 50 ms at the edge, and 99.9% availability for the redirect path. The whole design follows three rules.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;the redirect touches as little as possible&lt;/strong&gt;. A click is answered by CloudFront if the same code was seen in the last 5 seconds, then by Redis, and only on a double miss by DynamoDB. Click counting happens after the response, never inside it.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;short codes come from a leased block of integers, not a hash and not a Snowflake ID&lt;/strong&gt;. Each Lambda execution environment takes 1,000 integers from one DynamoDB counter with a single atomic &lt;code&gt;ADD&lt;/code&gt;, then hides the sequence behind a keyed permutation before Base62 encoding. Lambda has no stable worker ID, which is the one assumption Snowflake needs.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;the edge is two layers, and nothing reaches the origin without proof it came through both&lt;/strong&gt;. Cloudflare terminates TLS and runs the firewall. CloudFront routes by path and caches redirects. A shared secret header, stamped by Cloudflare and checked by a CloudFront function, closes the direct path to the distribution.&lt;/p&gt;
&lt;p&gt;The system is deployed and serving traffic, at hobby scale, on the smallest sizes of every managed service. The numbers in this series are the design targets that the code and the load scripts were built for, not measurements from a launch event. Where a number is a model rather than a measurement, the text says so.&lt;/p&gt;
&lt;p&gt;This series is written as a design reference: the requirements, the options I compared, and why I chose what I chose. The code is on &lt;a href=&quot;https://github.com/SumonMSelim/molla&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What makes a URL shortener hard?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The product is small. Someone submits a long URL and gets back a seven-character code. Anyone who opens &lt;code&gt;https://mol.la/{code}&lt;/code&gt; is sent to the long URL. That is two endpoints and one table.&lt;/p&gt;
&lt;p&gt;The traffic shape is what makes it hard. A shortener is written once and read many times, and the reads are not spread evenly. A link posted in a popular place gets thousands of clicks a minute for an hour and then almost none. Every one of those clicks is a request that a human is waiting on, in the middle of opening a page. The redirect must be fast, it must be right, and it must stay right after the owner deletes the link or an operator takes it down.&lt;/p&gt;
&lt;p&gt;Written out as requirements:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Detail&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Write volume&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;100 million new links a month, about 39 a second on average and 154 a second at peak.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Read volume&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;100 reads for every write: about 3,900 redirects a second on average, 15,400 at peak.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Redirect latency&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;p99 under 50 ms measured at the edge.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Availability&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;99.9% for the redirect path, measured at CloudFront. A region-wide outage is an accepted risk in the first release.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Retention&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Links live for 5 years by default, then expire. Callers can choose a shorter lifetime, down to one minute.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Custom aliases&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A caller can pick a 3 to 32 character alias instead of a generated code.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Click stats&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A count per link, allowed to lag by minutes. Not billing-grade.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Deletion and takedown&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A deleted or taken-down link must stop redirecting quickly, and must never come back.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Safety&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The service never fetches, previews or probes a destination URL.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Two of these define correctness: a deleted link must stay dead, and a new link must be visible on its first click. Part 2 is about those two. The rest of this post is about the shape of the system that serves the reads cheaply.&lt;/p&gt;
&lt;h2 id=&quot;the-shape-of-the-load&quot;&gt;The shape of the load&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Where do 10 billion monthly redirects get answered?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The design assumes three cache tiers between a click and DynamoDB, and it assumes a hit rate for each. Figure 1 shows the model that every capacity and cost number in this series is built on.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/read-funnel.svg&quot; alt=&quot;Redirects per month reaching each tier under the design’s hit-rate model&quot; title=&quot;Figure 1: Where redirects are answered under the design model. CloudFront sees all 10 billion. About half reach the redirect Lambda. Redis answers 95% of those, so about 250 million reads a month reach DynamoDB. These are assumptions to be replaced by metrics, not measurements.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Three things in that picture shaped the design:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Viral links and the long tail behave differently.&lt;/strong&gt; CloudFront caches a redirect for only 5 seconds. For a link clicked a few times a day, that is always a miss. For a link clicked a thousand times a minute, it absorbs almost everything. The 50% edge hit rate is a blend of the two, and it is the number I trust least. It is also the number that matters least for correctness, because the edge cache is short by design.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The database is the last resort, not the first.&lt;/strong&gt; With Redis in front of it, DynamoDB sees about one read in forty. A viral link is one partition key, and it cannot be sharded without changing the URL that people have already shared. The mitigation is that most of its traffic never reaches the table.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The per-request cost at the edge dominates the bill.&lt;/strong&gt; Every one of the 10 billion requests is a CloudFront viewer request, hit or miss. That is the expected shape of a 100:1 read-heavy service, and it is why the edge layer gets so much attention below.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;challenge-1-where-does-the-short-code-come-from&quot;&gt;Challenge 1: where does the short code come from?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What is the single decision that everything else depends on?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Every link needs a code that is unique, short, hard to guess, and cheap to mint under concurrent writers. Whatever produces that code is on the write path of every request, so I chose it first.&lt;/p&gt;
&lt;p&gt;I compared four options.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Hash the long URL&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;MD5 or SHA-256 of the URL, take the first 7 characters, check for a collision, retry&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Collisions become common at billions of rows, and every retry is a database round trip. Two people shortening the same URL also get the same code, which leaks who shortened what.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. One incrementing counter&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A database row holds the next integer; every create increments it&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A single hot writer that every request waits on. Codes are also sequential, so anyone can enumerate every link ever created.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Snowflake-style IDs&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Timestamp, worker ID and a sequence number, packed into an integer and Base62-encoded&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Needs a stable, long-lived worker ID per generator. AWS Lambda recycles execution environments on its own schedule and gives them no durable identity. Two environments that mint the same worker ID can mint the same code.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;D. Leased blocks of integers, permuted&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One DynamoDB counter item, advanced 1,000 at a time with an atomic &lt;code&gt;ADD&lt;/code&gt;. Each execution environment hands out integers from its block in memory. A keyed permutation hides the sequence before Base62 encoding.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One write to the counter per 1,000 codes, about 0.15 writes a second at peak. No coordination between environments and no worker identity needed. A wasted partial block after a cold start costs nothing but ID space, of which there are 3.5 trillion.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/code-generation-options.svg&quot; alt=&quot;Snowflake-style IDs on Lambda compared with leased integer blocks&quot; title=&quot;Figure 2: Snowflake assumes each generator has a durable worker ID, which Lambda cannot promise. Block leasing needs only one atomic counter update per block, and the permutation hides the order from clients.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose D.&lt;/strong&gt; The deciding argument was Lambda itself. Snowflake is the usual production recommendation, and it is a good one on a fleet of long-lived servers. On a fleet of ephemeral functions it reintroduces the collision risk it was designed to remove. Block leasing needs only one atomic increment, which DynamoDB’s &lt;code&gt;UpdateItem ADD&lt;/code&gt; provides without a read-modify-write race.&lt;/p&gt;
&lt;p&gt;Three details make this safe and unguessable:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The permutation is a six-round Feistel network&lt;/strong&gt; over 42 bits, using HMAC-SHA-256 from the Go standard library as the round function, with the key held in an encrypted parameter. Values that land outside the Base62 domain are cycle-walked (permuted again until they land inside). The mapping is a bijection, so two different integers can never produce the same code, and the inverse exists for anyone holding the key.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Seven Base62 characters&lt;/strong&gt; give 62^7, about 3.5 trillion codes. At 1.2 billion links a year the space lasts about 2,900 years. Base62 rather than Base64 because &lt;code&gt;+&lt;/code&gt; and &lt;code&gt;/&lt;/code&gt; are not safe in a URL without escaping.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A generated code is written with the same conditional put as a custom alias.&lt;/strong&gt; If a caller once chose the alias &lt;code&gt;aB3xK9c&lt;/code&gt; by hand, the generated code that happens to equal it fails its condition and the allocator takes the next integer. That retry is bounded to the handful of aliases that ever collide, not a search.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The raw integer also reserves 3 high bits for a region ID, so a second region could mint codes without a cross-region coordinator. The first release uses region 0.&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-keep-the-redirect-short&quot;&gt;Challenge 2: keep the redirect short&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What exactly happens inside a click?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The first design I sketched did the obvious thing: look the code up, increment a click counter on the same row, return the redirect. Under a burst, the counter increment makes the hottest row in the table also the most-written row in the table. That is the classic failure of this kind of system, and it is the one the reference literature warns about most loudly.&lt;/p&gt;
&lt;p&gt;So the redirect is split into a &lt;strong&gt;hot path&lt;/strong&gt; (what the click waits for) and a &lt;strong&gt;slow path&lt;/strong&gt; (what happens after the response is sent).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/redirect-hot-path-vs-slow-path.svg&quot; alt=&quot;Redirect hot path vs the click slow path&quot; title=&quot;Figure 3: The hot path is one Redis read, one DynamoDB read only on a miss, and one click item written after the 302. Click counting happens on the slow path, fed by the table&apos;s stream.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;On the hot path, &lt;code&gt;GET /{code}&lt;/code&gt; does at most three things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Read Redis&lt;/strong&gt; for &lt;code&gt;url:{code}&lt;/code&gt;. On a fresh active record, that is the whole lookup.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Read DynamoDB&lt;/strong&gt; with a consistent &lt;code&gt;GetItem&lt;/code&gt;, only on a miss or when the cached record is stale. The result populates Redis.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Write one click item&lt;/strong&gt; to a separate &lt;code&gt;Clicks&lt;/code&gt; table, after the 302 has been written, with a 500 ms budget. If the write fails, the click is logged and lost. The redirect is never delayed or changed by it.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The link item is deliberately never written on a click. An aggregation Lambda reads the click items from the table’s stream in batches and increments a separate stats table a few seconds later. Part 3 covers that path, and the four ways of moving clicks that were compared before settling on it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why 302 and not 301.&lt;/strong&gt; A 301 tells the browser the redirect is permanent, and browsers cache it indefinitely. That kills click counting, and it makes expiry, deletion and takedown impossible for anyone who has already clicked. A 302 brings the client back on almost every click. The cost of that round trip is paid by the cache tiers, not by weakening the redirect.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Caching a 302 anyway.&lt;/strong&gt; The redirect carries &lt;code&gt;Cache-Control: public, max-age=5&lt;/code&gt;. That looks like a contradiction, but it is not. A 302 tells the browser not to assume the destination is permanent. It does not forbid an intermediary from caching it for exactly as long as the header says. Five seconds at the edge absorbs a viral spike without every click reaching Lambda, and it bounds how long a deleted link can be served after takedown to five seconds. Not-found and error responses carry &lt;code&gt;no-store&lt;/code&gt;, so a custom alias created a second after a miss is visible at once.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-three-cache-tiers-and-why-redis-over-dax&quot;&gt;Challenge 3: three cache tiers, and why Redis over DAX&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not the managed cache that sits in front of DynamoDB?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;DynamoDB Accelerator (DAX) is the obvious cache for a DynamoDB-backed read path. It was rejected because the redirect needs more than a cached row. Part 2 explains the cache record in full, but the short version is:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Need&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;DAX&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Redis&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;An explicit “deleted” state that carries no destination&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No. DAX caches items; a deleted item is a miss, and a miss goes back to the table.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Yes. A tombstone record with its own lifetime.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Version comparison on write, so an old populate cannot overwrite a newer tombstone&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Yes, in one atomic Lua script.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A bounded stale window for use only when DynamoDB is failing&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Yes. &lt;code&gt;fresh_until&lt;/code&gt; and &lt;code&gt;stale_until&lt;/code&gt; are part of the record.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Provider neutrality&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;AWS only&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Any Redis. The same adapter runs against a local Redis in development.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;So the tiers are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Tier 1, CloudFront.&lt;/strong&gt; Under 5 ms. Caches a successful 302 for 5 seconds and nothing else. No &lt;code&gt;stale-while-revalidate&lt;/code&gt;, because that would extend takedown propagation past the 5-second window.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tier 2, ElastiCache for Redis.&lt;/strong&gt; Under 10 ms. Holds active records and deletion tombstones. Sized for the hot 20% of the daily working set, about 1 GB at the design targets. The Redis client has 150 ms dial, read and write timeouts and retries disabled, so a Redis failover degrades to a DynamoDB read instead of a hung invocation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tier 3, DynamoDB.&lt;/strong&gt; Only on a double miss or a revalidation. Reads are strongly consistent, so a newly created link is visible on its first click rather than after DynamoDB’s eventual-consistency window.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Unknown codes are cached nowhere. Negative caching was rejected because any valid alias can be created after an earlier miss, and a cached “missing” sentinel would hide it. A Bloom filter was rejected too: at 6 billion codes and a 1% false-positive rate it needs roughly a 7 GB bitset plus a correctness-sensitive update pipeline, to save reads that strict code validation and the edge rate limits already bound.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-the-edge&quot;&gt;Challenge 4: the edge&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why two edge providers, and how does nothing get around them?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The redirect endpoint is public and unauthenticated, so it needs a source rate control that costs less than the abuse it stops. The original design put an AWS WAF web ACL on the CloudFront distribution. At the design volume that is 10 billion requests evaluated a month, about $6,000 in WAF request charges alone. For a public shortener that is the wrong trade.&lt;/p&gt;
&lt;p&gt;The deployed design puts &lt;strong&gt;Cloudflare in front of CloudFront&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Cloudflare&lt;/strong&gt; holds the DNS zone, terminates TLS in Full (strict) mode against the ACM certificate on CloudFront, runs the firewall, and rate-limits &lt;code&gt;POST /api/v1/links&lt;/code&gt; per client IP. It also sets the real client IP in &lt;code&gt;CF-Connecting-IP&lt;/code&gt; on every request, which the origin can trust because Cloudflare overwrites any value the client sends.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;CloudFront&lt;/strong&gt; routes by path. &lt;code&gt;/api/*&lt;/code&gt; goes to API Gateway with caching disabled. &lt;code&gt;/app/*&lt;/code&gt; and the root path go to a private S3 bucket through Origin Access Control and serve the static single-page app. Everything else, which is any bare single-segment path, goes to the redirect origin with the 5-second cache policy. The page and the API share one hostname, so the browser never sends a CORS preflight.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The redirect origin is a Lambda Function URL, not API Gateway.&lt;/strong&gt; API Gateway would add about $1 per million requests on the read path, roughly $5,000 a month at 5 billion origin requests, for routing and usage plans that the redirect does not use. The Function URL costs nothing beyond the Lambda invocation. It uses IAM authorization, and CloudFront signs every origin request with Origin Access Control, so CloudFront is the only caller that can reach it.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A second edge layer creates a new hole: the &lt;code&gt;*.cloudfront.net&lt;/code&gt; hostname is reachable by anyone, and a request sent straight to it never passes Cloudflare’s firewall. Figure 4 shows how that hole is closed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/edge-lockdown.svg&quot; alt=&quot;Cloudflare stamps a secret header; a CloudFront function rejects requests without it&quot; title=&quot;Figure 4: Cloudflare adds X-Origin-Verify to every request it forwards. A CloudFront viewer-request function rejects anything without the right value with a 403, before any origin is contacted, and strips the header so no origin ever sees it.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;A Cloudflare Transform Rule stamps &lt;code&gt;X-Origin-Verify&lt;/code&gt; with a secret on every forwarded request. A CloudFront function runs on every viewer request, compares the header, returns &lt;code&gt;403&lt;/code&gt; with &lt;code&gt;no-store&lt;/code&gt; on a mismatch, and deletes the header before forwarding. The secret is generated by Terraform on the first apply and stored in the state. Both the rule and the function update in one plan, so rotating it is one apply and a few seconds of 403s while the function propagates.&lt;/p&gt;
&lt;p&gt;Two more edge details are worth knowing. CloudFront’s response headers policy sends a strict Content Security Policy as a header, because browsers ignore &lt;code&gt;frame-ancestors&lt;/code&gt; in a meta tag, and it strips the S3 encryption headers that would otherwise reveal the AWS account ID and KMS key ARN to every viewer. And Cloudflare’s bot protections are pinned off in Terraform, because the JavaScript detections inject an inline script that the site’s CSP blocks.&lt;/p&gt;
&lt;h2 id=&quot;challenge-5-compute-for-a-serverless-read-path&quot;&gt;Challenge 5: compute for a serverless read path&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why Lambda, and what does a VPC-attached function cost?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I compared three compute options for the redirect.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A fixed fleet behind a load balancer&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Predictable and fast, but it means paying for idle capacity all month for a service whose traffic arrives in spikes, plus the operations of a fleet: patching, scaling policies, and a load balancer with its own hourly charge.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Containers on Fargate&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Scales, but slower than Lambda to react to a viral spike, and the load balancer cost is the same.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Lambda (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Scales to a spike in seconds, costs nothing at idle, and the Go binary on arm64 starts in about 100 to 300 ms cold. The p99 target rules out cold starts during ramps, so the redirect function is built to run with provisioned concurrency, sized from observed concurrency (peak QPS times p50 duration, about 160 at the design targets).&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Reaching Redis puts the redirect function inside a VPC, in two private subnets across two Availability Zones. The write function stays outside the VPC, because its normal request path never touches Redis. Consequences:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;No NAT gateway and no interface endpoints.&lt;/strong&gt; No function calls the public internet. Every dependency the redirect function has outside the VPC is DynamoDB, reached through a gateway VPC endpoint, which has no hourly charge. That was not true of the first deployed version, which published clicks to Kinesis through an interface endpoint at about $7.30 per AZ-month. Part 3 explains the change.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One connection per execution environment.&lt;/strong&gt; The Redis and SDK clients are created once at cold start and reused across invocations. Provisioned concurrency keeps a warm pool of them.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Two roles, two functions.&lt;/strong&gt; The redirect function can read links, write click items and reach Redis. It cannot create or delete anything. The API function can create links and invoke cache invalidation. It cannot reach Redis directly or write clicks.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Every function is Go, compiled for &lt;code&gt;provided.al2023&lt;/code&gt; on arm64, at 128 MB. The redirect function has a 3-second timeout, and every dependency call inside it has a shorter budget: 150 ms for Redis, 1 second for the DynamoDB link read including the SDK’s three attempts, 500 ms for the click write. A hung dependency therefore leaves room to fall back or fail fast, never to time out the whole invocation.&lt;/p&gt;
&lt;h2 id=&quot;the-whole-architecture&quot;&gt;The whole architecture&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does it look like end to end?&lt;/strong&gt;&lt;/p&gt;
&lt;figure class=&quot;figure-wide&quot;&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/url-shortener/architecture.svg&quot; alt=&quot;URL shortener architecture on AWS: Cloudflare in front of CloudFront, API Gateway and an API Lambda for writes, a redirect Lambda in a VPC with ElastiCache for Redis, DynamoDB with a Clicks table and stream, an aggregation Lambda, an invalidation Lambda for takedowns, and GitHub Actions deploying through OIDC&quot; class=&quot;rounded-lg border border-border w-full h-auto&quot; decoding=&quot;async&quot;/&gt;&lt;figcaption class=&quot;figure-caption font-mono text-xs text-muted-foreground text-center mt-2&quot;&gt;&lt;p&gt;Figure 5: The full architecture as deployed. Cloudflare and CloudFront at the edge; a redirect Lambda in private subnets with Redis and VPC endpoints; API Gateway and an API Lambda for writes; a DynamoDB Clicks table, its stream and an aggregation Lambda on the slow path. &lt;a href=&quot;https://www.sumonselim.com/images/articles/url-shortener/architecture.svg&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Open full-size diagram&lt;/a&gt;&lt;/p&gt;&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;A click moves through it like this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The browser resolves &lt;code&gt;mol.la&lt;/code&gt; to &lt;strong&gt;Cloudflare&lt;/strong&gt;, which terminates TLS, runs the firewall, stamps the origin secret, and forwards to &lt;strong&gt;CloudFront&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;CloudFront function&lt;/strong&gt; checks the secret and strips it. On a cache hit, CloudFront answers the 302 itself.&lt;/li&gt;
&lt;li&gt;On a miss, CloudFront calls the &lt;strong&gt;redirect Lambda&lt;/strong&gt; through its Function URL, signed with Origin Access Control.&lt;/li&gt;
&lt;li&gt;The function reads &lt;strong&gt;Redis&lt;/strong&gt;. A fresh active record answers the click.&lt;/li&gt;
&lt;li&gt;On a Redis miss or a stale record, it reads &lt;strong&gt;DynamoDB&lt;/strong&gt; through the gateway endpoint and populates Redis.&lt;/li&gt;
&lt;li&gt;After writing the 302, it puts one item into the &lt;strong&gt;Clicks&lt;/strong&gt; table through the same gateway endpoint.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A link is created like this:&lt;/p&gt;
&lt;ol start=&quot;7&quot;&gt;
&lt;li&gt;&lt;code&gt;POST /api/v1/links&lt;/code&gt; goes through CloudFront to &lt;strong&gt;API Gateway&lt;/strong&gt; and the &lt;strong&gt;API Lambda&lt;/strong&gt;, outside the VPC.&lt;/li&gt;
&lt;li&gt;The function validates the request, leases an integer from the &lt;strong&gt;Counters&lt;/strong&gt; item if no alias was given, and writes the &lt;strong&gt;Links&lt;/strong&gt; item and the optional &lt;strong&gt;Idempotency&lt;/strong&gt; item in one DynamoDB transaction.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And the slow path:&lt;/p&gt;
&lt;ol start=&quot;9&quot;&gt;
&lt;li&gt;An &lt;strong&gt;aggregation Lambda&lt;/strong&gt; consumes the Clicks table’s &lt;strong&gt;DynamoDB Stream&lt;/strong&gt; in batches and increments &lt;strong&gt;LinkStats&lt;/strong&gt; once per code per batch. Raw click items expire from the table after 90 days.&lt;/li&gt;
&lt;li&gt;An &lt;strong&gt;operator takedown&lt;/strong&gt; soft-deletes the item and invokes the &lt;strong&gt;invalidation Lambda&lt;/strong&gt;, which writes a versioned tombstone to Redis. The cached 302 at the edge ages out on its own within 5 seconds.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;GitHub Actions&lt;/strong&gt; deploys by assuming an IAM role through OIDC, on a version tag only. There are no long-lived AWS keys anywhere in the pipeline.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Alarms&lt;/strong&gt; cover the things that should wake someone up: CloudFront 5xx rate and origin p99 latency against the 50 ms target, API Gateway 5xx and p99 latency, Lambda errors and throttles on every function, Redis engine CPU and evictions, DynamoDB throttles on every table, the aggregation function’s iterator age, its dead-letter queue, and any failed cache invalidation, which is owned by security rather than platform because a missing tombstone means a taken-down link is still live. Alarms go to an SNS topic and from there to email. A budget with a monthly limit sits next to them.&lt;/p&gt;
&lt;h2 id=&quot;what-it-would-cost-at-the-target&quot;&gt;What it would cost at the target&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does a 100:1 read-heavy service cost at 10 billion reads a month?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;These are list-price arithmetic at the design targets, not a bill. The deployed system runs at a tiny fraction of this.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Line item&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Basis&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Approx. per month&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;CloudFront&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;10B requests, about 5 TB egress&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$7,900&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Lambda&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~5B redirect invocations plus 100M writes, 128 MB, arm64&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$1,100&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Lambda provisioned concurrency&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~160 concurrent, redirect function only&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$450&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;ElastiCache for Redis&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;cache.r7g.large, primary plus replica&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$400&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;API Gateway (write path only)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;100M requests&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$350&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;DynamoDB, links&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;100M writes plus ~250M on-demand reads&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$200&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;DynamoDB, clicks&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;5B on-demand writes, one per redirect that reaches Lambda&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$6,250&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;CloudWatch, Function URL, gateway endpoint&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;~$100&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cloudflare&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Free plan&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;$0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;~$16,750&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;CloudFront request pricing dominates because every redirect is a viewer request whether it hits or misses. Two lines moved since the original design. AWS WAF at $0.60 per million requests, about $6,000, disappeared when the firewall moved to Cloudflare. And the click line grew from about $250 for Kinesis to about $6,250 for one DynamoDB write per click, because the deployed system chose the pipeline with no fixed monthly cost over the one with the lowest cost per event. At hobby scale that is the right trade by a wide margin, and Part 3 shows the arithmetic in both directions.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 2 looks inside the cache. It covers what a cache record holds and why it has three timestamps, how a versioned tombstone survives a late writer, when a stale record may be served and when it must not, and how a takedown propagates through DynamoDB, Redis and the edge in that order.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Flash-Sale Seat Reservation System in AWS (Part 3): Holds, Payments, and the Slow Path</title><link>https://www.sumonselim.com/seat-reservation-part3-holds-payments-and-the-slow-path/</link><guid isPermaLink="true">https://www.sumonselim.com/seat-reservation-part3-holds-payments-and-the-slow-path/</guid><description>An admitted seat is only half a booking. Part 3 follows it through payment: a 10-minute hold, redirect signals that anyone can fake, one reconciler that makes every release decision, a payment gateway token shared across the fleet, and an SQS FIFO to DynamoDB pipeline that never makes a user wait.</description><pubDate>Thu, 24 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; After admission, a seat is &lt;strong&gt;held for 10 minutes&lt;/strong&gt; while the candidate pays. The central rule for payments is one-sided: &lt;strong&gt;many paths can confirm a booking, but only one can release a seat.&lt;/strong&gt; Three paths can mark a booking &lt;code&gt;PAID&lt;/code&gt;: the browser callback, the gateway’s signed webhook, and a background reconciler.&lt;/p&gt;
&lt;p&gt;The reconciler asks the gateway for the payment status. Each of the three paths checks with the gateway, and each is idempotent (safe to run more than once). Only the reconciler releases seats. It does so in two cases: the gateway reports that the payment failed or was cancelled, or the hold deadline has passed and the gateway has not reported the payment as complete. If the gateway cannot answer, the hold is extended. A seat is never released when the outcome is uncertain. The “cancel” or “failed” status in the redirect itself is ignored, because anyone can fake it. Durable writes happen outside the request path.&lt;/p&gt;
&lt;p&gt;An &lt;strong&gt;SQS FIFO&lt;/strong&gt; queue feeds a worker that writes to &lt;strong&gt;DynamoDB&lt;/strong&gt; with conditional puts (writes that succeed only if a condition holds). The worker never touches the seat counters. &lt;strong&gt;DynamoDB TTL&lt;/strong&gt; and a &lt;strong&gt;Lambda driven by DynamoDB Streams&lt;/strong&gt; are only a safety net for expiry. On launch day, 31.6K holds were created for 20.7K seats, and the queue never held a message older than 4 seconds. The post ends with how we tested the design, in layers and many times over, and what that testing found before launch.&lt;/p&gt;
&lt;h2 id=&quot;the-hold-lifecycle&quot;&gt;The hold lifecycle&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What states does a booking go through?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/hold-states.svg&quot; alt=&quot;Hold lifecycle: admitted, HELD, PAID, RELEASED&quot; title=&quot;Figure 1: The hold lifecycle. A held seat ends in exactly one of two places: PAID, or RELEASED back into the pool.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;A booking has three durable (stored) states:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;HELD:&lt;/strong&gt; the seat is counted and a payment exists. The record carries a deadline 10 minutes in the future.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;PAID:&lt;/strong&gt; the gateway has confirmed the payment. The seat is permanent, and a confirmation email is sent.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;RELEASED:&lt;/strong&gt; the hold ended without payment. The seat is back in the pool, the record is deleted, and the candidate can try again.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If payment creation or the enqueue fails, the booking never reaches &lt;code&gt;HELD&lt;/code&gt;. The API undoes the admission before it responds.&lt;/p&gt;
&lt;p&gt;The 10-minute hold is a trade-off in both directions. A shorter hold returns unpaid seats sooner, but it punishes anyone who needs some time to approve a payment on their phone. A longer hold keeps seats locked by people who have left and will not pay. Ten minutes was comfortably longer than the gateway’s checkout took in testing, and it kept resale fast. On launch day, 31.6K holds were created for 20.7K seats. About a third of the holds expired or failed, and their seats were sold again within the hour.&lt;/p&gt;
&lt;h2 id=&quot;challenge-1-payment-signals-you-cannot-trust&quot;&gt;Challenge 1: payment signals you cannot trust&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why can’t the payment redirect decide the outcome?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;After paying, the gateway redirects the browser to &lt;code&gt;/payment/callback?paymentID=...&amp;amp;status=success|failure|cancel&lt;/code&gt;. The obvious design is to trust that status: mark the booking paid on &lt;code&gt;success&lt;/code&gt;, and release it on &lt;code&gt;cancel&lt;/code&gt;. That design is broken in both directions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;An attacker controls the query string.&lt;/strong&gt; Anyone can type &lt;code&gt;status=cancel&lt;/code&gt; for a payment ID they have seen. That would free a seat that is still being paid for, or one that is already paid.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Redirects can be old or repeated.&lt;/strong&gt; The browser’s Back button, a second tab or a retried request can all deliver the same redirect again, sometimes after the booking has already changed state.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A redirect may never arrive.&lt;/strong&gt; The user closes the tab, their phone loses signal, or the redirect times out. The payment completed, but nobody told us.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We considered three designs.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Problem&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Trust the redirect status&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Easy to fake, easy to repeat, and easy to lose, as above.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Confirm every redirect with the gateway’s query API before acting&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Better, but the gateway’s query API only reports a definite status for a &lt;em&gt;completed&lt;/em&gt; payment. So a cancel cannot be confirmed one way or the other. Every fake redirect would also cost us a call to a rate-limited API.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Confirm-only redirects, one releaser (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A redirect can help to confirm a payment. It can never release a seat.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/confirm-many-release-one.svg&quot; alt=&quot;Many paths can confirm, one path can release&quot; title=&quot;Figure 2: Three independent paths can move a booking to PAID. Each one checks with the gateway and is idempotent. Only the reconciler releases seats (the TTL safety net reuses the same guarded rollback). A redirect that says cancel changes nothing.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The three confirm paths are:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Browser callback.&lt;/strong&gt; The API accepts the callback only for a payment ID that it issued, and only with the per-payment signature that the gateway returned when the payment was created. It also refuses to charge once the hold deadline has passed. Otherwise we could take money for a seat that the reconciler has already released. It then calls the gateway’s execute API under a lock with an owner token (&lt;code&gt;SET NX&lt;/code&gt; with a random token, and only the owner of that token can release the lock). So the payment is executed at most once, even if the redirect arrives twice. If the execute call times out, the API queries the payment once, as the gateway’s own integration guide requires. It does that only to recover a completed payment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gateway webhook.&lt;/strong&gt; The gateway also sends a signed notification (standard AWS SNS HTTP delivery) when a payment completes. The handler verifies the SNS signature and looks up the booking by invoice number. It still queries the gateway and compares the transaction ID before it marks the booking paid. It always answers &lt;code&gt;200&lt;/code&gt; to a correctly signed message, even when it leaves the decision to the reconciler. That way SNS never builds up a flood of redeliveries.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reconciler query.&lt;/strong&gt; This path is covered in Challenge 2.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Every confirm path ends in the same conditional update: &lt;code&gt;HELD → PAID&lt;/code&gt;, which succeeds only if the record is still &lt;code&gt;HELD&lt;/code&gt; with the same payment ID. Whichever path gets there first wins, and the others do nothing. Confirmation emails are sent after that update succeeds, never before.&lt;/p&gt;
&lt;p&gt;One race condition shaped the design early. &lt;strong&gt;A fast payer can finish before the worker has written the record.&lt;/strong&gt; The hold is written to DynamoDB asynchronously, so a user who pays within seconds can come back before any &lt;code&gt;HELD&lt;/code&gt; record exists. So at admission, the API also stores a copy of the booking record in Redis, keyed by payment ID, with a TTL slightly longer than the hold. If the callback finds no record in the database, it writes the &lt;code&gt;PAID&lt;/code&gt; record from that copy.&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-exactly-one-path-releases-a-seat&quot;&gt;Challenge 2: exactly one path releases a seat&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Who decides that a hold has expired?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;reconciler&lt;/strong&gt; is a background loop inside the API fleet. A Redis lock with an owner token makes sure that exactly one instance runs it at a time. Every 20 seconds, that instance does a sweep:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/reconciler-sweep.svg&quot; alt=&quot;The reconciler sweep&quot; title=&quot;Figure 3: One sweep. The gateway&apos;s answer decides the action. A query with no answer extends the hold instead of releasing it.&quot;/&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Clean up stale pending admissions&lt;/strong&gt; from Part 2: seats whose request died before it reached the database.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Find &lt;code&gt;HELD&lt;/code&gt; records&lt;/strong&gt; within 6 minutes of their deadline, or past it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Handle the most overdue records first,&lt;/strong&gt; 8 at a time, within a 45-second time budget, so the sweep finishes before the next one starts. When many holds expire at the same time, the records that are closest to hurting a user go first.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ask the gateway for the status&lt;/strong&gt; of each record:
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Completed:&lt;/em&gt; mark it &lt;code&gt;PAID&lt;/code&gt; and send the email. This recovers every user whose redirect never arrived.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Failed or cancelled, or not completed after the deadline:&lt;/em&gt; release the seat, using the payment-guarded undo from Part 2, and delete the record.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Still pending before the deadline:&lt;/em&gt; leave it alone. The user may still be paying.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;The query fails three times:&lt;/em&gt; extend the hold by 10 minutes, up to three times, then alert a human. &lt;strong&gt;We never release a seat only because we could not get an answer&lt;/strong&gt;, because the payment may have succeeded.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This is the only status query traffic we send to the gateway on the release side. Keeping it in one rate-limited loop keeps our use of the gateway’s rate limits predictable.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;DynamoDB TTL is not the main timer.&lt;/strong&gt; TTL (time to live) is set on the record’s deadline attribute. But AWS deletes expired items on a best-effort schedule, and the delay can be long. During a sellout, that delay would mean seats that nobody could buy. So the reconciler expires holds itself, on time. TTL, a DynamoDB Stream, and an &lt;strong&gt;expiry Lambda&lt;/strong&gt; form the safety net. The Lambda acts only on deletions made by the TTL service itself (the reconciler’s own deletes are ignored), and only if the deleted record was still &lt;code&gt;HELD&lt;/code&gt;. It then runs the same payment-guarded undo. If the reconciler already released that seat, the Lambda’s undo does nothing.&lt;/p&gt;
&lt;p&gt;One bug from QA is worth sharing. Paid records must &lt;strong&gt;remove&lt;/strong&gt; the TTL attribute. One of our paths wrote &lt;code&gt;PAID&lt;/code&gt; records with the hold’s TTL still set. DynamoDB would have deleted those confirmed bookings 10 minutes later.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-one-token-a-rate-limited-gateway&quot;&gt;Challenge 3: one token, a rate-limited gateway&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you share an auth token across a fleet?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The gateway’s API calls need a short-lived token. The token &lt;em&gt;grant&lt;/em&gt; endpoint (the endpoint that issues a new token) is rate-limited to a couple of calls per hour. If every instance fetched its own token, a deploy or a restart would use up the whole allowance in seconds and lock the entire fleet out of payments.&lt;/p&gt;
&lt;p&gt;So the token lives in Redis, shared by the whole fleet:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;One refresher at a time.&lt;/strong&gt; An instance that finds no valid token takes a &lt;code&gt;SET NX&lt;/code&gt; lock with a 45-second TTL. Only the lock holder calls the grant endpoint. All other instances wait for the new token to appear, while still respecting their own request deadline.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Refresh early.&lt;/strong&gt; The token is cached until a few minutes before it expires, so a request never uses a token at the moment it expires.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The grant call outlives the request that started it.&lt;/strong&gt; The grant call runs on its own 30-second deadline, separate from the request that triggered it. A user’s 8-second timeout cannot stop a grant halfway and force another one.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Wait after a failure.&lt;/strong&gt; A failed grant keeps the lock for 60 seconds instead of releasing it. So the fleet does not retry in a loop and use up the hourly allowance.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-4-durability-off-the-hot-path&quot;&gt;Challenge 4: durability off the hot path&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How does the database keep up without slowing down bookings?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/hot-path-vs-slow-path.svg&quot; alt=&quot;Hot path vs slow path&quot; title=&quot;Figure 4: The slow path. SQS FIFO absorbs the burst. The worker writes to DynamoDB at its own pace. Streams feed the expiry safety net and the back-office sync.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;We considered four ways to store each booking durably.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Write to DynamoDB inside the request&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Adds a network write to every admission. A throttle or a slow partition at T+0 (the moment registration opens) becomes latency the user sees, or an admission that must be undone.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Kinesis Data Streams&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Built for ordered, high-volume streams, but shards need capacity planning, and you must build per-record retries and dead-letter handling yourself.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;SQS standard&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Scales without limit, but it can deliver messages twice and out of order. The worker would have to handle all of that complexity.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;SQS FIFO, high-throughput mode (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Removes duplicates on send and keeps order within each group. With a large number of message groups it has plenty of throughput. The dead-letter queue is built in.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The details that matter:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Message group = the first 4 hex characters of the candidate hash.&lt;/strong&gt; That gives 65,536 groups. The groups spread the load, and ordering within a group keeps one candidate’s messages in sequence. High-throughput FIFO mode (&lt;code&gt;DeduplicationScope=messageGroup&lt;/code&gt;, &lt;code&gt;FifoThroughputLimit=perMessageGroupId&lt;/code&gt;) removes the old per-queue throughput limit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deduplication ID = the candidate hash plus the request timestamp.&lt;/strong&gt; A retried send is treated as the same message, but a real re-booking is not.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visibility timeout of 60 seconds and 5 receives&lt;/strong&gt; before a message moves to the dead-letter queue. That queue has an alarm that fires on even one message.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The worker on each instance long-polls the queue (it keeps a receive request open and waits for messages instead of asking repeatedly). It writes each record with a &lt;strong&gt;conditional put&lt;/strong&gt; (the write succeeds only if the record does not exist yet). When the condition fails, the worker has to find out why, and a guess is not good enough:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/worker-conflict-classification.svg&quot; alt=&quot;How the worker classifies a conditional-write conflict&quot; title=&quot;Figure 5: A conflict is classified with a strongly consistent read. Only a stale record from a released attempt is replaced. Anything unclear stays in the queue.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;PAID&lt;/code&gt;:&lt;/strong&gt; the callback got there first. Skip the message.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;HELD&lt;/code&gt; with the same payment ID:&lt;/strong&gt; a repeated delivery of the same message. Delete the message.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;HELD&lt;/code&gt; with a different payment ID:&lt;/strong&gt; a stale record from an earlier attempt that was released, after which the candidate booked again. Replace it, on the condition that the old payment ID is still there. We found this case in QA, and it is why the payment ID is part of the check. Without it, the stale record hid the new payment, and the new booking could never be marked paid.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The read failed:&lt;/strong&gt; leave the message unacknowledged and let SQS deliver it again.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;The worker never touches the seat counters.&lt;/strong&gt; Seats belong to Redis and the admission script. Records belong to the worker. When both could decrease a counter, a redelivered message could free a seat that someone still held. Giving each piece of state exactly one owner made that bug impossible.&lt;/p&gt;
&lt;p&gt;DynamoDB itself uses on-demand capacity with one table. The partition key is the candidate hash. A GSI (global secondary index) on payment ID serves the callback’s lookup. Point-in-time recovery and deletion protection are both on. In the first five minutes the worker wrote about 37,000 write units’ worth of records. The table absorbed that without a single throttle, because the queue had already smoothed out the spike.&lt;/p&gt;
&lt;p&gt;Two more stream consumers connect to the table, both with failure handling built in:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The sync Lambda&lt;/strong&gt; copies every &lt;code&gt;PAID&lt;/code&gt; record into a relational database for the back-office app, using upserts (insert or update in one statement).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Both Lambdas&lt;/strong&gt; use &lt;code&gt;ReportBatchItemFailures&lt;/code&gt;, split a batch in half on error, limit the record age, and send anything they give up on to an SQS on-failure destination. Without this, a dropped stream batch would mean a lost release or a missing paid booking.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/launch-holds-per-5-min.svg&quot; alt=&quot;Holds enqueued per 5 minutes on launch day&quot; title=&quot;Figure 6: Holds enqueued per 5 minutes. 15.3K in the first five minutes. The queue&apos;s oldest message was never older than 4 seconds.&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;the-live-status-document&quot;&gt;The live status document&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do thousands of writers keep one JSON file correct?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The availability counts on the page come from &lt;code&gt;status.json&lt;/code&gt; in S3 (see Part 1). The API and the expiry Lambda both write it. Our first version read the file, changed one field and wrote it back. With several writers at the same time, two writes overlapped, and an old write reopened a level that had just filled.&lt;/p&gt;
&lt;p&gt;The rule that fixed it: &lt;strong&gt;every writer builds the whole document from Redis&lt;/strong&gt;, where the counters and the open/closed flags live, and overwrites the file. Writers that run at the same time then arrive at the same result instead of competing over a copy. Two latches (one-time flags) keep the writes cheap:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A 2-second &lt;code&gt;SET NX&lt;/code&gt; throttle turns a burst of admissions into a single S3 write.&lt;/li&gt;
&lt;li&gt;The level-full and closed transitions each publish exactly once.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;A release clears those latches, so a freed seat reopens the level on the page.&lt;/p&gt;
&lt;h2 id=&quot;test-find-fix-repeat&quot;&gt;Test, find, fix, repeat&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Was this design right the first time?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;No. The design in this series is the result of about four months of testing, finding problems, fixing them and testing again. That loop is one of the main reasons launch day was quiet. Every change went through several layers of testing, and each layer answered a different question.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/testing-layers.svg&quot; alt=&quot;The layers of testing and the fix loop&quot; title=&quot;Figure 7: The testing layers, from fast and cheap at the top to slow and close to real at the bottom. A problem found in any layer was fixed, covered by a new test where possible, and then every layer was run again.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Unit tests&lt;/strong&gt; for every package: each branch of the admission script, the gateway client, the webhook signature check and the status document.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An end-to-end suite on a local copy of the stack&lt;/strong&gt;, with a mock payment gateway that can be told to fail or cancel. It runs a booking all the way to &lt;code&gt;PAID&lt;/code&gt;. It also runs the failure cases: a gateway error, a duplicate booking, a new booking after a released hold, a forged callback, a callback that arrives twice, and a payment that completes before the worker has written the record.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Full-rate load tests&lt;/strong&gt; on a stack the same size as production. Each run used 40,000 test candidates, sent 2,000 bookings per second for 25 seconds, and then sent a slower stream of late arrivals and retries. A run passed only if admissions stopped exactly at the cap, DynamoDB reported no throttling, and the counters matched the database afterwards.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The payment gateway’s sandbox&lt;/strong&gt;, for real payment flows: pay, cancel, let a hold expire, and book again.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reviews and audits&lt;/strong&gt; of the design, the code and the infrastructure. They looked for signals an attacker could fake, rate limits we could use up, and missing permissions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Launch rehearsals.&lt;/strong&gt; We ran the same reset, load-candidates and open steps that we would use on the day, more than a hundred times, from the same pipeline.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Each layer found problems that the others missed. A few examples:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Load tests:&lt;/strong&gt; the Redis client’s default connection pool was sized for normal traffic, not for a burst. We raised it to 300 connections per instance and ran the test again.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sandbox:&lt;/strong&gt; the counters drifted after a user cancelled and then booked again. The worker found the old record, treated the new booking as a duplicate, and decremented a counter. This is why the worker never touches the counters, and why it classifies every conflict with a consistent read (Challenge 4).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Testing the undo paths:&lt;/strong&gt; a rollback that ran twice pushed a level counter below zero. This is why every undo checks and acts in one atomic step (&lt;a href=&quot;https://www.sumonselim.com/seat-reservation-part2-never-sell-a-seat-twice&quot;&gt;Part 2&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reviewing paid records:&lt;/strong&gt; a paid record could still carry the hold’s TTL, so DynamoDB would have deleted a paid booking about ten minutes later. A paid record now has no TTL.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Security review:&lt;/strong&gt; the cancel status in the redirect has no signature, so anyone can fake it. Checking each one with the gateway would also use up the gateway’s token limit. This is why a redirect can never release a seat (Challenge 1).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A week before launch:&lt;/strong&gt; two concurrent writers could leave the status page showing a full level as open. The writers now run in a fixed order, and the page also checks the counts, so a full level can never look open.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;None of these problems is unusual. Most of them only show up under a specific timing, order of events or load, and the rest only show up when someone looks for them on purpose. The only reliable way to find them before users do is to test at every layer, many times, and to test again after every fix.&lt;/p&gt;
&lt;h2 id=&quot;lessons&quot;&gt;Lessons&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What would I tell someone building this next?&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Decide the one fact everyone competes for in one atomic step, and keep it off the database.&lt;/strong&gt; Everything else in the system can be eventually consistent if that one decision is exact.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Make the request path as short as possible.&lt;/strong&gt; Admit, create the payment, enqueue, and respond. Every durable write that can happen after the response should happen after the response.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Give every piece of state exactly one owner.&lt;/strong&gt; Redis owns seats, the worker owns records, and the reconciler owns releases. Most of our pre-launch bugs came from two components writing the same state.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Treat every external signal as a hint.&lt;/strong&gt; Redirects, webhooks and query results can be faked, delayed, duplicated or missing. Confirm with the source, make every state change conditional, and let exactly one path take the action that cannot be undone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Never release when you are not sure.&lt;/strong&gt; If you cannot tell whether someone paid, extend the hold and alert a human. Selling a paid seat twice is worse than holding an unpaid one a little longer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Idempotency must live in the same atomic step as the action.&lt;/strong&gt; A check followed by a separate action is a race, and under a burst every race is lost sooner or later.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Add capacity before a sudden jump in traffic, and load-test with a mock of every external dependency.&lt;/strong&gt; The mock gateway let us practise the full booking path at full rate as often as we wanted.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Plan as much time for testing as for building.&lt;/strong&gt; Test in layers, from unit tests to full-rate load tests and launch rehearsals. When you find a problem, fix it, add a test for it, and run every layer again. Most of what makes this design correct was learned that way.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The result was the launch day in &lt;a href=&quot;https://www.sumonselim.com/seat-reservation-part1-architecture-for-a-flash-sale&quot;&gt;Part 1&lt;/a&gt;: 20,700 seats sold, 99.99% of requests served without a server error, and zero double bookings.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Flash-Sale Seat Reservation System in AWS (Part 2): Never Sell a Seat Twice</title><link>https://www.sumonselim.com/seat-reservation-part2-never-sell-a-seat-twice/</link><guid isPermaLink="true">https://www.sumonselim.com/seat-reservation-part2-never-sell-a-seat-twice/</guid><description>The whole promise of the system depends on one Redis Lua script. Part 2 explains what it checks and in what order, why Lua won over MULTI/WATCH and distributed locks, and the four ways an in-memory counter can still go wrong: double rollbacks, lost replies, crashed requests, and a failover that loses the last writes.</description><pubDate>Tue, 22 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Every booking goes through one Redis Lua script. The script checks, in order, whether the candidate is already admitted, whether their level is full, and whether any seat is left overall. Then it counts the seat and marks the candidate. All of this happens as one atomic step (nothing else can run in between). Lua won over &lt;code&gt;MULTI/WATCH&lt;/code&gt; (too many retries when many requests compete) and distributed locks (extra round trips while holding the lock). An in-memory counter can still be wrong in four ways. Each needed its own fix:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Double rollbacks:&lt;/strong&gt; the undo step has a guard, so running it twice does nothing the second time.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lost replies:&lt;/strong&gt; every call carries a nonce (a random value that identifies one request), so a retried call gets its original slot back.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Crashed requests:&lt;/strong&gt; a list of pending admissions, plus a cleanup job, returns seats that never reached the database.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Failover:&lt;/strong&gt; a booking counts only after the Redis replica confirms it has the write (&lt;code&gt;WAIT 1 200&lt;/code&gt;). Otherwise the booking is undone and the client retries.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;the-invariants&quot;&gt;The invariants&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What exactly does “never sell a seat twice” mean?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Before writing any code, we wrote down three invariants (rules that must always be true). Everything in this post exists to keep them true.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Caps hold.&lt;/strong&gt; The number of admitted seats per level never exceeds that level’s cap, and the total never exceeds the global cap.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One live booking per candidate.&lt;/strong&gt; A candidate code is linked to at most one seat that is held or paid.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No leaks.&lt;/strong&gt; Every admitted seat becomes either paid or released in the end. No seat stays counted with nobody holding it.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Invariants 1 and 2 are what “zero double bookings” means. Invariant 3 stops the event from ending with unsold seats that the system forgot about.&lt;/p&gt;
&lt;h2 id=&quot;the-state&quot;&gt;The state&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What lives in Redis?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Key&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Type&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;booking:open&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;string&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The admin’s open/close switch&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;candidates:valid&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;set&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Allowlist of eligible candidate codes, loaded before opening&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;candidate:email:&amp;lt;code&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;string&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The email on file for each code&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;adm:seen&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;set&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Candidate codes that currently hold a seat&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;adm:total&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;integer&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Seats admitted overall&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;adm:level:&amp;lt;L&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;integer&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Seats admitted per level&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;adm:pending&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;hash&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;code → nonce, level, time, slot&lt;/code&gt; for admissions not yet safely in the database&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;hold:*&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;strings with a TTL (they expire on their own)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Per-payment stashes (temporary copies): the booking record, the payment URL, and the execute and rollback guards&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Two configuration choices matter more than they seem to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;maxmemory-policy noeviction&lt;/code&gt;.&lt;/strong&gt; When memory runs low, Redis must refuse writes with an error. It must never silently delete &lt;code&gt;adm:seen&lt;/code&gt; to free space. Losing that set would allow duplicates. A write error, on the other hand, simply becomes a 503 that the client can retry.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Normalised identifiers.&lt;/strong&gt; Candidate codes have their surrounding spaces removed and are converted to uppercase before any lookup. Otherwise the counter would treat &lt;code&gt;ab123&lt;/code&gt; and &lt;code&gt;AB123 &lt;/code&gt; as two different people. A SHA-256 hash of the normalised code is the database key. Its first characters become the queue message group and the payment’s invoice number.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;gates-then-the-script&quot;&gt;Gates, then the script&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why check some things outside the script?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/admission-flow.svg&quot; alt=&quot;Admission flow: gates, the atomic script, and the replica acknowledgement&quot; title=&quot;Figure 1: The admission flow. The gates are simple reads. The script is one atomic call. The replica acknowledgement decides whether the admission counts.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The gates are simple read checks. They reject most invalid traffic before any write happens:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Is booking open?&lt;/strong&gt; If not, &lt;code&gt;503 closed&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Is the code on the allowlist?&lt;/strong&gt; If not, &lt;code&gt;400 invalid_code&lt;/code&gt;. The allowlist is loaded into Redis from the back-office database before opening. There is deliberately &lt;strong&gt;no fallback to the database&lt;/strong&gt; while the system runs. A code that is missing from the allowlist must not turn into a database query at 50,000 requests a minute.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Does the email match the code?&lt;/strong&gt; If not, &lt;code&gt;400 email_mismatch&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A hidden honeypot field is checked before all of these. (A honeypot is a form field that real users never see, so only bots fill it in.) A form that fills it in gets a fake success response that looks real, with no admission and no log entry.&lt;/p&gt;
&lt;p&gt;The gates can live outside the script because their values change only when an operator changes them, before the event. The checks that compete with each other at the moment of booking are all inside the script:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;lua&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- KEYS: adm:seen, adm:total, adm:pending&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- ARGV: code, max_total, level, level_cap, nonce, now_ms&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; code, level, nonce &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;5&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;]&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; level_key &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;#39;adm:level:&amp;#39; &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; level&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- 1. Already admitted? A retry of the same request gets its slot back.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;SISMEMBER&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], code) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 1&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; then&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; p &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;HGET&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], code)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; p &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; n, lvl, _, slot &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; string.match&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(p, &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;^([^|]*)|([^|]*)|([^|]*)|([^|]*)$&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; n &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; nonce &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(slot), lvl} &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}                                  &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- duplicate&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- 2. Level full?&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; cap &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;4&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;])&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; cap &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 0&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; and&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;GET&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, level_key) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 0&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; cap &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, level}                               &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- level full&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- 3. Any seat left overall?&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;GET&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;]) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;or&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 0&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;gt;=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; tonumber&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;]) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;then&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;  return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;-&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}                                  &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- closed&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;end&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- 4. Admit: count, mark, and record as pending.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;local&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; slot &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;INCR&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;])&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;INCR&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, level_key)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;SADD&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], code)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;HSET&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], code, nonce &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;#39;|&amp;#39; &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; level &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;#39;|&amp;#39; &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;6&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;] &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;#39;|&amp;#39; &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; slot)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {slot, level}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The order matters. The duplicate check comes first, so a candidate who already has a seat is told so, even after their level fills up. The level check comes before the global check, so the user learns the most specific reason. Only the last branch writes anything. A rejection therefore costs a few reads on one thread.&lt;/p&gt;
&lt;p&gt;The API loads the script once with &lt;code&gt;SCRIPT LOAD&lt;/code&gt; and calls it with &lt;code&gt;EVALSHA&lt;/code&gt;. After a restart or failover, the new primary has an empty script cache and answers &lt;code&gt;NOSCRIPT&lt;/code&gt;. The client reloads the script and retries once.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why not the other atomic building blocks in Redis?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Problem under a flash sale&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;INCR&lt;/code&gt;, then check, then &lt;code&gt;DECR&lt;/code&gt; if the counter went too far&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The counter briefly goes above the cap, and readers can see that. The duplicate check is a separate step, and another request can run between the steps, so two requests for the same candidate can both pass.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;MULTI/WATCH&lt;/code&gt; (optimistic transactions)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every booking at the same level watches the same key. In the opening second, nearly all transactions abort and retry. That creates a storm of retries on the busiest key.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Distributed lock (for example Redlock) around a read, change, write sequence&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;At least two extra round trips while holding the lock, and a lock service that is one more thing that can fail.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Lua script (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Runs from start to finish on the Redis thread. There is no lock to hold across the network and no retry loop.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Two more design details keep the rest of the system simple:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;“Level full” is published once.&lt;/strong&gt; When a level fills, a &lt;code&gt;SETNX&lt;/code&gt; latch (a key that only the first writer can set) makes exactly one API instance rewrite &lt;code&gt;status.json&lt;/code&gt;. Thousands of requests cannot compete to publish the same change.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A duplicate can continue.&lt;/strong&gt; Suppose a candidate’s booking is still &lt;code&gt;HELD&lt;/code&gt; and they submit again, perhaps because their first request timed out in the browser. The &lt;code&gt;409&lt;/code&gt; response then carries their existing payment URL. The URL is read from a Redis stash (never from the database), and the page redirects them straight to payment. Without this, a user whose first response was lost could not reach the seat they already hold.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;failure-mode-1-undo-that-runs-twice&quot;&gt;Failure mode 1: undo that runs twice&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What happens when rollback runs twice?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A seat must be given back when a booking fails: the payment could not be created, the enqueue failed, or the hold expired without payment. Several paths can trigger that release. Early in load testing, two of them sometimes ran for the same booking, and the counters &lt;strong&gt;went negative&lt;/strong&gt;. The undo step decreased the counters every time it ran, even though removing the candidate from the set only had an effect the first time.&lt;/p&gt;
&lt;p&gt;The fix was to make undo a script that only acts if the candidate is still admitted:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;lua&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;SREM&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;]) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 0&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; then&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; return&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 0&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; end&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;  -- already undone&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;DECR&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;])                                     &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- total&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;DECR&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;adm:level:&amp;#39; &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;..&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;2&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;])                     &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- level&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;redis.&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;call&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;#39;HDEL&amp;#39;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, KEYS[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;3&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;], ARGV[&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;1&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;])                            &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;-- pending entry&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;return&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 1&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That fixes repeats, but not a &lt;strong&gt;stale&lt;/strong&gt; (out of date) undo. Suppose a candidate’s first payment is released and they book again. Then a late event for the &lt;em&gt;first&lt;/em&gt; payment arrives, such as a TTL expiry or a repeated callback. A guard that only asks “is the candidate admitted?” passes, because the candidate &lt;em&gt;is&lt;/em&gt; admitted again. The stale event then frees the new seat.&lt;/p&gt;
&lt;p&gt;So every release that a payment triggers goes through a second guard, keyed by payment ID. &lt;code&gt;SET hold:rollback:&amp;lt;paymentId&amp;gt; NX EX 86400&lt;/code&gt; and the undo run in the same script. A payment can release a seat at most once, and only the payment that owns the seat can release it.&lt;/p&gt;
&lt;p&gt;The rule we took from this: &lt;strong&gt;any operation that more than one path can trigger must be idempotent, and the guard that makes it idempotent must live in the same atomic step as the action itself.&lt;/strong&gt; (Idempotent means it is safe to run more than once, with the same result.) A check followed by a separate action is a race.&lt;/p&gt;
&lt;h2 id=&quot;failure-mode-2-the-reply-that-never-arrives&quot;&gt;Failure mode 2: the reply that never arrives&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What if the script succeeds but the API never hears about it?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Networks drop replies. When that happens, the Redis client does the sensible thing and retries the command. For the admission script, that sensible retry is a disaster.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/lost-reply-nonce.svg&quot; alt=&quot;A lost reply turns into a false duplicate unless the retry carries the same nonce&quot; title=&quot;Figure 2: Without a nonce, the retried admission finds the candidate already admitted and reports a duplicate. The user gets no payment link and the seat stays taken. With a nonce, the retry is recognised and returns the original slot.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The first call admitted the candidate. The retry finds them in &lt;code&gt;adm:seen&lt;/code&gt; and returns “duplicate”. The user sees “already registered” with no payment link, and their seat stays counted, with no hold behind it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The fix is a nonce for each request.&lt;/strong&gt; The API generates a random nonce for each booking request and passes it to the script. On admission, the script records it in the &lt;code&gt;adm:pending&lt;/code&gt; hash (step 4 above). When a call finds the candidate already admitted, it compares nonces. The same nonce means this is the same request, retried, so the script returns the original slot. A different nonce means a real second attempt, so it returns duplicate.&lt;/p&gt;
&lt;p&gt;We also run the admission with a context that is separate from the HTTP request’s cancellation. If a user closes the tab during the request, that cannot stop the call halfway through its retry.&lt;/p&gt;
&lt;h2 id=&quot;failure-mode-3-the-request-that-dies-halfway&quot;&gt;Failure mode 3: the request that dies halfway&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What if the API crashes between admitting and enqueueing?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The hot path is three steps: admit, create payment, enqueue. If the process dies after the first step, the seat is counted, but no record exists anywhere that could expire it. Neither the database nor the queue knows the seat exists. That would break invariant 3.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The pending ledger closes the gap.&lt;/strong&gt; (The ledger here is simply the list of admissions that are not yet safe in the database.) Every admission writes an &lt;code&gt;adm:pending&lt;/code&gt; entry in the same atomic step. &lt;code&gt;/book&lt;/code&gt; clears the entry only after the enqueue has succeeded, because from that point on the queued record carries the booking. Any rollback clears the entry atomically too.&lt;/p&gt;
&lt;p&gt;On every sweep, the reconciler (the single background runner described in Part 3) looks for pending entries older than 15 minutes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If a database record exists for that candidate, the booking completed. The reaper (the cleanup step) removes the entry.&lt;/li&gt;
&lt;li&gt;If no record exists, the request died between steps. The reaper undoes the admission, with the same nonce check, so it can never undo a newer attempt.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Fifteen minutes is longer than the 10-minute hold plus the queue’s worst-case delay. A slow but healthy request is never cleaned up by mistake.&lt;/p&gt;
&lt;h2 id=&quot;failure-mode-4-the-failover-that-forgets&quot;&gt;Failure mode 4: the failover that forgets&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Can a Redis failover sell a seat twice?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Yes, if you let it. ElastiCache replication is asynchronous. The primary confirms a write to the client before the replica has received it. If the primary dies in that gap, the replica is promoted to primary &lt;em&gt;without&lt;/em&gt; the last few admissions.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/failover-replica-ack.svg&quot; alt=&quot;Failover without and with a replica acknowledgement&quot; title=&quot;Figure 3: Left: the primary confirms the last seat, then dies before it replicates the write, and the promoted replica sells the same seat again. Right: the API waits for one replica to confirm the write before it confirms the booking, so the promoted replica already has the admission.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;At the last seat, that gap means one seat sold twice. The same applies to a candidate: the promoted replica does not know they booked, so they can book a second seat.&lt;/p&gt;
&lt;p&gt;We compared three options.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Trade-off&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Accept the risk&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The window is milliseconds long and failover is rare. But it breaks the one promise the client cared about, at exactly the moment when load is highest.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Count seats in the database too&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Correct, but it puts the database back on the hot path, which is what Part 1 worked to avoid.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Wait for a replica acknowledgement (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Send the script and &lt;code&gt;WAIT 1 200&lt;/code&gt; together in one pipeline: wait up to 200 ms for one replica to confirm it has the write. If the replica confirms, the admission counts. If not, undo it and return a &lt;code&gt;503&lt;/code&gt; that the client can retry.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Under normal conditions, replication lag between Availability Zones is a few milliseconds, so the wait adds almost nothing to a normal booking. Both commands go out in one pipeline, so there is no extra round trip.&lt;/p&gt;
&lt;p&gt;This choice has two consequences we accepted deliberately:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Bookings fail closed.&lt;/strong&gt; That means: if the replica is down, every booking returns &lt;code&gt;503&lt;/code&gt; until ElastiCache replaces it. We chose correctness over availability for this one path. The page retries with increasing delays, and replacing a replica takes minutes, not hours.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;WAIT&lt;/code&gt; is not consensus.&lt;/strong&gt; It makes a lost admission far less likely. It does not make Redis strongly consistent. With one replica, the node that confirmed the write is the node that gets promoted. That covers the realistic failure: the loss of one node or one Availability Zone.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As a final safety net, every five minutes the reconciler compares the Redis counters with a count of the records in DynamoDB. It raises an alert only if the mismatch is still there on two checks in a row, because records normally lag behind the counter by a few seconds.&lt;/p&gt;
&lt;h2 id=&quot;how-we-tested-it&quot;&gt;How we tested it&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you convince yourself a counter is right?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Unit tests against an in-memory Redis&lt;/strong&gt; for every branch of the script: caps, duplicates, nonce replay, idempotent and stale undo, and the pending reaper.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Race tests&lt;/strong&gt; that send thousands of admissions at the same time against a small cap. They check that the admitted count equals the cap exactly and that no candidate appears twice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A real primary and replica in Docker&lt;/strong&gt; for the replica acknowledgement path. In-memory fakes usually report zero replicas, so they cannot test it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Full-rate load tests&lt;/strong&gt; with 40,000 test candidates against the real stack. They pass only if admissions stop exactly at the cap and the counters match the database afterwards.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On launch day the invariants held. 20,700 seats were sold, with zero double bookings and zero overbookings.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;An admitted seat is only half a booking. &lt;a href=&quot;https://www.sumonselim.com/seat-reservation-part3-holds-payments-and-the-slow-path&quot;&gt;Part 3&lt;/a&gt; follows it through payment. It covers why a payment redirect can confirm a booking but never release one, and how a single runner makes every release decision. It also covers how a rate-limited gateway token is shared across the fleet, and how the queue and DynamoDB keep up without ever slowing down a booking.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Flash-Sale Seat Reservation System in AWS (Part 1): The Architecture</title><link>https://www.sumonselim.com/seat-reservation-part1-architecture-for-a-flash-sale/</link><guid isPermaLink="true">https://www.sumonselim.com/seat-reservation-part1-architecture-for-a-flash-sale/</guid><description>20,700 exam seats, millions of people trying at the same time, and an older system that crashed and sold seats twice. Part 1 explains what the traffic looked like, why one atomic Redis script decides who gets a seat instead of a database, how CloudFront handles three out of four requests before they reach a server, and why we added servers before the event instead of using autoscaling.</description><pubDate>Mon, 21 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; A language proficiency test certification exam had 20,700 seats across five levels. When registration opened last year, millions of people tried to access and book the exam. The previous system crashed under that load. It also sold the same seat twice.&lt;/p&gt;
&lt;p&gt;To make the system scalable, highly-available and reliable for this year’s registration, I re-designed the system and new design follows three rules.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;one atomic Redis script decides who gets a seat&lt;/strong&gt;. (Atomic means the whole check-and-count runs as one step that nothing can interrupt.) No database takes part in that decision.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;the request path does only three things&lt;/strong&gt;: admit the booking in Redis, create a payment link, and put a record on a queue. Everything else happens later, in the background.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;everything that can be a static file is served from the edge&lt;/strong&gt; (the CDN, close to the user). CloudFront, S3 and an AWS WAF web ACL handled about three out of four requests without touching a server.&lt;/p&gt;
&lt;p&gt;We sized the API fleet from load tests and added servers before the event. We did not use autoscaling. In the first hour it served 1.5M+ requests at the origin, peaked at 54.8K requests per minute, kept median latency under 10 ms, returned a server error on fewer than 0.01% of requests, and sold every seat with zero double bookings.&lt;/p&gt;
&lt;p&gt;This series is written as a design reference: the challenges, the options we compared, and why we chose what we chose.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What made this hard?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The work itself looks simple: a form with a candidate code, an email address and an exam level, then a payment. The traffic pattern is what makes it hard. Registration opens at an announced minute, so almost everyone arrives in the same few seconds. They keep refreshing the page until they get a seat or the seats run out. The previous system crashed at exactly that moment. It also sold some seats twice. The client’s requirement was simple and direct: &lt;strong&gt;stay up, and never book a seat twice.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Written out as requirements:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Detail&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Hard caps&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A cap (a maximum) per level, for five levels, and a global cap of 20,700. Never exceeded, not even by one seat.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One booking per candidate&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A candidate code can hold at most one live booking.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Eligible candidates only&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The code must be on an allowlist loaded in advance, and the email must match the one we have stored for that code.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Pay to keep the seat&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A seat is held for 10 minutes while the candidate pays through the payment gateway. If the payment is not completed, the seat returns to the pool of free seats.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Money-safe&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Nobody is charged for a seat they did not get, and nobody who paid loses their seat.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Available under the burst&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The page must load and answer quickly, even when everyone arrives at once.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;First come, first served&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No lottery. Whoever is admitted first gets the seat.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;“Never exceed the cap” and “one booking per candidate” are the two rules that define correctness. Part 2 is entirely about them. The rest of this post is about surviving the burst while keeping those rules true.&lt;/p&gt;
&lt;h2 id=&quot;the-shape-of-the-load&quot;&gt;The shape of the load&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does a flash sale look like in the traffic numbers?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Figure 1 shows the real traffic around opening time, grouped into five-minute buckets from CloudWatch.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/launch-traffic-edge-vs-origin.svg&quot; alt=&quot;Requests per 5 minutes at CloudFront (edge) and at the ALB (origin) around opening&quot; title=&quot;Figure 1: Requests at the edge compared with requests that reached the origin, in 5-minute buckets. The origin peaked at about 261K requests per five minutes. Over the first hour, the edge carried about four times as many requests as the origin.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Three things stand out, and each one shaped the design:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The ramp is a cliff.&lt;/strong&gt; In other words, traffic does not grow slowly; it jumps almost straight up. Origin traffic went from near zero to about 12K requests per minute in the first five minutes after opening, and to more than 50K per minute within twenty minutes. Anything that reacts to load, such as an Auto Scaling policy, a function with a cold start, or a database that scales its capacity, reacts too late. The moment that matters has already passed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Most requests are not bookings.&lt;/strong&gt; People reload the page and check availability long before and long after they submit the form. In the first hour CloudFront saw about 6.2M requests. Only about 1.5M of them reached the servers. Every request the edge answers is one that the booking path never has to handle.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Most of the origin traffic is rejections.&lt;/strong&gt; Once seats run low, most &lt;code&gt;/book&lt;/code&gt; calls end with a fast “no”: duplicate, level full, or closed. A rejection must cost almost nothing, because there are far more rejections than admissions.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;challenge-1-where-do-we-decide-who-gets-a-seat&quot;&gt;Challenge 1: where do we decide who gets a seat?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What is the single hardest decision in this system?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Every booking asks the same question: &lt;em&gt;is there still a seat at this level, and has this person already booked one?&lt;/em&gt; Thousands of requests ask it at the same instant. The answer must be exactly right for every one of them. Whatever component answers that question is the bottleneck of the whole system, so we chose it first.&lt;/p&gt;
&lt;p&gt;We considered four options.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Relational database row lock&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;SELECT ... FOR UPDATE&lt;/code&gt; on a &lt;code&gt;seats_left&lt;/code&gt; row, then insert the booking&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Correct, but every booking must wait its turn on one row. Lock waits build up, connection pools run empty, and everything times out at the same time. This is the classic failure of older systems of this kind.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. DynamoDB conditional counters&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;UpdateItem&lt;/code&gt; with &lt;code&gt;seats_left &amp;gt; 0&lt;/code&gt; on a counter item, plus a transaction for the duplicate check&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Correct and serverless, but a single counter item is a hot key (one item that every request writes to). One partition limits how many writes per second it can take. Adding a duplicate check means a transaction on every attempt, and even a rejection still costs a write.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Virtual waiting room&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Put everyone in a queue and let people in at a fixed rate&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Protects the backend, but it is a whole product to build or buy. Users wait for minutes, and you still need an atomic counter at the end of the queue.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;D. One atomic script in Redis&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A Lua script checks for a duplicate, checks the level cap and the global cap, and records the admission, all in one call&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Redis runs a script from start to finish before it runs anything else, so no lock is held while waiting on the network. It costs one round trip of microseconds, and a rejection is only a read. The open questions, durability and failover, are answered in Part 2.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/row-lock-vs-atomic-script.svg&quot; alt=&quot;A database row lock compared with an atomic in-memory script&quot; title=&quot;Figure 2: With a row lock, requests wait in line for one row and hold their connections while they wait. With an atomic script, each call runs from start to finish on the Redis thread and holds nothing while waiting on the network.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;We chose D.&lt;/strong&gt; The deciding argument was this: Redis runs commands on a single thread, and that single thread &lt;em&gt;is&lt;/em&gt; the lock. It is held only for the microseconds a script runs, never for a network round trip. The same property makes rejections nearly free. That matters because most of the traffic is rejections.&lt;/p&gt;
&lt;p&gt;The cost is that the source of truth for “who has a seat” now lives in memory. That creates three problems that Part 2 has to solve: a reply lost on the network, a process crash between steps, and a failover that loses the last few writes. We accepted those problems with open eyes. The other options had problems we could not solve within a single burst.&lt;/p&gt;
&lt;p&gt;We also chose the &lt;strong&gt;smallest possible Redis setup&lt;/strong&gt;: one shard (cluster mode disabled), one primary and one replica in different Availability Zones, with automatic failover. The script touches several keys at once. On one shard, that needs no extra work to keep the keys together (no hash tags). As Figure 4 shows later, a single &lt;code&gt;cache.r6g.large&lt;/code&gt; primary never went above 10% engine CPU.&lt;/p&gt;
&lt;h2 id=&quot;challenge-2-keep-the-hot-path-short&quot;&gt;Challenge 2: keep the hot path short&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What exactly happens inside a booking request?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The previous system did all its real work inside the request. It wrote the booking to the database, sent the email and updated the counters, all while the user waited. Under a burst, each of those steps becomes a waiting line, and the slowest one sets the latency for everyone.&lt;/p&gt;
&lt;p&gt;We split the work into a &lt;strong&gt;hot path&lt;/strong&gt; (the steps the user waits for) and a &lt;strong&gt;slow path&lt;/strong&gt; (the steps that run after the response is sent).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/hot-path-vs-slow-path.svg&quot; alt=&quot;Hot path vs slow path&quot; title=&quot;Figure 3: The hot path does one in-memory call, one HTTPS call, and one queue send. Every durable write happens after the response, outside the request.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;On the hot path, &lt;code&gt;POST /book&lt;/code&gt; does exactly three things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Admit&lt;/strong&gt; the booking in Redis with the atomic script.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Create a payment&lt;/strong&gt; with the payment gateway and get back a payment URL.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Enqueue&lt;/strong&gt; a &lt;code&gt;HELD&lt;/code&gt; record, which means send it to an SQS FIFO queue.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;It then returns &lt;code&gt;202 Accepted&lt;/code&gt; with the payment URL, and the browser redirects to the gateway. If step 2 or step 3 fails, the API undoes the admission before it responds. A failure never leaks a seat (leaves a seat counted with nobody holding it).&lt;/p&gt;
&lt;p&gt;The database is deliberately missing from this list. A worker reads the queue and writes the records into DynamoDB a few seconds later. Payment confirmations, expiry, emails and the back-office sync all run on the slow path. Part 3 covers that path in detail, including why it is safe for the database to be a few seconds behind the seat count.&lt;/p&gt;
&lt;p&gt;The payment gateway call is the one dependency on the hot path that we do not control. It is the only reason the hot path is not a pure in-memory operation. It is also the only slow step, and it shows in the slowest requests: p99 latency was 4.1 s in the first five minutes, when every admitted user was creating a payment at the same time. After that it settled to about 0.3 s. The median stayed at 2 to 5 ms the whole time, because most requests were fast rejections that never reached the gateway. Placing the gateway call &lt;em&gt;after&lt;/em&gt; admission is what makes this work: rejected requests never wait for it.&lt;/p&gt;
&lt;h2 id=&quot;challenge-3-keep-traffic-off-the-servers&quot;&gt;Challenge 3: keep traffic off the servers&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How do you make three out of four requests never reach your code?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The cheapest request is the one your servers never see. We put everything we could behind CloudFront.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The page itself&lt;/strong&gt; is a static HTML file in a private S3 bucket, served through CloudFront with Origin Access Control. Page loads never touch a server.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Availability counts&lt;/strong&gt; (seats left per level, and whether booking is open or closed) are a small &lt;code&gt;status.json&lt;/code&gt; document in the same bucket. The API rewrites it as the counts change. The browser reads it once when the page loads. After that, the page reacts to API responses instead of asking the server again and again. A &lt;code&gt;429 closed&lt;/code&gt; disables the form, and a &lt;code&gt;409 level full&lt;/code&gt; disables that level. CloudFront serves the file with caching disabled, so readers always see the latest version. The load still lands on S3, not on our servers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One origin, one hostname.&lt;/strong&gt; CloudFront routes &lt;code&gt;/book&lt;/code&gt;, &lt;code&gt;/payment/callback&lt;/code&gt;, &lt;code&gt;/payment/webhook&lt;/code&gt; and &lt;code&gt;/health&lt;/code&gt; to the Application Load Balancer, and everything else to S3. The page and the API share one hostname, so the browser sends no CORS preflight (an extra request the browser sends first when the page and the API are on different hosts). Under a burst, skipping the preflight removes a whole extra request from every booking.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In front of all of this sits an &lt;strong&gt;AWS WAF web ACL attached to the CloudFront distribution&lt;/strong&gt;. It checks every request at the edge before CloudFront forwards anything.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Rule&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Rate limit on &lt;code&gt;/book&lt;/code&gt;, 2,000 requests per 5 minutes per IP&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Stops a single client from flooding the booking endpoint&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Rate limit on &lt;code&gt;/payment/callback&lt;/code&gt;, 100 per 5 minutes per IP&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Makes it impractical to guess payment IDs&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;AWS managed IP reputation list and known-bad-inputs rules&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Drops known attackers and exploit payloads at low cost&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Body size limit on &lt;code&gt;/book&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The form is tiny, so a large request body is never legitimate&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The per-IP limits are deliberately generous. Mobile carriers in the region use carrier-grade NAT, which puts many subscribers behind a small number of shared public IPs. A strict per-IP limit would have blocked whole neighbourhoods of real candidates. The rate rules exist to stop abuse, not to control traffic. The admission script already rejects excess load cheaply on its own.&lt;/p&gt;
&lt;p&gt;The load balancer accepts traffic only from CloudFront. Its security group allows CloudFront’s origin-facing IP ranges and nothing else. But that list covers &lt;em&gt;every&lt;/em&gt; CloudFront distribution in AWS. An attacker could create their own distribution, point it at our load balancer, and bypass our web ACL. So CloudFront also adds a secret header to every request it sends to the origin. The ALB listener forwards only requests that carry that header. Its default action is a fixed &lt;code&gt;403&lt;/code&gt;. CloudFront talks to the ALB over HTTPS, so the secret never crosses the internet in clear text.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-capacity-for-a-cliff&quot;&gt;Challenge 4: capacity for a cliff&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why pre-scale instead of autoscale?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We considered three compute options.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;EC2 Auto Scaling with target tracking&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Scaling reacts to metrics that are a minute or more behind, then waits for new instances to boot and pass health checks. By the time new capacity arrives, the jump in Figure 1 is already over.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;AWS Lambda behind API Gateway&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Scales fast, but the burst hits concurrency ramp limits and cold starts at exactly the wrong moment. Every new execution environment also opens its own Redis connections. A traffic spike then becomes a flood of new connections to the one component that must not stall.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A fixed, pre-scaled fleet&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Simple and predictable. Size it from load tests, add instances hours before opening, and remove them afterwards.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;We pre-scaled a fixed fleet&lt;/strong&gt;: three instances, one per Availability Zone, behind an Application Load Balancer. Each instance ran the API and the queue worker as two systemd services, with a fixed Redis connection pool (300 connections per instance, enough that the burst never waits for a connection). The instances live in private subnets with no public IPs. They reach the payment gateway and the email provider through a NAT gateway in each Availability Zone, and they reach AWS APIs through VPC endpoints. Operators use AWS Systems Manager Session Manager, not SSH.&lt;/p&gt;
&lt;p&gt;We chose the size from load tests before launch. The setup was a k6 load generator in the same region, an allowlist pre-loaded with 40,000 test candidate codes (about double the real seat count), and a mock payment gateway with adjustable latency. The mock let us practise the full booking path at full rate without hitting the real gateway’s limits. The tests also shaped several details you will see in Parts 2 and 3.&lt;/p&gt;
&lt;p&gt;On the day, the fleet had far more capacity than it needed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/launch-cpu-api-vs-redis.svg&quot; alt=&quot;CPU of the API fleet and the Redis primary during the burst&quot; title=&quot;Figure 4: CPU during the burst. The API fleet averaged under 12% in the peak five minutes, and the Redis primary&apos;s engine CPU stayed under 10%.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;We sized it that way on purpose. The extra capacity cost a few dollars an hour for a few hours. An outage at opening would have cost the client the whole event. With these numbers, the next run could use two Graviton instances and a smaller Redis node and still use less than a third of their capacity at the peak.&lt;/p&gt;
&lt;h2 id=&quot;the-whole-architecture&quot;&gt;The whole architecture&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does it look like end to end?&lt;/strong&gt;&lt;/p&gt;
&lt;figure class=&quot;figure-wide&quot;&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/seat-reservation/architecture.svg&quot; alt=&quot;Seat reservation system architecture on AWS: CloudFront and AWS WAF at the edge, an ALB in public subnets, a pre-scaled API fleet with ElastiCache for Redis in private subnets, SQS FIFO, DynamoDB, the expiry and sync Lambdas, RDS, S3, and the external payment gateway and email provider&quot; class=&quot;rounded-lg border border-border w-full h-auto&quot; decoding=&quot;async&quot;/&gt;&lt;figcaption class=&quot;figure-caption font-mono text-xs text-muted-foreground text-center mt-2&quot;&gt;&lt;p&gt;Figure 5: The full architecture. CloudFront and the AWS WAF web ACL at the edge; an ALB and a pre-scaled API fleet in private subnets; Redis for admission; SQS FIFO, DynamoDB and Lambda for the slow path. &lt;a href=&quot;https://www.sumonselim.com/images/articles/seat-reservation/architecture.svg&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Open full-size diagram&lt;/a&gt;&lt;/p&gt;&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;A booking moves through it like this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The browser loads the page and &lt;code&gt;status.json&lt;/code&gt; from &lt;strong&gt;CloudFront&lt;/strong&gt;, which serves both from a private &lt;strong&gt;S3&lt;/strong&gt; bucket. The &lt;strong&gt;AWS WAF web ACL&lt;/strong&gt; on the distribution checks every request.&lt;/li&gt;
&lt;li&gt;The browser posts to &lt;code&gt;/book&lt;/code&gt;. CloudFront forwards the request over HTTPS, with the origin secret header, to the &lt;strong&gt;ALB&lt;/strong&gt; in the public subnets.&lt;/li&gt;
&lt;li&gt;An &lt;strong&gt;API instance&lt;/strong&gt; in a private subnet checks the gates (is booking open, is the code valid) and runs the admission script on &lt;strong&gt;ElastiCache for Redis&lt;/strong&gt; (primary plus replica across two AZs, TLS and AUTH enabled).&lt;/li&gt;
&lt;li&gt;If admitted, the API creates a payment with the &lt;strong&gt;payment gateway&lt;/strong&gt; (outbound through the NAT gateway) and enqueues a &lt;code&gt;HELD&lt;/code&gt; record on &lt;strong&gt;SQS FIFO&lt;/strong&gt;. It returns the payment URL.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;worker&lt;/strong&gt; on each instance long-polls the queue. (Long-polling means it keeps a request open and waits for messages instead of asking again and again.) It writes the record to &lt;strong&gt;DynamoDB&lt;/strong&gt; with a conditional put. (A conditional put is a write that succeeds only if a condition is true, here that the record does not exist yet.)&lt;/li&gt;
&lt;li&gt;The user pays at the gateway, and the gateway redirects the browser to &lt;code&gt;/payment/callback&lt;/code&gt;. The gateway also sends a signed webhook to &lt;code&gt;/payment/webhook&lt;/code&gt;. Either one can mark the booking &lt;code&gt;PAID&lt;/code&gt;. The API then sends a confirmation email.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;reconciler&lt;/strong&gt; (a background loop inside the API fleet, with only one instance running it at a time) releases holds that were not paid in time. &lt;strong&gt;DynamoDB TTL&lt;/strong&gt; (time to live: DynamoDB deletes a record some time after its deadline passes) and &lt;strong&gt;DynamoDB Streams&lt;/strong&gt; drive an &lt;strong&gt;expiry Lambda&lt;/strong&gt; that acts as a safety net.&lt;/li&gt;
&lt;li&gt;A second stream consumer, the &lt;strong&gt;sync Lambda&lt;/strong&gt;, copies paid bookings into an &lt;strong&gt;RDS&lt;/strong&gt; database for the back-office app. The back-office app also loads the candidate allowlist into Redis before opening.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;CloudWatch alarms&lt;/strong&gt; cover the things that should wake someone up: ALB 5xx errors and unhealthy hosts, Redis CPU, memory, connections and replication lag, queue depth and the dead-letter queue, DynamoDB throttles, Lambda errors and stream iterator age. Application logs go to CloudWatch Logs, so an incident never starts with an SSH session. A few custom metrics sit next to them: admissions per minute, replica-acknowledgement failures (explained in the next post), holds past their deadline, and any difference between the Redis counters and the database.&lt;/p&gt;
&lt;h2 id=&quot;launch-day&quot;&gt;Launch day&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Did it work?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Metric (first hour)&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Result&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Requests reaching the servers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;1.5M+ (about 6.2M at the edge)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Peak throughput at the origin&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;54.8K requests per minute&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Median latency&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;under 10 ms (2 to 5 ms at the ALB)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Requests served without a server error&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;99.99%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Seats sold&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;20,700 of 20,700, about 95% of them within the first hour&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Double bookings or overbookings&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The number I care about most is the last one. It did not happen by accident. It is the result of the decisions in Part 2, and of months of testing, finding problems and fixing them before launch (Part 3 describes how).&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 2 looks inside the admission script. It covers what the script checks and in what order. It explains how the script stays correct when a reply is lost and the client library retries, and how the seat from a crashed request is returned to the pool. It also shows how we closed the short time window in which a Redis failover could silently sell the same seat twice.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Self-Hosted AI Assistant (Part 7): Missions</title><link>https://www.sumonselim.com/timothy-part7-missions/</link><guid isPermaLink="true">https://www.sumonselim.com/timothy-part7-missions/</guid><description>A mission is Timothy&apos;s unit of long-running work: a goal driven through discover, plan, build, prove and result by a pure state machine. Part 7 covers fresh worker sessions instead of transcript replay, native and delegated CLI workers behind one contract, verification the harness owns, brakes that park instead of loop, and how schedules turn into missions and notifications.</description><pubDate>Tue, 15 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Timothy’s chat turns suit questions. They are the wrong shape for “refactor this module” or “research this and write it up”, work that takes dozens of model turns, must survive restarts, and needs checking. That work runs as a &lt;strong&gt;mission&lt;/strong&gt;: a goal driven through fixed phases by a pure state machine, with every transition written to Postgres. Three rules shape it.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;state lives in rows, not in a transcript&lt;/strong&gt;. Every worker turn is seeded from a packet (goal, plan, progress notes, git log), not from the last turn’s transcript. Resuming after a crash is a new session plus that packet, never a replay.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;the harness decides when work is done, never the model&lt;/strong&gt;. A worker’s DONE is a request for verification. A unit’s &lt;code&gt;passes&lt;/code&gt; flag flips only on a check the harness ran itself.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;every loop has a brake, and most brakes park rather than throw work away&lt;/strong&gt;. A stopped mission pauses with a typed reason, keeps its branch, and tells me.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does long work need that a chat turn does not have?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A chat turn lives in one request and one growing context. Long work breaks both: the context fills with tool output, the process restarts, and a model that says “all tests pass” may never have run them.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Detail&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Durable&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A brain restart mid-mission loses nothing; the driver picks it up from the row.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Honest&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;“Done” means a check passed, not that a model said so.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Bounded&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No mission can loop forever or spend without limit.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Unattended&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Missions run on a schedule and reach me when they need me.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2 id=&quot;challenge-1-how-does-work-outlive-a-conversation&quot;&gt;Challenge 1: how does work outlive a conversation?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not just give a chat turn more tools and more time?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. A long chat turn&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One agent loop runs until the model stops&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Unbounded context, a restart kills it, and the model decides when it is finished.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. An agent framework’s loop&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The framework holds plan and memory in process&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The state I most need to inspect and resume lives in someone else’s objects.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. A state machine over rows&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A pure &lt;code&gt;Step(state, input)&lt;/code&gt; decides every transition; workers are short, fresh sessions&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Restartable, testable without a model, and every decision is an event row.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p7-state-machine.svg&quot; alt=&quot;Mission phases, loops and pause reasons&quot; title=&quot;Figure 1: The mission pipeline, with rework, the one automatic replan, the flows that skip prove, and the typed reasons a mission can park on.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; &lt;code&gt;Step&lt;/code&gt; has no I/O: it takes phase, status and counters, and returns the next state plus the events to append. &lt;code&gt;Store.ApplyTransition&lt;/code&gt; is the only writer of mission state, in one transaction under a row lock. Phase and status are separate axes, so “in build, paused for budget” is one readable state.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Fixed phases.&lt;/strong&gt; &lt;code&gt;discover&lt;/code&gt; explores, &lt;code&gt;plan&lt;/code&gt; submits units (artifacts, a &lt;code&gt;check_cmd&lt;/code&gt;, acceptance criteria), &lt;code&gt;build&lt;/code&gt; works one unit per turn, &lt;code&gt;prove&lt;/code&gt; reviews, and &lt;code&gt;result&lt;/code&gt; delivers (push, pull request, destinations) with zero model calls. Lighter flows skip phases; the flow is fixed at creation and no tool call can change it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fresh sessions.&lt;/strong&gt; A native worker’s whole context is the rendered packet as one user message. Durability lives in the plan, the progress log and git history.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sentinel tools.&lt;/strong&gt; Each phase reports through a tool call (&lt;code&gt;submit_plan&lt;/code&gt;, &lt;code&gt;mission_status&lt;/code&gt;, &lt;code&gt;review_verdict&lt;/code&gt;), so results are structured, not prose.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-2-who-decides-that-the-work-is-done&quot;&gt;Challenge 2: who decides that the work is done?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Can the worker that wrote the code also grade it?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Trust the worker’s DONE&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The worker reports success&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Models claim success on unfinished work, and on goals that cannot be done.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. An LLM reviewer alone&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A second model reads the result&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Still a claim about a claim. It cannot see what never ran.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Harness evidence, then a reviewer&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Go checks artifacts and runs &lt;code&gt;check_cmd&lt;/code&gt;; a fresh reviewer judges what checks cannot&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Evidence the model cannot fake, plus judgement where existence checks fall short.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p7-verify-review-loop.svg&quot; alt=&quot;Harness verification and the review round&quot; title=&quot;Figure 2: A worker&apos;s DONE triggers a commit and a harness check of every unit; only harness-passed units reach the reviewer, and only they can flip passes.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; After every DONE the harness re-checks every unit, so an earlier unit’s regression is caught too. A failing check costs a worker turn, with its output in the next packet. The reviewer is a fresh session on its own &lt;code&gt;review_route&lt;/code&gt;, which exists so review can run on a different provider than the worker: a model is a weak judge of its own mistakes.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Gates must fail first.&lt;/strong&gt; At plan time a sandbox probe runs each &lt;code&gt;check_cmd&lt;/code&gt; against the untouched tree. A gate that already passes proves nothing, so the plan is rejected.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Artifacts before commands.&lt;/strong&gt; &lt;code&gt;CheckArtifacts&lt;/code&gt; confirms declared files exist, are non-empty and sit inside the workspace before any model-written command runs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Findings need evidence.&lt;/strong&gt; A blocking finding must name a changed file and quote it, or Go demotes it to minor. A criterion marked &lt;code&gt;not_met&lt;/code&gt; forces rework even if the reviewer approved.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-3-who-does-the-work&quot;&gt;Challenge 3: who does the work?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Should Timothy write code itself, or hand it to a coding CLI?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Native only&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every unit runs on Timothy’s agent loop&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Fine for research and writing; dedicated coding CLIs have far more tuning for code.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Delegate everything&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every mission goes to a CLI&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Loses Timothy’s skills, memory, knowledge base and permission chain.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Both behind one contract&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;Runner.RunWorker&lt;/code&gt; takes a packet and returns a &lt;code&gt;WorkerVerdict&lt;/code&gt; either way&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The state machine and verification never know which kind ran.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p7-native-vs-delegated.svg&quot; alt=&quot;Native and delegated workers&quot; title=&quot;Figure 3: Native and delegated workers return the same verdict to the same harness checks.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; A coding mission may name a &lt;strong&gt;harness&lt;/strong&gt; (claude, codex, cursor, opencode or pi). The CLI runs detached in the mission’s sandbox, the brain polls its output, and it reports through a DONE/RETRY/BLOCKED schema. It may resume its own CLI session between units, but the packet is always complete. Everything else runs native.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;An explicit harness is a contract.&lt;/strong&gt; If no route entry can serve it, the mission pauses as infra and resumes when the cooldown ends. A silent native fallback would change tools and prompt mid-mission.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One sandbox per mission.&lt;/strong&gt; &lt;code&gt;sandboxd&lt;/code&gt;, the only Docker-socket holder, runs it as an unprivileged user with a read-only root filesystem, no capabilities, resource caps, and only &lt;code&gt;PATH&lt;/code&gt; and &lt;code&gt;HOME&lt;/code&gt; in its environment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A clone per mission.&lt;/strong&gt; Each coding mission gets its own clone and branch, one commit per finished unit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Delegated review is optional.&lt;/strong&gt; A CLI reviewer runs read-only; any failure falls back to native review.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-4-how-does-it-run-when-i-am-not-watching&quot;&gt;Challenge 4: how does it run when I am not watching?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What starts a mission at 06:00, and what stops one that never ends?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Cron creates missions directly&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A ticker inserts mission rows&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Notifications and run tracking become side effects a crash can lose.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. A message broker&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Triggers and outcomes go through a queue&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Another service to run, for one user’s volume.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. An events inbox in Postgres&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Side effects are &lt;code&gt;events&lt;/code&gt; rows written in the same transaction as the change; a drainer delivers them after commit&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Nothing is lost between commit and send, in the database I already run.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p7-schedule-to-notification.svg&quot; alt=&quot;From cron boundary to notification&quot; title=&quot;Figure 4: Starting a scheduled mission and reporting its outcome both travel as events rows, so neither is lost in a crash.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; Schedules are &lt;strong&gt;automations&lt;/strong&gt;: an agent, a mission template, triggers (cron, webhooks, channel messages) and destinations. Each run is an ordinary mission created through the API’s path. When a mission reaches done, failed, paused or waiting for input, &lt;code&gt;ApplyTransition&lt;/code&gt; writes an events row; consumers notify me, reply in the originating channel, and close the automation run.&lt;/p&gt;
&lt;p&gt;The brakes (mission ceilings are operator settings, read per turn):&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Brake&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Stops&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Budget&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Ledger spend reaching the mission’s cap: pause&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Backoff&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Three worker failures in a row: pause&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Stall&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The same failure twice: one automatic replan, then pause&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Rework&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Review rounds reaching &lt;code&gt;max_iterations&lt;/code&gt;: pause, branch kept&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Iterations&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;max_iterations&lt;/code&gt; (default 8) retries in a phase: fail&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Automations&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Runs per hour, concurrency mode, a dedup key per boundary, a breaker after three failed runs&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Every harness change must pass &lt;code&gt;make canary&lt;/code&gt;: a real mission against the live stack, with a randomly drawn goal so caches cannot flatter it. It fails on any permission park, no harness-verified unit, or too many turns. A sibling canary inverts the test: its goal names a missing file, and it passes only if the mission fails honestly without fabricating it.&lt;/p&gt;
&lt;h2 id=&quot;what-broke&quot;&gt;What broke&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;The rollback that deleted good work.&lt;/strong&gt; Retries used to roll the working tree back. A delegated CLI wrote a module and its test, reported RETRY to fix one function, and the rollback deleted both. RETRY means unfinished, not wrong, so no retry rolls back now; only a review rework does.&lt;/p&gt;
&lt;h2 id=&quot;lessons&quot;&gt;Lessons&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Put long-running state in rows a pure function moves; transcripts are for reading, not resuming.&lt;/li&gt;
&lt;li&gt;A model’s “done” is a request for verification, and only harness evidence answers it.&lt;/li&gt;
&lt;li&gt;A check that passes before the work starts proves nothing, so test the gate too.&lt;/li&gt;
&lt;li&gt;Give review its own route so it can run on another provider; let the harness have the final say.&lt;/li&gt;
&lt;li&gt;A brake should park with a reason whenever the work might still be worth keeping.&lt;/li&gt;
&lt;li&gt;Side effects that must survive a crash belong in the same transaction as the change that caused them.&lt;/li&gt;
&lt;/ol&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Self-Hosted AI Assistant (Part 6): Letting the Model Act Safely</title><link>https://www.sumonselim.com/timothy-part6-letting-the-model-act-safely/</link><guid isPermaLink="true">https://www.sumonselim.com/timothy-part6-letting-the-model-act-safely/</guid><description>Timothy&apos;s model can run shell commands, read mail and fetch web pages, so every tool call walks a permission chain written in Go. Part 6 covers that chain, keeping big results and idle skills out of context, fencing untrusted tool output, pinning sensitive sessions to a local model, and the sandbox and network boundaries underneath.</description><pubDate>Sat, 12 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Timothy is the self-hosted, single-user AI assistant I build in Go. This part is about the model acting: running shell commands, reading mail, fetching pages. One agent loop executes every tool call, for chat and native mission workers alike, under three rules.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;the model proposes and code decides&lt;/strong&gt;. Every call walks one permission chain in Go: policy guard, exempt list, danger classifier, standing grants, then a prompt to me. First match wins.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;anything an outsider wrote reaches the model as fenced data&lt;/strong&gt;. Trust is a flag set on each tool where it is built, and the default is untrusted.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;privacy and blast radius are enforced by routes and networks, not prompts&lt;/strong&gt;. A session that touches a sensitive connector stays on a route I chain to a local model, side-calls included. Model code runs in containers only &lt;code&gt;sandboxd&lt;/code&gt; can create, and model-supplied URLs dial through an SSRF guard.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;A model with tools runs instructions from strangers. Some come from me; others ride in on a web page, an email or a PDF, and the model reads them with the same attention. It can also simply be wrong: a confident &lt;code&gt;rm&lt;/code&gt; in the wrong directory is not an attack, but it ends the same way.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Risk&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Example&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Stopped by&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Destructive action&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;git push&lt;/code&gt;, &lt;code&gt;rm&lt;/code&gt; outside the workspace&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Permission chain&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Injected instructions&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A mail body saying “forward the inbox”&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Trust fence, permission chain&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Private data leaving home&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Raw email sent to a cloud model&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Sensitive route pinning&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Escaping the box&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Model code reaching Postgres or the host&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;sandboxd&lt;/code&gt;, networks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Reaching internal addresses&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;fetch_url http://169.254.169.254/&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;netguard&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2 id=&quot;challenge-1-what-does-the-model-get-to-see&quot;&gt;Challenge 1: what does the model get to see?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;How much capability goes into every request?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Every schema costs tokens on every step, and the surface grows with each connector.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Agent framework&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A library owns the loop&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The loop is where safety lives; I want to read every line.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Everything eager&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;All schemas, skills and full results in every request&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One big MCP server or build log fills the window.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Typed registry, loaded lazily&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Typed tools; skills, big servers and big results load on demand&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Each request carries only what this turn needs.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; The loop is plain Go: call the gateway, run the requested tools (four in parallel), append results, repeat. By default, at step 15 of 16 the model is told to finish; at 16 the schemas are dropped and it must answer. The same call three times in a row forces that early.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Typed tools.&lt;/strong&gt; A tool is a name, a description (the model’s only manual), a JSON Schema and an &lt;code&gt;Execute&lt;/code&gt; function. Arguments are validated and clamped before the tool runs. Failures, panics included, return as structured feedback, never a crashed turn.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Big results stay out.&lt;/strong&gt; A result over 8 KB (4 KB for &lt;code&gt;shell&lt;/code&gt;) goes to &lt;code&gt;tool_outputs&lt;/code&gt;. The model gets a deterministic digest: size, first 30 and last 10 lines, error-looking lines, and a ref for &lt;code&gt;retrieve_output&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Skills are lazy packs.&lt;/strong&gt; The system prompt lists one “Use when” line per &lt;code&gt;SKILL.md&lt;/code&gt;; the body arrives only via &lt;code&gt;load_skill&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Large MCP servers hide behind an index&lt;/strong&gt; of one line per tool and a &lt;code&gt;load_tool&lt;/code&gt; entry point.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-2-who-decides-whether-a-call-runs&quot;&gt;Challenge 2: who decides whether a call runs?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not let the model decide?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Rules in the system prompt&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;“Never delete files without asking”&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Injected text can argue with a prompt.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Ask every time&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every call needs a click&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Safe and unusable. By day three I would approve without reading.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Static allowlist&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Listed tools run freely&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cannot tell &lt;code&gt;git status&lt;/code&gt; from &lt;code&gt;git push&lt;/code&gt;.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;D. Ordered chain in code&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Hard deny, exemptions, danger classifier, grants, then ask&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;More code, but each layer is small and testable.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p6-permission-chain.svg&quot; alt=&quot;Permission chain decision flow&quot; title=&quot;Figure 1: The permission chain for one tool call, where the first match wins.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose D.&lt;/strong&gt; The order is the design: a hard deny runs before anything that could allow, and a dangerous command is caught before any grant could wave it through.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The policy guard&lt;/strong&gt; refuses shell tokens naming env files, key material, &lt;code&gt;~/.ssh&lt;/code&gt;, &lt;code&gt;~/.aws&lt;/code&gt;, system directories, &lt;code&gt;..&lt;/code&gt;, or absolute paths outside the workspace. It matches path-shaped tokens only, so grepping for the word “credentials” still runs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The danger classifier&lt;/strong&gt; scores commands against a regex table. &lt;code&gt;rm&lt;/code&gt;, &lt;code&gt;git push&lt;/code&gt;, &lt;code&gt;sudo&lt;/code&gt;, &lt;code&gt;docker&lt;/code&gt;, &lt;code&gt;curl | sh&lt;/code&gt; and an overwriting redirect score 3; &lt;code&gt;mv&lt;/code&gt;, &lt;code&gt;kill&lt;/code&gt; and &lt;code&gt;chmod -R&lt;/code&gt; score 2. At 3 the call asks, and no grant skips that. A command it cannot read (&lt;code&gt;$(...)&lt;/code&gt;, &lt;code&gt;eval&lt;/code&gt;, &lt;code&gt;sh -c&lt;/code&gt;) counts as destructive. Inside a mission sandbox, file-scoped rules on the mission’s own paths relax, because there the container is the boundary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Exempt tools&lt;/strong&gt; are pure reads with their own guards (&lt;code&gt;fetch_url&lt;/code&gt;, &lt;code&gt;search_kb&lt;/code&gt;), mission sentinels, and the root-confined &lt;code&gt;write_file&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Asking&lt;/strong&gt; parks the turn. I allow once, allow for the session (a &lt;code&gt;session_grants&lt;/code&gt; row for 12 hours), or deny. An unattended mission gets an automatic denial with a hint on how to rewrite the call.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-3-how-does-untrusted-text-stay-data&quot;&gt;Challenge 3: how does untrusted text stay data?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What stops a web page from giving orders?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Nothing&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Results go in as plain text&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Injected text looks exactly like my instructions.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. List of untrusted tools&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The loop fences results from named tools&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Fails open for any tool the list forgets.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Trust flag per tool&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;Tool.Trusted&lt;/code&gt; is set where the tool is built; everything else is fenced&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A new tool is fenced until someone decides otherwise.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p6-trust-fence.svg&quot; alt=&quot;Trust fence around tool results&quot; title=&quot;Figure 2: Untrusted results are wrapped and escaped; attached documents are the remaining gap.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose C,&lt;/strong&gt; after B failed: the list missed tools it did not name, and MCP servers choose their own names. Now a tool returning anything an outsider wrote simply never sets &lt;code&gt;Trusted&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;One fence.&lt;/strong&gt; &lt;code&gt;trustfence&lt;/code&gt; wraps content in &lt;code&gt;&amp;lt;untrusted_content source=&amp;quot;...&amp;quot; trust=&amp;quot;data&amp;quot;&amp;gt;&lt;/code&gt; with a preamble saying everything inside is quoted material. Memories use the same mechanism.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Forged close tags are escaped,&lt;/strong&gt; case and whitespace variants included.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Errors pass through.&lt;/strong&gt; They are harness prose the model needs to read.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;shell&lt;/code&gt; is trusted on purpose.&lt;/strong&gt; Its output is the model’s own workspace; fencing it would wrap every build log.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The known gap: attached files and referenced documents enter the user message unfenced. And the fence is a strong hint, not enforcement: &lt;code&gt;fetch_url&lt;/code&gt; is exempt, so a page that persuades the model to fetch a URL with private data in its query string is not stopped here. That risk is still open, which is why the defences below never rely on the model behaving.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-where-may-private-data-and-model-code-go&quot;&gt;Challenge 4: where may private data and model code go?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What keeps my inbox off a cloud model, and model code off my host?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Local model for everything&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No cloud provider at all&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Local models are weaker at long, tool-heavy work.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Pin only the turn&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The turn that called a sensitive tool switches route&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The mail stays in the transcript, and side-calls re-send it later.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Pin the session, side-calls included&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;After a sensitive tool runs, every later call uses the sensitive route&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Some turns run on a weaker model.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p6-sensitive-pinning.svg&quot; alt=&quot;Sensitive session route pinning&quot; title=&quot;Figure 3: A sensitive connector flips the route mid-turn, and the session stays pinned, side-calls included.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; Privacy is a property of the transcript, not of one turn. Every connector, from Gmail and Calendar to an MCP server, has a &lt;code&gt;sensitive&lt;/code&gt; flag, and the &lt;code&gt;sensitive_tool_route&lt;/code&gt; setting names a route I chain to a local model.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Mid-turn flip.&lt;/strong&gt; When the model asks for a sensitive tool, the loop switches route before the result goes back, and drops any model hint, which would otherwise outrank the route.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sticky.&lt;/strong&gt; Every later turn scans &lt;code&gt;session_events&lt;/code&gt; for a sensitive &lt;code&gt;tool_execution&lt;/code&gt;. Unified tools like &lt;code&gt;search_mail&lt;/code&gt; carry no connector name, so the call’s &lt;code&gt;account&lt;/code&gt; argument is resolved back to its connector.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Side-calls too.&lt;/strong&gt; Memory extraction, turn distillation, auto-titling and compaction share the verdict.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p6-sandbox-boundary.svg&quot; alt=&quot;Sandbox and network boundaries&quot; title=&quot;Figure 4: Only sandboxd holds the Docker socket, and outbound fetches dial through netguard.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Chat’s &lt;code&gt;shell&lt;/code&gt; runs inside the brain container under the permission chain. Mission code runs in per-mission containers that only &lt;code&gt;sandboxd&lt;/code&gt; can create, because it alone holds the Docker socket. It sits on a network only brain reaches, runs read-only with every capability dropped, and accepts a mission UUID, a command and a few validated fields, never a free-form image, mount or container name. Each container runs unprivileged with a read-only root filesystem, resource caps, and only its own mission directory mounted. It lives on the default bridge, so &lt;code&gt;pip install&lt;/code&gt; works while Timothy’s internal network stays out of reach.&lt;/p&gt;
&lt;p&gt;Outbound URLs go through &lt;code&gt;netguard&lt;/code&gt;. It resolves the host itself, refuses loopback, private, link-local (cloud metadata) and CGNAT addresses, dials the vetted IP so DNS cannot change in between, and re-checks every redirect. Model-supplied URLs get no exceptions; operator-configured MCP endpoints and webhooks may skip it only for allowlisted hosts.&lt;/p&gt;
&lt;h2 id=&quot;what-broke&quot;&gt;What broke&lt;/h2&gt;
&lt;p&gt;The first &lt;code&gt;load_tool&lt;/code&gt; exemption was a suffix rule: any tool ending in &lt;code&gt;_load_tool&lt;/code&gt; skipped the chain. MCP servers name their own tools, so a server could publish &lt;code&gt;exfiltrate_load_tool&lt;/code&gt; and walk past every check. The exemption is now an exact match against names the connector manager generates. Same lesson as the trust flag: a name an outsider chooses must never carry authority.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 7 covers missions: long-running work that outlives a chat turn, judged by evidence the harness collects rather than the model’s word.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Self-Hosted AI Assistant (Part 5): Memory and Knowledge</title><link>https://www.sumonselim.com/timothy-part5-memory-and-knowledge/</link><guid isPermaLink="true">https://www.sumonselim.com/timothy-part5-memory-and-knowledge/</guid><description>Timothy remembers facts about its user and searches documents the user added, and both live in one Postgres. Part 5 covers typed memories that land pending and only ever supersede, a promotion policy written in Go, three-leg recall fused with RRF into a fenced 1,500-token block, and a knowledge base the model searches through a tool instead of having it pushed into every prompt.</description><pubDate>Thu, 10 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Timothy is my self-hosted, single-user AI assistant. It keeps two kinds of long-term context. &lt;strong&gt;Memory&lt;/strong&gt; is short facts about me, pulled out of conversations. The &lt;strong&gt;knowledge base&lt;/strong&gt; (KB) is documents I add, chunked and indexed. Both live in one Postgres with pgvector, under three rules.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;the model proposes, code decides&lt;/strong&gt;. One LLM call suggests facts as strict JSON. Go validates them, removes duplicates and decides whether each one becomes active.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;a memory is never edited, only superseded&lt;/strong&gt;. A correction inserts a new row and archives the old one, which points at its successor. Recall only sees &lt;code&gt;active&lt;/code&gt; rows.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;memory is pushed, knowledge is pulled&lt;/strong&gt;. A small, token-budgeted memory block rides on every turn inside a trust fence. The KB is too big for that, so the model searches it with a tool.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What should an assistant remember, and what should it look up?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A provider’s built-in memory belongs to that provider, and I switch models often. Memory also steers the model, so a bad memory is worse than none.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Detail&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Provider-independent&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Facts survive a change of model or provider.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Owner in control&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;I can confirm, reject, edit and archive every memory.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No confident staleness&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Unconfirmed facts fade. Returning nothing beats returning something wrong.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Bounded cost&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A hard token budget, counted with a real tokenizer.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Poisoning resistant&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Retrieved text is framed as data, never as instructions.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Documents&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;PDFs, DOCX, HTML, web pages and their images become searchable.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2 id=&quot;challenge-1-who-decides-what-becomes-a-memory&quot;&gt;Challenge 1: who decides what becomes a memory?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;If the model writes its own memory, who checks it?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Provider memory&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The vendor’s memory feature&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Locked to one vendor, invisible to me.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Model writes directly&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A tool call stores an active fact&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One injected web page can plant a standing instruction.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Search raw transcripts&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Index every old turn&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Noisy, and old turns contradict newer ones.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;D. Propose, then stage&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;An LLM proposes; Go checks; most land &lt;code&gt;pending&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The model reads. Code makes every decision that matters.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose D.&lt;/strong&gt; Spotting facts in a conversation is language work. Deciding what may influence future turns is policy, which belongs in code I can test.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p5-memory-lifecycle.svg&quot; alt=&quot;Memory lifecycle: proposals pass Go checks, land pending, and move to active, rejected or archived&quot; title=&quot;Figure 1: Only the promotion policy, the user, or the remember tool make a memory active, and corrections form a supersede chain.&quot;/&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Trigger&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Input&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Turn end&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The user’s message plus the turn’s distilled summary, fire-and-forget&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Before compaction&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Turns about to be summarized away&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Mission finished&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The outcome digest, under a stricter prompt: discoveries only&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Daily reflection&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Recent episodic memories, asked for at most three cross-episode insights&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;remember&lt;/code&gt; tool&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A fact I explicitly asked to keep: active at once&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;What keeps it safe:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Types age differently.&lt;/strong&gt; &lt;code&gt;episodic&lt;/code&gt; is something that happened, &lt;code&gt;semantic&lt;/code&gt; a durable fact or preference, &lt;code&gt;procedural&lt;/code&gt; a how-to. Rules and standing instructions must be &lt;code&gt;semantic&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Promotion is a Go function.&lt;/strong&gt; Only &lt;code&gt;episodic&lt;/code&gt; facts with confidence of at least 0.8 and no sensitive words (“password”, “always”, “from now on”) activate alone. &lt;code&gt;semantic&lt;/code&gt; and &lt;code&gt;procedural&lt;/code&gt; facts always wait for me, because that is where instructions would hide.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Strict parsing.&lt;/strong&gt; An unknown field, bad enum or missing &lt;code&gt;changes_behavior&lt;/code&gt; flag rejects the batch, which gets one retry. Facts marked as general knowledge are dropped.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Repetition reinforces.&lt;/strong&gt; A proposal within cosine 0.95 of an active memory bumps its &lt;code&gt;last_confirmed_at&lt;/code&gt; instead of inserting. A match with a rejected memory is dropped, so rejections stick.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-2-how-does-recall-find-the-right-few-facts&quot;&gt;Challenge 2: how does recall find the right few facts?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Which memories go into this turn’s prompt?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Vector only&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;k nearest embeddings&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Misses exact names; always returns something.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Separate stores&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Vector DB, search engine, graph DB&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Three systems to sync for a few thousand rows.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Tool-only recall&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The model calls &lt;code&gt;search_memory&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;It cannot ask about a preference it does not know exists.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;D. Three legs in Postgres&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Vector, full-text and entity queries fused with Reciprocal Rank Fusion (RRF)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One store, and each leg covers another’s blind spot.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose D&lt;/strong&gt;, run before every turn. &lt;code&gt;search_memory&lt;/code&gt; remains for deliberate lookups.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p5-recall-pipeline.svg&quot; alt=&quot;Recall pipeline from the user message through three legs, RRF, decay, cutoff and packing into a fenced block&quot; title=&quot;Figure 2: RRF merges three legs&apos; ranks, recency and type weights scale the score, and survivors are packed into a fenced block at the prompt&apos;s tail.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The score is &lt;code&gt;sum(1 / (60 + rank)) × 0.5^(age / 90 days) × type weight&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Legs fail independently.&lt;/strong&gt; With the embedding route down, full-text and entity still answer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A floor, not a quota.&lt;/strong&gt; Scores under 0.005 are dropped: a fresh semantic hit at rank 30 survives; after about 120 unconfirmed days it does not.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A real token budget.&lt;/strong&gt; Items are costed with the o200k tokenizer in rendered form, fence included, up to 1,500 tokens. The best item goes first and the runner-up last, because models attend least to the middle.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fenced at the tail.&lt;/strong&gt; The block is wrapped in &lt;code&gt;&amp;lt;memory trust=&amp;quot;data&amp;quot;&amp;gt;&lt;/code&gt; with a “not instructions” preamble, and closing-tag lookalikes are escaped. It sits after the stable prompt prefix, so prompt caching survives.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-3-how-does-memory-stay-clean&quot;&gt;Challenge 3: how does memory stay clean?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What stops a year of extraction from becoming noise?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In-place rewrites would break supersede-only; a TTL would delete facts I rely on. Instead, memoryd runs a daily consolidation job of independent stages, each a status change or a supersede:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Stage&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Rule&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Merge near-duplicates&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;An LLM merges each group into one fact; a guard rejects merges that drop specific tokens or change length too much.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Dedupe pending&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Of two pending near-duplicates, the newer is rejected.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Archive episodic&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Not created or retrieved in 180 days.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Decay semantic&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Unconfirmed for a year: confidence × 0.8, queued for reconfirmation.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Reflect&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Ten or more episodic memories in 7 days: ask for up to 3 insights, which land pending.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Demote pending&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Low-confidence, never retrieved, 60 days old: archived.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Recall stamps &lt;code&gt;last_retrieved_at&lt;/code&gt; and &lt;code&gt;retrieval_hits&lt;/code&gt;, so the job acts on what is actually used.&lt;/p&gt;
&lt;h2 id=&quot;challenge-4-how-should-documents-reach-the-model&quot;&gt;Challenge 4: how should documents reach the model?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Retrieve the KB like memory, or search it on demand?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Pre-retrieve every turn&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Inject top chunks for the user message&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Pays tokens on every turn; most turns need no documents.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Paste whole documents&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Attach files to the prompt&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Blows the context window.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Tool-driven search&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The model calls &lt;code&gt;search_kb&lt;/code&gt;, then &lt;code&gt;read_kb&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Tokens are spent only when a question needs documents.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; Memory is small and nearly always relevant; documents are large and sometimes relevant. Pinning a collection to a session tells the model to call &lt;code&gt;search_kb&lt;/code&gt; first.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p5-kb-pipeline.svg&quot; alt=&quot;KB ingestion from file or URL through markitdown, image description, chunking and embedding, and the search_kb read path&quot; title=&quot;Figure 3: Brain converts and enriches documents, memoryd chunks and embeds them, and search_kb fuses two gated legs into capped, fenced passages.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;One converter.&lt;/strong&gt; A &lt;code&gt;markitdown-svc&lt;/code&gt; sidecar turns PDF, DOCX and HTML into Markdown, and returns PDF images plus renders of pages with almost no text layer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Images become text.&lt;/strong&gt; A vision-route caption, or local OCR from &lt;code&gt;ocr-svc&lt;/code&gt; when no vision route is bound.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Heading-aware chunks&lt;/strong&gt; of about 500 tokens with 15% overlap. The breadcrumb (title and heading path) is embedded with each chunk.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Delete and rewrite.&lt;/strong&gt; Re-ingest replaces a document’s chunks in one transaction; transient failures retry after 2, 10 and 30 minutes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Gated legs.&lt;/strong&gt; Vector hits need cosine 0.25; keyword hits need two shared query words and count at a tenth of the vector weight.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Weights, never filters.&lt;/strong&gt; The agent’s and session’s collections get a 1.5× boost, but the model cannot choose collections. Mission output (0.8) and web clips (0.6) rank below curated documents.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Two chunks per document at most&lt;/strong&gt;, and results come back fenced as &lt;code&gt;&amp;lt;untrusted_content&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p5-memory-vs-kb.svg&quot; alt=&quot;Side-by-side comparison of long-term memory and the knowledge base&quot; title=&quot;Figure 4: Memory and the knowledge base share one Postgres and the same fusion idea, but differ in who writes them, when they are read and how they are framed.&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;what-broke&quot;&gt;What broke&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;The confirmation queue flooded.&lt;/strong&gt; Near-duplicates were once inserted for consolidation to merge later, and mission digests had their own goal and title extracted as “facts”. The fixes were in code: duplicates reinforce the existing row, missions got their own extraction contract, and a word-overlap check drops facts that echo the digest’s header.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;One shared word was enough to rank.&lt;/strong&gt; The KB keyword leg OR-matched query words, so a chunk sharing one common word outranked relevant documents. The two-word minimum and the low keyword weight came from that, checked against a recall test set.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 6 covers what happens when the model stops reading and starts acting: tools, permissions and the sandbox.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Self-Hosted AI Assistant (Part 4): Never Lose a Turn</title><link>https://www.sumonselim.com/timothy-part4-never-lose-a-turn/</link><guid isPermaLink="true">https://www.sumonselim.com/timothy-part4-never-lose-a-turn/</guid><description>A chat turn in Timothy can run for half an hour, longer than any browser tab should be trusted to stay open. Part 4 explains why a turn belongs to the session rather than the HTTP request, how a returning tab reattaches to a turn still in flight, why a session allows one turn at a time, and the five places a turn&apos;s final event was once lost.</description><pubDate>Tue, 08 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Timothy is the self-hosted AI assistant I built in Go. A chat turn can call tools, wait for my approval, and stream from a slow local model, so it often outlives the browser tab that started it. This part is about making sure a turn that ran always leaves a trace. Three rules carry it.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;a turn belongs to the session, not to the request&lt;/strong&gt;. Closing the tab ends the HTTP request, not the turn. Only the stop button or a 30-minute ceiling can.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;a returning tab reattaches; it does not guess&lt;/strong&gt;. A running turn buffers its events in memory. A new tab replays that buffer and follows the turn live, through the same code path as the tab that started it.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;every stream ends with exactly one terminal event&lt;/strong&gt;. The rule holds at every hop from the provider to the browser, and a backstop in the persistence path covers any hop that still fails.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why can’t a chat turn just be an HTTP request?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The obvious Go handler runs the whole turn on the request’s context, so everything stops when the client goes away. But I reload pages and my laptop sleeps. Each of those used to kill an answer seconds from finishing, and the session then showed a failure that was not one.&lt;/p&gt;
&lt;p&gt;The opposite mistake is worse: a turn that ends with nothing recorded at all. The requirements:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What it means&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Survives the client&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A closed tab, reload or dropped connection never kills a turn&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Stoppable&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;An explicit stop works from any tab&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Watchable&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Any tab can watch a running turn live&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Exclusive&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Two sends on one session never interleave in the event log&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Always evidenced&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A turn that ran leaves an answer, a partial, or a named failure&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2 id=&quot;challenge-1-who-owns-a-turn&quot;&gt;Challenge 1: who owns a turn?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What should cancel a turn, if not the browser?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p4-detached-turn.svg&quot; alt=&quot;Detached turn lifecycle&quot; title=&quot;Figure 1: Closing the tab ends only the request, while the turn runs on its own context until it persists, and stop takes the same exit as the deadline.&quot;/&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Request-scoped context&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The turn runs on the request’s context&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A reload or a dropped connection kills the turn&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Job queue and worker&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Persist a job, a worker runs it, clients poll&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A broker and a second copy of state the event log already holds, for one user&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Detached turn with its own context (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The turn runs in brain on a context the request cannot cancel, registered per session&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No new infrastructure; the event log stays the only durable state&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; Brain builds the turn’s context with &lt;code&gt;context.WithTimeout(context.WithoutCancel(reqCtx), 30*time.Minute)&lt;/code&gt;. It keeps the request’s values (auth, trace) and drops its cancellation. The relay watches the request only to know whether this tab is still listening. When the tab goes, the relay switches to &lt;code&gt;drainAndPersist&lt;/code&gt;: it consumes the turn to the end and persists it as if the client had stayed.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Stop is explicit.&lt;/strong&gt; Closing a tab used to double as a stop button, so a real one had to exist: &lt;code&gt;POST /v1/sessions/{id}/stop&lt;/code&gt; calls the stored cancel function. The turn then exits through the same path as the deadline: partial text becomes a &lt;code&gt;pending_state&lt;/code&gt;, otherwise a &lt;code&gt;turn_failed&lt;/code&gt; event.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The ceiling must outlive the permission park.&lt;/strong&gt; A turn can wait 10 minutes for my approval of a tool call. A &lt;code&gt;TURN_TIMEOUT&lt;/code&gt; override exists for slow CPU-only backends, and values of 10 minutes or less are rejected.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Partials are checkpointed.&lt;/strong&gt; The relay writes a &lt;code&gt;pending_state&lt;/code&gt; every 2 seconds while text grows, so even a killed brain loses little.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-2-how-does-a-returning-tab-catch-up&quot;&gt;Challenge 2: how does a returning tab catch up?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Is the persisted transcript enough for a tab that opens mid-turn?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p4-reattach-vs-refetch.svg&quot; alt=&quot;Re-fetch versus reattach&quot; title=&quot;Figure 2: A re-fetch sees only what is durable, while /live replays the turn so far and then follows it, falling back to a re-fetch when it cannot finish.&quot;/&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Re-fetch the transcript&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Poll &lt;code&gt;GET /v1/sessions/{id}&lt;/code&gt; until the turn completes&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Only as fresh as the last checkpoint, with no live tokens or tool calls&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Persist every token, tail the log&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Write each chunk to &lt;code&gt;session_events&lt;/code&gt;, stream from the database&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Floods the append-only log with deltas both projections must ignore&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. In-memory replay buffer (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;GET /v1/sessions/{id}/live&lt;/code&gt; replays the turn’s events so far, then follows it&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No extra writes, same wire format as the original stream&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; Each running turn has a &lt;strong&gt;turn broadcaster&lt;/strong&gt;: a buffer of every event so far plus a set of live subscriber channels. &lt;code&gt;subscribe()&lt;/code&gt; takes the snapshot and registers the channel under one lock, so no event can fall into the gap between replay and live. The stream is identical to &lt;code&gt;POST .../messages&lt;/code&gt; and ends with the same &lt;code&gt;meta&lt;/code&gt; event, so the web client feeds both through one reducer.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The registry is the truth.&lt;/strong&gt; &lt;code&gt;turn_active&lt;/code&gt; on the session endpoint is read from the broadcaster map, not a separate flag. The entry is removed only after the terminal persist is durable, so &lt;code&gt;turn_active: false&lt;/code&gt; guarantees a fetch sees the finished turn.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Slow watchers are cut loose.&lt;/strong&gt; A subscriber more than 64 events behind is closed rather than allowed to stall the turn. It sees no &lt;code&gt;meta&lt;/code&gt;, so the client re-fetches once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Re-fetch remains the fallback.&lt;/strong&gt; A &lt;code&gt;404 no_active_turn&lt;/code&gt; means the turn just finished, so the client re-fetches. A transport error means it is probably still running, so the client reattaches, up to five times.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-3-what-stops-two-turns-on-one-session&quot;&gt;Challenge 3: what stops two turns on one session?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What happens when I double-click send, or two tabs send at once?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p4-one-turn-409.svg&quot; alt=&quot;One turn per session&quot; title=&quot;Figure 3: The slot is claimed before the first append, so the losing request writes nothing and becomes a viewer of the winning turn.&quot;/&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Database lock&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A row or advisory lock per session&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A second source of truth for “a turn is running” that can drift&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Queue the second message&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Run it after the current turn&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The second send is usually an accident (a double-click or a racing retry), and a queue is more state to own&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Exclusive claim, then 409 (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;turnBegin&lt;/code&gt; registers the broadcaster or fails&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The same map answers “is a turn running?” and “may I start one?”&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; &lt;code&gt;turnBegin&lt;/code&gt; checks and inserts under one mutex. A loser gets &lt;code&gt;ErrTurnInFlight&lt;/code&gt;, which the API maps to &lt;code&gt;409 turn_in_flight&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Claim before the first append.&lt;/strong&gt; The check runs before the &lt;code&gt;user_message&lt;/code&gt; is written, so a loser never leaves a message with no turn behind it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The loser becomes a viewer.&lt;/strong&gt; The web client answers a 409 with a toast and an attach to &lt;code&gt;/live&lt;/code&gt;, so a double-click is harmless.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-4-how-does-every-stream-end-exactly-once&quot;&gt;Challenge 4: how does every stream end exactly once?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Can the end of a turn be best-effort?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Every provider’s wire format is translated into one event vocabulary with a one-line contract: a stream ends with exactly one terminal event, &lt;code&gt;done&lt;/code&gt; (possibly preceded by &lt;code&gt;incomplete&lt;/code&gt;) or &lt;code&gt;error&lt;/code&gt;, and the channel closes immediately after.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Trust each producer&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Each layer sends its terminal if it can&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Any one lost send erases the turn&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Backstop only&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Persistence synthesizes a failure when nothing arrives&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A generic reason that hides which layer broke&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Defend every hop, plus a backstop (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Each layer guarantees its terminal; persistence refuses to record nothing&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Real reasons reach the user&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; The details that make each hop honest:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Headers before the provider dial.&lt;/strong&gt; Brain’s gateway client allows 30 seconds for response headers, and a cold-loading local model can be slower. The gateway writes &lt;code&gt;200&lt;/code&gt; and flushes before its first provider attempt; later failures, including &lt;code&gt;chain_exhausted&lt;/code&gt;, arrive as SSE error events.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Silence has a name.&lt;/strong&gt; A provider that finishes with zero content is a failed attempt (&lt;code&gt;empty_output&lt;/code&gt;) that fails over to the next provider, and the ledger books it as &lt;code&gt;incomplete&lt;/code&gt;, never &lt;code&gt;ok&lt;/code&gt;. A completed turn with no text, reasoning or tool calls becomes &lt;code&gt;turn_failed&lt;/code&gt; with &lt;code&gt;empty_response&lt;/code&gt;. The agent loop keeps an &lt;code&gt;incomplete&lt;/code&gt; sticky, so a later &lt;code&gt;done&lt;/code&gt; cannot erase it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Heartbeats.&lt;/strong&gt; The chat stream and &lt;code&gt;/live&lt;/code&gt; write a &lt;code&gt;: ping&lt;/code&gt; comment every 20 seconds, so no proxy sees an idle connection.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;what-broke&quot;&gt;What broke&lt;/h2&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p4-terminal-contract.svg&quot; alt=&quot;Where the terminal event was lost&quot; title=&quot;Figure 4: The terminal event was lost at five places on its way to the browser, and persistTurn is the backstop beneath all of them.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;A turn of about thirty minutes against a slow model on a CPU-only box ended with nothing in &lt;code&gt;session_events&lt;/code&gt;. Detached turns made long turns possible, and long turns exposed every weak hop. A proxy killed the connection after about 100 idle seconds. The provider driver’s final &lt;code&gt;emit&lt;/code&gt; lost a race against &lt;code&gt;ctx.Done()&lt;/code&gt; and closed its channel empty. The gateway sent no terminal after content had streamed. Brain’s gateway client skipped its synthetic &lt;code&gt;gateway_stream_cut&lt;/code&gt; because the context was already done, and the agent loop’s final send raced the same deadline.&lt;/p&gt;
&lt;p&gt;Three of the five came down to one pattern: &lt;code&gt;select { case out &amp;lt;- ev: case &amp;lt;-ctx.Done(): }&lt;/code&gt; for an end-of-stream event. When the deadline fires as the terminal is sent, both cases are ready and Go picks one at random. The gateway now names a terminal-less close &lt;code&gt;stream_cut&lt;/code&gt;, and brain sends terminals with a 5-second bound instead (&lt;code&gt;emitFinal&lt;/code&gt; in the loop). Underneath, &lt;code&gt;persistTurn&lt;/code&gt; turns “no text and no failure” into &lt;code&gt;turn_failed&lt;/code&gt; with code &lt;code&gt;turn_aborted&lt;/code&gt;. The lesson: &lt;strong&gt;racing cancellation is fine for progress events and wrong for the event that proves the work happened.&lt;/strong&gt;&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 5 turns to what Timothy remembers afterwards: typed, staged memory and a knowledge base the model searches through a tool.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Self-Hosted AI Assistant (Part 3): Sessions as an Event Log</title><link>https://www.sumonselim.com/timothy-part3-sessions-as-an-event-log/</link><guid isPermaLink="true">https://www.sumonselim.com/timothy-part3-sessions-as-an-event-log/</guid><description>Every Timothy conversation is an append-only log of typed events in Postgres. Part 3 explains why the model&apos;s context and the chat transcript are two separate projections of that log, how appends keep the prompt prefix stable for provider caches, how compaction summarizes without losing facts, and how checkpoints let a turn survive a killed process.</description><pubDate>Sat, 05 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Timothy is the self-hosted AI assistant I built in Go. A conversation in Timothy is not a list of messages. It is an append-only log of typed events in one Postgres table, &lt;code&gt;session_events&lt;/code&gt;, and everything else is computed from it. Three rules shape it.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;the log is the only truth, and it only grows&lt;/strong&gt;. No event is ever edited. Every change, including a summary that replaces old turns, is a new row with the next sequence number.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;what the model sees and what I see are different documents&lt;/strong&gt;. Two pure functions read the same rows: one builds the model’s context, the other builds the rich transcript the web UI replays. Neither is stored.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;the projected prefix never changes between turns&lt;/strong&gt;. New content is appended at the end, so provider prompt caches keep hitting. The prefix moves only at a compaction event, which is rare and deliberate.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does a chat session need to survive?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A chat session looks simple until turns run tools and stream for minutes. Then it has to handle all of these:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Detail&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Crash safety&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Killing the brain mid-answer loses at most a couple of seconds of text.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Full replay&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Reloading the page shows everything: reasoning, tool calls, cost, failures.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Bounded context&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The model’s context stays under a token budget without forgetting names, dates or commitments.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cache friendliness&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Turn N+1 resends turn N’s messages byte for byte, so the provider can reuse its cache.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Fast follow-ups&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A question sent seconds after an answer must see that answer as complete.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The UI wants everything, the model wants as little as possible, and the cache wants nothing to change.&lt;/p&gt;
&lt;h2 id=&quot;challenge-1-how-do-you-store-a-conversation&quot;&gt;Challenge 1: how do you store a conversation?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not a messages table?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Messages table, edited in place&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One row per message; summaries and partial answers overwrite rows.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every summary destroys history, and the UI and the model are forced to share one shape.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. One JSON document per session&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Load, modify, save the whole conversation.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Concurrent writers (a streaming turn, a permission answer, a late summary) lose each other’s writes.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Append-only event log with projections (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Typed events with a gapless per-session &lt;code&gt;seq&lt;/code&gt;; views are computed on read.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Writes are tiny and never touch history. Any view can be rebuilt.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose the event log.&lt;/strong&gt; Every requirement above turned into “append one more event”: a checkpoint, a summary, a failure, a late distillation. Nothing reaches back to edit.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p3-two-projections.svg&quot; alt=&quot;One session_events log projected into the model context and the UI transcript&quot; title=&quot;Figure 1: The same rows feed two projections: the model never sees tool digests or permission prompts, and the UI never shows turn memory.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Gapless sequence numbers.&lt;/strong&gt; &lt;code&gt;Append&lt;/code&gt; locks the &lt;code&gt;sessions&lt;/code&gt; row &lt;code&gt;FOR UPDATE&lt;/code&gt; and inserts &lt;code&gt;MAX(seq) + 1&lt;/code&gt; in the same transaction. Writers to one session queue behind each other; different sessions never contend.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Kinds are added, never changed.&lt;/strong&gt; There are ten: &lt;code&gt;session_started&lt;/code&gt;, &lt;code&gt;user_message&lt;/code&gt;, &lt;code&gt;assistant_turn&lt;/code&gt;, &lt;code&gt;tool_execution&lt;/code&gt;, &lt;code&gt;turn_memory&lt;/code&gt;, &lt;code&gt;compaction_applied&lt;/code&gt;, &lt;code&gt;pending_state&lt;/code&gt;, &lt;code&gt;permission_request&lt;/code&gt;, &lt;code&gt;permission_resolved&lt;/code&gt; and &lt;code&gt;turn_failed&lt;/code&gt;. New fields are additive, so old rows still decode.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tool traffic stays out of the model’s history.&lt;/strong&gt; Within a turn the model sees tool results directly. Across turns, &lt;code&gt;tool_execution&lt;/code&gt; holds only a digest for the UI, and a separate &lt;code&gt;turn_memory&lt;/code&gt; event carries the distilled residue the model needs: files changed, failures and why, key findings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Attachments are converted once.&lt;/strong&gt; A PDF’s markdown is stored inside the &lt;code&gt;user_message&lt;/code&gt; at send time. Images are stored as references and turned into bytes only just before the gateway call.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-2-how-do-you-keep-the-prompt-cache-warm&quot;&gt;Challenge 2: how do you keep the prompt cache warm?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not trim the context to fit?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Provider prompt caches match on a byte-identical prefix, so rewriting any earlier message means a cache miss and a higher bill.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Sliding window&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Drop the oldest messages until the context fits the budget.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Once the budget is reached the prefix changes every turn, and old facts disappear silently.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Per-turn rewriting&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Middleware compresses or reformats older messages on each request.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;An “optimisation” that busts the cache on every turn.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Append-only projection (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;code&gt;LLMContext&lt;/code&gt; never trims; new events become new messages at the tail.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The prefix stays identical between turns and changes only when a compaction event lands.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose the append-only projection.&lt;/strong&gt; &lt;code&gt;LLMContext&lt;/code&gt; takes a budget argument and deliberately ignores it: the compactor enforces the budget, in rare and deliberate steps.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p3-prefix-stability.svg&quot; alt=&quot;Append-only projection versus a sliding window&quot; title=&quot;Figure 2: Appending keeps turn N&apos;s messages byte-identical in turn N+1, while a sliding window shifts every message once the budget is reached.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Late residue is its own message.&lt;/strong&gt; Distilling a turn into &lt;code&gt;turn_memory&lt;/code&gt; is an LLM call that finishes seconds after the answer. The &lt;code&gt;assistant_turn&lt;/code&gt; is appended the moment the stream ends; the residue lands later as a new event rather than an edit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Per-turn extras ride the system prompt’s tail.&lt;/strong&gt; Recalled memories and a hinted skill can change every turn, so they go after the stable part of the system prompt.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A property test enforces it.&lt;/strong&gt; It grows a log one event at a time and fails if any earlier projected message changes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;One sanctioned exception.&lt;/strong&gt; A spliced partial answer (Challenge 4) vanishes when the turn completes. That is one cache miss per recovered interruption, cheaper than duplicating content or adding an LLM call to the failure path.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-3-how-do-you-compact-without-forgetting&quot;&gt;Challenge 3: how do you compact without forgetting?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What do you throw away when the context is full?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Truncate&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Drop old turns.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Loses exactly the commitments and decisions a long conversation exists to keep.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. One-shot rewrite&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Summarize the whole session and replace the stored history.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Irreversible: one bad summary is permanent.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Incremental compaction event (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Summarize the oldest half of the live messages into a &lt;code&gt;compaction_applied&lt;/code&gt; event.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The log keeps every original row; only the model’s view changes.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose incremental compaction.&lt;/strong&gt; A &lt;code&gt;compaction_applied&lt;/code&gt; event says “in the model’s context, replace everything up to &lt;code&gt;replaces_through_seq&lt;/code&gt; with this summary”. The UI still shows every original message, plus a divider noting which ones the model now sees only as a summary.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p3-compaction.svg&quot; alt=&quot;The compaction boundary and what replaces what&quot; title=&quot;Figure 3: One compaction pass extracts facts, summarizes the oldest half, and appends a single event; the original rows stay in the log.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Trigger.&lt;/strong&gt; &lt;code&gt;MaybeCompact&lt;/code&gt; runs after every completed turn and again before each send. The budget is 60% of the context window of the model that served the last turn, falling back to a setting (60,000 tokens by default). Tokens are counted with tiktoken’s &lt;code&gt;o200k_base&lt;/code&gt; encoding, not a bytes-divided-by-three guess.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Boundary.&lt;/strong&gt; The cut is half the live messages, extended so it never ends on an unanswered question, with at least one turn left live. It maps back to an event &lt;code&gt;seq&lt;/code&gt;; if the mapping does not line up, nothing is compacted.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Facts first.&lt;/strong&gt; Before summarizing, the turns about to be replaced go to memoryd for extraction, and the memory ids are recorded in &lt;code&gt;facts_extracted&lt;/code&gt;. Whatever the summary drops still survives as memory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Summary rules.&lt;/strong&gt; The summarizer must keep every name, date, number, commitment, decision and open question. A truncated or empty summary is rejected, and the next turn tries again.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-4-what-survives-a-crash-mid-answer&quot;&gt;Challenge 4: what survives a crash mid-answer?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What if the brain dies while the model is still talking?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Write at the end of the turn&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Persist only when the stream completes.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A crash or deploy during a three-minute answer loses all of it.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Write every chunk&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One row per streamed token.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Thousands of rows per turn for no extra safety.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Periodic checkpoints (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Append a &lt;code&gt;pending_state&lt;/code&gt; with the full partial text every two seconds, plus one on any abnormal end.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Bounded loss, a handful of rows, and the same projection code handles recovery.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose periodic checkpoints.&lt;/strong&gt; Each &lt;code&gt;pending_state&lt;/code&gt; holds the whole partial text, so only the newest matters, and a &lt;code&gt;SIGKILL&lt;/code&gt; loses at most one flush interval.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p3-crash-checkpoint.svg&quot; alt=&quot;Checkpoint timeline: flushes, a kill, and the splice on the next request&quot; title=&quot;Figure 4: After a kill, the newest checkpoint splices into the next request as an interrupted assistant message until a completed turn supersedes it.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Live means newest and not superseded.&lt;/strong&gt; A later &lt;code&gt;assistant_turn&lt;/code&gt; supersedes it, and so does a compaction whose boundary covers it. A user message does not: the question after an interruption must still see the partial.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The model is told.&lt;/strong&gt; The partial projects as an assistant message ending in &lt;code&gt;[this response was interrupted mid-stream; continue from it]&lt;/code&gt;. The UI shows it as an interrupted turn.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Writes outlive the request.&lt;/strong&gt; Checkpoints and final writes use a context detached from the HTTP request, so a closed tab or a shutdown still leaves a durable row.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A turn never leaves zero events.&lt;/strong&gt; If there is no partial text, a &lt;code&gt;turn_failed&lt;/code&gt; event records the reason instead, and the model sees &lt;code&gt;[previous turn failed: ...]&lt;/code&gt; next time.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;what-broke&quot;&gt;What broke&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Turn memory as an assistant message.&lt;/strong&gt; The residue first rode in the assistant role. Weaker models imitate what they appear to have written, so one began echoing &lt;code&gt;[turn memory] finding: ...&lt;/code&gt; into live answers, and the distiller then fed on its own output. Residue now rides as a user-role note, which models are far less inclined to imitate.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Empty summaries.&lt;/strong&gt; Reasoning-heavy models spent the whole output cap thinking and returned an empty summary. The summarize call now asks for low reasoning effort and allows 3,000 output tokens, and an empty result is refused rather than stored.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 4 follows a single turn from the browser to the provider and back, and shows why it must always end in exactly one terminal event.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Self-Hosted AI Assistant (Part 2): The LLM Gateway</title><link>https://www.sumonselim.com/timothy-part2-the-llm-gateway/</link><guid isPermaLink="true">https://www.sumonselim.com/timothy-part2-the-llm-gateway/</guid><description>Every model call in Timothy&apos;s own agent loop goes through one gateway that holds the provider keys. Providers are Postgres rows, routes are bound to roles and filtered by capability, every driver speaks one event vocabulary, and failover stops the moment content reaches the client. Every attempt leaves a ledger row priced at request time, or NULL when the price is unknown.</description><pubDate>Thu, 03 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Every model call in Timothy’s own loop goes through one Go service, the &lt;strong&gt;gateway&lt;/strong&gt;. It holds the provider credentials for those calls, picks a provider and model per request, streams the answer back in one normalized format, and writes a cost row for every attempt. Three rules shape it.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;providers and routes are data&lt;/strong&gt;. Adding a provider or swapping a model is a row edit, live within seconds, never a code change or a restart.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;failover stops at the first byte of content&lt;/strong&gt;. Before anything reaches the client, the gateway retries and fails over freely. After that, it never switches providers: an error is relayed honestly instead of being papered over.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;cost is recorded, never guessed&lt;/strong&gt;. Each attempt is priced at request time and never rewritten. An unknown price means &lt;code&gt;NULL&lt;/code&gt;, not an estimate.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;Timothy talks to many models: Anthropic and OpenAI directly, OpenAI-compatible endpoints such as Z.AI, xAI and OpenRouter, AWS Bedrock, and a local Ollama on my own hardware. Each speaks a different protocol, reports tokens differently, and fails in its own way. Chat turns, summaries, memory extraction, embeddings and mission workers all need them.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;What it means&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One credential holder&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The agent loop never touches a provider key&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Change without deploys&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Add a provider, swap a model, reorder a fallback: no restart&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One stream shape&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;brain’s agent loop handles one vocabulary, not four&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Honest failure&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No silently restarted answers&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Honest cost&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every attempt, success or failure, leaves a row&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2 id=&quot;challenge-1-where-do-providers-live&quot;&gt;Challenge 1: where do providers live?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not configure providers in code or a config file?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. A Go type per provider&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Clients and model names in code&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every new model is a release.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Config file plus env vars&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;YAML for providers, keys in the environment&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A restart for every model swap, and plaintext keys in every process that inherits the environment.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Rows plus secret references (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A &lt;code&gt;providers&lt;/code&gt; row names a driver, base URL, default model and a &lt;code&gt;credential_ref&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Edited from the UI, hot-reloaded, and the row never holds a key.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose rows.&lt;/strong&gt; A provider is a row with a &lt;code&gt;driver&lt;/code&gt; (one of four: &lt;code&gt;anthropic&lt;/code&gt;, &lt;code&gt;openaicompat&lt;/code&gt;, &lt;code&gt;openai-responses&lt;/code&gt;, &lt;code&gt;bedrock&lt;/code&gt;), a &lt;code&gt;base_url&lt;/code&gt;, headers, an &lt;code&gt;options&lt;/code&gt; blob and a &lt;code&gt;credential_ref&lt;/code&gt;. The ref is a name, never a value. One &lt;code&gt;openaicompat&lt;/code&gt; driver serves every conforming endpoint. Drivers are thin wire adapters: they translate, never loop or route.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A secret store resolves refs.&lt;/strong&gt; The &lt;code&gt;secrets&lt;/code&gt; table maps a ref name to a backend: built-in storage (AES-256-GCM under a master key, with the ref name bound as additional data so a ciphertext copied onto another row fails to open), HashiCorp Vault, or AWS Secrets Manager. The master key, &lt;code&gt;TIMOTHY_MASTER_KEY&lt;/code&gt;, is the only credential that lives in the environment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unresolved means unhealthy, not crashed.&lt;/strong&gt; A ref that resolves empty marks that provider unhealthy, and routing skips it. A row whose driver fails to build is excluded alone; the rest keep serving.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Snapshots swap atomically.&lt;/strong&gt; Both tables are read in one read-only &lt;code&gt;REPEATABLE READ&lt;/code&gt; transaction into an immutable snapshot, swapped in through an atomic pointer. Reloads run on a 30-second poll and after every admin write. A failed reload keeps the last good snapshot.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-2-how-does-a-request-pick-a-model&quot;&gt;Challenge 2: how does a request pick a model?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not let each caller name the model?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Callers name a model&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;brain sends a model id&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Model ids spread through the code; changing one is a hunt.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Task categories&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Callers say “coding” or “summarize”&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A fixed taxonomy every caller and every chain must agree on.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Route names in code&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Code compares &lt;code&gt;route == &amp;quot;embedding&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Renaming a route silently breaks whatever looked it up.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;D. Routes bound to roles (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Four roles (&lt;code&gt;default&lt;/code&gt;, &lt;code&gt;summarize&lt;/code&gt;, &lt;code&gt;embedding&lt;/code&gt;, &lt;code&gt;vision&lt;/code&gt;) say which route serves what Timothy needs&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Names are free text; code asks “which route holds role X?”&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose roles.&lt;/strong&gt; A route is a named, ordered chain of &lt;code&gt;{provider_id, model}&lt;/code&gt; entries, plus a &lt;code&gt;capability&lt;/code&gt; (&lt;code&gt;chat&lt;/code&gt;, &lt;code&gt;embeddings&lt;/code&gt; or &lt;code&gt;vision&lt;/code&gt;) and an optional &lt;code&gt;role&lt;/code&gt;. A partial unique index allows one route per role. brain asks the gateway which route holds a role, so routes can be renamed or rebuilt without touching code, and agents can point at their own.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p2-route-resolution.svg&quot; alt=&quot;Route resolution from role to attempts&quot; title=&quot;Figure 1: A request becomes an ordered list of attempts: hint, then sticky, then the chain in strategy order, each candidate gated on health and capability.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Capability is checked twice.&lt;/strong&gt; The driver must declare it, and the model’s entry in the synced LiteLLM catalog must agree, so an embeddings-only model in a chat chain is skipped before any wire call. Images in the messages add &lt;code&gt;vision&lt;/code&gt; to every candidate.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sticky beats score.&lt;/strong&gt; The provider that last served this session successfully on this route goes first, because staying put keeps its prompt cache warm. Sticky is a preference, never an expansion: it must already be in the chain, and editing the route resets it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Strategies are per route.&lt;/strong&gt; &lt;code&gt;ordered&lt;/code&gt; keeps my written order. &lt;code&gt;auto&lt;/code&gt;, &lt;code&gt;price&lt;/code&gt; and &lt;code&gt;latency&lt;/code&gt; score entries from declared prices and the last hour of ledger stats. Uptime multiplies the score, so a cheap provider that keeps failing sinks under every strategy.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Rejections are explained.&lt;/strong&gt; If nothing passes, the &lt;code&gt;no_route&lt;/code&gt; error lists every skipped candidate and why.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-3-when-is-it-safe-to-switch-providers&quot;&gt;Challenge 3: when is it safe to switch providers?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;If a provider fails, why not just replay the request on the next one?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The rule rests on one contract: every driver translates its wire format into the same channel of events, ending with exactly one terminal event, &lt;code&gt;done&lt;/code&gt; or &lt;code&gt;error&lt;/code&gt;. Drivers also normalize usage, so input tokens always exclude cache reads.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p2-event-stream.svg&quot; alt=&quot;Four drivers, one event stream&quot; title=&quot;Figure 2: Four wire formats in, one ordered event vocabulary out, with exactly one terminal event per stream.&quot;/&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. No failover&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One provider per request&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One outage stops every turn.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Replay anywhere&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;On any error, resend to the next provider&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The client already rendered half an answer, maybe a tool call; a second model writes a different one on top.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Splice&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Continue the partial answer on another provider&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Two models writing one answer, and tool-call state cannot be handed over.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;D. A bright line (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Fail over only before the first content event&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The client sees one provider’s answer, or an honest error.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose the bright line.&lt;/strong&gt; An attempt’s errors are held back until it produces content: a &lt;code&gt;chunk&lt;/code&gt;, &lt;code&gt;reasoning_chunk&lt;/code&gt; or tool event. Until then, a failed attempt is drained quietly, recorded, and the loop moves on with a &lt;code&gt;failover&lt;/code&gt; event. After that, the stream belongs to that provider, and any error goes to the client as-is.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p2-failover-bright-line.svg&quot; alt=&quot;The failover bright line&quot; title=&quot;Figure 3: Left of the line the client has seen nothing, so retry and failover are safe; right of it, the gateway only reports.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Not every error advances.&lt;/strong&gt; Timeouts, 5xx, 429 and 401/403 (a bad key on this provider) move on. 400, 404, 413 and 422 stop the chain, because the next provider would reject the same request.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Retries are sized by position.&lt;/strong&gt; The HTTP drivers retry 429, 5xx and network errors with jittered exponential backoff, but only once while more entries remain; the last entry gets three.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Exhaustion names every attempt&lt;/strong&gt; by error code only, never raw provider text.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-4-how-do-you-account-for-cost-honestly&quot;&gt;Challenge 4: how do you account for cost honestly?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Why not store tokens and price them later?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Price at query time&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Store tokens; price them when the dashboard asks&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A price edit rewrites history overnight.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Provider billing exports&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Reconcile from each vendor’s usage export&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Late, per vendor, blind to sessions and agents.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Price at request time (chosen)&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cost computed when &lt;code&gt;usage&lt;/code&gt; arrives and frozen in the row&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;The row says what was known then; unknown stays &lt;code&gt;NULL&lt;/code&gt;.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose to freeze cost at request time.&lt;/strong&gt; Every attempt, failed ones included, leaves one &lt;code&gt;cost_ledger&lt;/code&gt; row: provider, model, route, agent, purpose, session, tokens, latency, status and cost. The &lt;code&gt;done&lt;/code&gt; event carries the &lt;code&gt;ledger_id&lt;/code&gt; and cost back to brain. A failed insert is logged, never raised: accounting must not break serving.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p2-ledger-row.svg&quot; alt=&quot;Lifecycle of a ledger row&quot; title=&quot;Figure 4: Prices are resolved before the call, cost is fixed when usage arrives, and the same frozen rows feed stickiness, scoring and budgets.&quot;/&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Prices come from two places.&lt;/strong&gt; An operator’s per-model override wins; otherwise the synced catalog. If neither has the model, &lt;code&gt;cost&lt;/code&gt; is &lt;code&gt;NULL&lt;/code&gt;, with a warning and an unpriced-usage counter, so the gap is visible instead of silently zero.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cache writes are split by tier.&lt;/strong&gt; One-hour cache writes are stored apart from five-minute ones because they bill higher. With no declared one-hour price, the cost is &lt;code&gt;NULL&lt;/code&gt; rather than a guessed multiple.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Currency is stored, never converted.&lt;/strong&gt; FX rates exist for display only.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The same rows steer routing.&lt;/strong&gt; Stickiness, scored strategies, the usage dashboard and daily and monthly budgets all read the ledger.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;what-broke&quot;&gt;What broke&lt;/h2&gt;
&lt;p&gt;Some reasoning-class OpenAI models returned a &lt;code&gt;200&lt;/code&gt; and an empty stream over chat/completions on turns where a tool call was mandatory. Counting that as success is doubly wrong: the turn looks fine, and stickiness, which reads &lt;code&gt;status=&amp;#39;ok&amp;#39;&lt;/code&gt; rows, pins the session to the provider that returned nothing. Now a contentless stream is booked &lt;code&gt;empty_output&lt;/code&gt; and advances the chain, and a dedicated &lt;code&gt;openai-responses&lt;/code&gt; driver serves those models. Success means content, not a status code.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 3 follows the stream into brain, where every session is an append-only event log with two projections.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Designing a Self-Hosted AI Assistant (Part 1): The Architecture</title><link>https://www.sumonselim.com/timothy-part1-the-architecture/</link><guid isPermaLink="true">https://www.sumonselim.com/timothy-part1-the-architecture/</guid><description>Timothy is a self-hosted, single-user AI assistant written in Go. Part 1 explains the rule behind it (Go orchestrates, each model call does one job), why it is split into brain, gateway, memoryd and sandboxd along trust boundaries instead of features, why one Postgres with pgvector holds all state, and how one chat request moves through the system.</description><pubDate>Tue, 01 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; Timothy is a self-hosted AI assistant I built in Go for one user: me. It gives me one chat interface over every model provider I use, memory in my own database, a ledger of every token spent, and long-running work that continues after I close the tab. The design follows three rules.&lt;/p&gt;
&lt;p&gt;First, &lt;strong&gt;deterministic code orchestrates, and each model call does exactly one thing&lt;/strong&gt;. Go decides which model to call, what goes into the prompt, whether a tool may run, and when to stop. A model call answers one question and returns data.&lt;/p&gt;
&lt;p&gt;Second, &lt;strong&gt;services are split along trust boundaries, not features&lt;/strong&gt;. The gateway is the path to every model provider, sandboxd alone holds the Docker socket, and brain is the only service with a public API.&lt;/p&gt;
&lt;p&gt;Third, &lt;strong&gt;one Postgres holds all state&lt;/strong&gt;. Sessions, memories, vectors, the cost ledger, missions and encrypted secrets share one database with pgvector. No broker, no separate vector database.&lt;/p&gt;
&lt;p&gt;This series is written as a design reference: the requirements, the options I compared, and why I chose what I chose. The code is on &lt;a href=&quot;https://github.com/SumonMSelim/timothy&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What does a personal assistant need that a chat tab does not give?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I use several model providers, each in its own tab with its own history. None shows what a conversation cost across providers, none remembers what I told the others, and none works unless I am typing. Timothy replaces those tabs:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Requirement&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Detail&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Users&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Exactly one. One bearer token guards everything.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Providers&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Any number, configured at runtime as rows, not code. Hosted APIs and local models side by side.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;State&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Conversations, memory, configuration and costs live in my database.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Cost&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every model call lands in a ledger. An unknown price is stored as unknown, never guessed.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Unattended work&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Missions and automations run without me, and stop for approval before anything destructive.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Footprint&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One Docker Compose file on one machine. No Kubernetes, no broker.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2 id=&quot;challenge-1-who-decides-what-happens-next&quot;&gt;Challenge 1: who decides what happens next?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Should the model run the show, or the code?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. Agent framework&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A library supplies the loop, memory, tool calling and prompt templates&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Prompts hide behind abstractions. When a turn goes wrong I need the exact bytes sent.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. Model as orchestrator&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A planning model picks tools, sub-agents and models, and decides when work is done&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;It loses coherence, defends its own mistakes and declares unfinished work done. Every safety rule becomes a prompt it can be talked out of.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Go orchestrates, each call does one job&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Plain Go calls the gateway. Each model call has one purpose and returns data that code validates&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No framework to lean on; the plumbing is mine to write and test.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p1-one-job-per-call.svg&quot; alt=&quot;Go decisions beside single-purpose model calls&quot; title=&quot;Figure 1: Go makes every decision that must be repeatable, and each model call has one job that the ledger&apos;s purpose column records.&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; The deciding argument: a prompt can be persuaded and an &lt;code&gt;if&lt;/code&gt; statement cannot. Routing, compaction, memory selection and tool permission must give the same answer every time, so they are Go. Models get the reading, summarising and writing, one narrow job per call.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;One agent loop, in one place.&lt;/strong&gt; brain owns the only tool loop; the gateway never loops. The loop has a 16-step ceiling, warns the model one step early, and sends the last step with no tools.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Every side call is labelled.&lt;/strong&gt; Distillation, memory extraction, compaction summaries, titles, agent dispatch and knowledge-base filing are separate calls, each with its own &lt;code&gt;purpose&lt;/code&gt; in the cost ledger.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-2-where-do-the-seams-go&quot;&gt;Challenge 2: where do the seams go?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;One process, a service per feature, or something else?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. One binary&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Everything in one Go process&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Simplest to run, but the process reading untrusted web pages and model output would also hold every provider key and the Docker socket, which is root on the host.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. A service per feature&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Chat, missions, automations and the knowledge base as separate services over a broker&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Many deploy units for one user, and the seams follow features, which change, not privileges, which do not.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. Split where privilege or runtime differs&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;A few Go services, each holding one dangerous thing, plus sidecars for Python-only tools&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;More containers, and internal calls cross the network.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; A seam earns its place when it keeps a key, a socket or a runtime away from code that handles untrusted input, and brain handles untrusted input (web pages, email, tool results, model output) all day.&lt;/p&gt;
&lt;figure class=&quot;figure-wide&quot;&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/architecture.svg&quot; alt=&quot;Timothy architecture: every compose service, both networks, Postgres, mission sandboxes and model providers&quot; class=&quot;rounded-lg border border-border w-full h-auto&quot; decoding=&quot;async&quot;/&gt;&lt;figcaption class=&quot;figure-caption font-mono text-xs text-muted-foreground text-center mt-2&quot;&gt;&lt;p&gt;Figure 2: Every service in the compose file, where only web and brain publish ports and sandboxd shares a network with brain alone. &lt;a href=&quot;https://www.sumonselim.com/images/articles/timothy/architecture.svg&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Open full-size diagram&lt;/a&gt;&lt;/p&gt;&lt;/figcaption&gt;&lt;/figure&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Service&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Owns&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Never does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;brain&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;public API, agent loop, tools, missions, channels, connectors&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;touch the Docker socket&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;gateway&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;providers, routing, failover, normalized streaming, cost ledger&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;run tools or loop&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;memoryd&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;memories, knowledge base, hybrid search&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;hold a provider key (it embeds through the gateway)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;sandboxd&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;the Docker socket, one container per mission&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;connect to the database&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;sidecars&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;searxng, markitdown, ocr, pdfgen, whisper (opt-in)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;touch the database&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Internal APIs carry no auth, on purpose.&lt;/strong&gt; They publish no host ports. A shared secret would have to live in brain’s environment, exactly what the split assumes may be compromised, so the network is the boundary.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;sandboxd sits on its own network&lt;/strong&gt;, &lt;code&gt;timothy-sandbox&lt;/code&gt;, with brain as the only other member. Its API takes a mission ID, never an image, mount or container name, and its container runs read-only with every capability dropped.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The gap I accepted.&lt;/strong&gt; brain also holds the master key, because connectors, channels and delegated coding CLIs need credentials of their own. Every model call from Timothy’s own loop uses a key that exists only in the gateway, but brain is not key-free.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;challenge-3-where-does-state-live&quot;&gt;Challenge 3: where does state live?&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;One database, or the right store for each shape of data?&lt;/strong&gt;&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Option&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;How it works&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Why not (or why)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;A. A store per shape&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Postgres for rows, a vector database for embeddings, a broker for events&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Three backups, three failure modes, and a sync job between rows and vectors that will drift.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;B. A database per service&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Each service owns its own store&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;No shared transactions. brain and the gateway both write the cost ledger, for example.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;C. One Postgres with pgvector&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Every table in one database; vectors and full-text columns sit on the same rows as the text&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;One instance to keep healthy; when it is down, everything is.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;strong&gt;I chose C.&lt;/strong&gt; At one user’s scale Postgres is good enough at every job here, and one database means one backup and transactions that span what would otherwise be separate systems.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Vectors live beside their text.&lt;/strong&gt; &lt;code&gt;memories&lt;/code&gt; and &lt;code&gt;kb_chunks&lt;/code&gt; each carry a &lt;code&gt;vector(1024)&lt;/code&gt; column with an HNSW index and a generated &lt;code&gt;tsvector&lt;/code&gt; column, so hybrid search needs no sync job.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An inbox table instead of a broker.&lt;/strong&gt; A side effect that must survive a crash (a finished mission, a cron boundary, a webhook) goes into &lt;code&gt;events&lt;/code&gt; in the same transaction as its cause. A drainer delivers it after commit, with bounded retries.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Append-only where history matters.&lt;/strong&gt; &lt;code&gt;session_events&lt;/code&gt;, &lt;code&gt;mission_events&lt;/code&gt; and &lt;code&gt;memories&lt;/code&gt; are never updated in place; a correction is a new row.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;how-one-chat-request-flows&quot;&gt;How one chat request flows&lt;/h2&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/timothy/p1-chat-turn-flow.svg&quot; alt=&quot;Sequence of one chat turn across browser, brain, memoryd, gateway and provider&quot; title=&quot;Figure 3: One chat turn, from the browser to a provider and back.&quot;/&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The browser sends &lt;code&gt;POST /v1/sessions/{id}/messages&lt;/code&gt;; the web container’s nginx proxies &lt;code&gt;/v1&lt;/code&gt; to brain.&lt;/li&gt;
&lt;li&gt;brain claims the session’s single turn slot (a second request gets &lt;code&gt;409&lt;/code&gt;) and appends a &lt;code&gt;user_message&lt;/code&gt; event. The turn now belongs to the session, not the HTTP request: closing the tab does not stop it.&lt;/li&gt;
&lt;li&gt;brain compacts if the context passed 60% of the model’s window, then projects &lt;code&gt;session_events&lt;/code&gt; into model messages.&lt;/li&gt;
&lt;li&gt;memoryd embeds the query through the gateway and returns a fenced memory block of at most 1,500 tokens.&lt;/li&gt;
&lt;li&gt;brain assembles the system prompt: a stable prefix first, so provider prompt caches keep hitting, and per-turn blocks at the tail.&lt;/li&gt;
&lt;li&gt;The loop calls &lt;code&gt;POST /v1/stream&lt;/code&gt; on the gateway with a route name. The gateway resolves it to a provider chain, streams, and writes a &lt;code&gt;cost_ledger&lt;/code&gt; row per attempt.&lt;/li&gt;
&lt;li&gt;Normalized events flow to brain and on to the browser over SSE. Tool calls run in brain through the permission chain, then the loop calls again.&lt;/li&gt;
&lt;li&gt;brain appends the &lt;code&gt;assistant_turn&lt;/code&gt;. Distillation, memory extraction, a compaction check and a first-turn title run after the answer is durable.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;degrade-never-crash&quot;&gt;Degrade, never crash&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;What happens when a dependency is not there?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;One machine restarts in odd orders: Postgres comes up late, a sidecar is off, a provider is down. Every Go service serves &lt;code&gt;/health&lt;/code&gt; before its database is reachable. The pool reconnects with backoff, migrations retry, and &lt;code&gt;/health&lt;/code&gt; reports &lt;code&gt;degraded&lt;/code&gt; with a reason instead of the container restart-looping.&lt;/p&gt;
&lt;p&gt;Optional features follow the same rule: without the OCR sidecar a knowledge-base image gets no description rather than a failed ingest, and an unset &lt;code&gt;WHISPER_URL&lt;/code&gt; leaves transcription unmounted. Only configuration that cannot fix itself fails fast: a missing master key stops the gateway at boot.&lt;/p&gt;
&lt;h2 id=&quot;whats-next&quot;&gt;What’s next&lt;/h2&gt;
&lt;p&gt;Part 2 opens the gateway: providers as data, routes as roles, one event stream for every provider, and the bright line that decides when failover is still safe.&lt;/p&gt;</content:encoded><category>System Design</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Zero Trust in EKS: AWS IRSA &amp; Supply Chain Security - Least Privilege &amp; Trusted Images</title><link>https://www.sumonselim.com/zero-trust-eks-part4-irsa-supply-chain/</link><guid isPermaLink="true">https://www.sumonselim.com/zero-trust-eks-part4-irsa-supply-chain/</guid><description>Completing our Zero Trust in EKS series, this post focuses on securing North-South traffic using AWS IAM Roles for Service Accounts (IRSA) and establishing a robust software supply chain to ensure the integrity and trustworthiness of our container images.</description><pubDate>Mon, 12 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In the preceding posts of our Zero Trust in EKS series, we’ve established a strong foundation by implementing workload identity with SPIFFE/SPIRE for East-West communication and enforcing network isolation with Kubernetes Network Policies, alongside data protection using AWS KMS and Secrets Manager. Our final deep dive will focus on two equally critical aspects: securing &lt;strong&gt;North-South traffic&lt;/strong&gt; to AWS services using &lt;strong&gt;IAM Roles for Service Accounts (IRSA)&lt;/strong&gt; and fortifying our &lt;strong&gt;Software Supply Chain&lt;/strong&gt; to ensure that only trusted and verified code runs in our EKS clusters.&lt;/p&gt;
&lt;h2 id=&quot;cloud-identity-aws-irsa-for-least-privilege-access-to-aws-services&quot;&gt;Cloud Identity: AWS IRSA for Least-Privilege Access to AWS Services&lt;/h2&gt;
&lt;p&gt;While SPIFFE/SPIRE excels at securing communication &lt;em&gt;between&lt;/em&gt; workloads within the EKS cluster (East-West traffic), our applications often need to interact with external AWS services such as Amazon SQS, Amazon S3, or Amazon RDS. Traditionally, this was often handled by attaching an IAM role to the EC2 worker nodes, granting all pods on that node the permissions defined in the role. This approach, however, violates the principle of least privilege, as a compromised pod could inherit broad permissions, leading to a significant security breach.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;AWS IAM Roles for Service Accounts (IRSA)&lt;/strong&gt; revolutionizes this by allowing you to associate an IAM role directly with a Kubernetes Service Account. This means that only pods configured to use that specific service account can assume the IAM role, thereby gaining access to the AWS resources defined in the role’s policy. This provides granular, least-privilege access for your Kubernetes workloads to AWS services.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/irsa-authentication-flow.webp&quot; alt=&quot;AWS IRSA Authentication Flow: IAM Roles for Service Accounts&quot;/&gt;&lt;/p&gt;
&lt;h3 id=&quot;how-irsa-works&quot;&gt;How IRSA Works:&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;OIDC Provider:&lt;/strong&gt; EKS clusters are configured with an OpenID Connect (OIDC) identity provider. This provider allows Kubernetes service accounts to authenticate with AWS IAM.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Service Account Annotation:&lt;/strong&gt; A Kubernetes Service Account is annotated with the Amazon Resource Name (ARN) of an IAM role.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pod Token:&lt;/strong&gt; When a pod is launched using this service account, Kubernetes injects a projected service account token into the pod. This token is a JSON Web Token (JWT) signed by the EKS cluster’s OIDC provider.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;STS AssumeRoleWithWebIdentity:&lt;/strong&gt; The application within the pod (e.g., using an AWS SDK) can then use this JWT to call the AWS Security Token Service (STS) &lt;code&gt;AssumeRoleWithWebIdentity&lt;/code&gt; API operation. AWS STS validates the JWT against the EKS cluster’s OIDC provider.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Temporary Credentials:&lt;/strong&gt; If the JWT is valid and the IAM role’s trust policy allows it, AWS STS returns temporary AWS credentials (access key ID, secret access key, and session token) to the pod.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;AWS Resource Access:&lt;/strong&gt; The application uses these temporary credentials to access the AWS resources it needs, with permissions limited by the associated IAM role.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;irsa-in-our-zero-trust-eks-demo&quot;&gt;IRSA in our Zero Trust EKS Demo&lt;/h3&gt;
&lt;p&gt;In our &lt;a href=&quot;https://github.com/SumonMSelim/zero-trust-eks-demo&quot;&gt;URL Shortener Demo&lt;/a&gt;, the &lt;code&gt;worker&lt;/code&gt; service needs to interact with Amazon SQS to process messages, and the &lt;code&gt;url-service&lt;/code&gt; needs to retrieve database credentials from AWS Secrets Manager. Both services leverage IRSA to obtain the necessary permissions.&lt;/p&gt;
&lt;p&gt;Here’s how the &lt;code&gt;worker&lt;/code&gt; service account is configured to assume an IAM role:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;yaml&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;# zero-trust-eks-demo/kubernetes/identity/service-accounts.yaml&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;apiVersion&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;v1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;kind&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;ServiceAccount&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;metadata&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  name&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;worker&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  namespace&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;services&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  annotations&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    # This annotation links the Kubernetes Service Account to an AWS IAM Role.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    # The IAM Role ARN is typically provisioned via Terraform.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;    eks.amazonaws.com/role-arn&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;arn:aws:iam::&amp;lt;AWS_ACCOUNT_ID&amp;gt;:role/zero-trust-eks-worker-irsa&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The corresponding IAM role (&lt;code&gt;zero-trust-eks-worker-irsa&lt;/code&gt;) would have a trust policy allowing the EKS OIDC provider to assume it, and an inline policy granting only the necessary SQS permissions (e.g., &lt;code&gt;sqs:ReceiveMessage&lt;/code&gt;, &lt;code&gt;sqs:DeleteMessage&lt;/code&gt;) to its specific queue. This ensures that the &lt;code&gt;worker&lt;/code&gt; pod has the absolute minimum permissions required for its function, adhering strictly to the principle of least privilege for North-South traffic.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/irsa-least-privilege-config.webp&quot; alt=&quot;IRSA Configuration &amp;amp; Least Privilege: Service-to-Role Mapping&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;supply-chain-security-ensuring-trust-from-code-to-cluster&quot;&gt;Supply Chain Security: Ensuring Trust from Code to Cluster&lt;/h2&gt;
&lt;p&gt;Zero Trust principles extend beyond runtime security to encompass the entire software development lifecycle. A robust &lt;strong&gt;Software Supply Chain Security&lt;/strong&gt; strategy is crucial to prevent malicious code or vulnerabilities from ever reaching your production EKS cluster. This involves verifying the integrity and authenticity of all components, from source code to deployed container images.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/supply-chain-security-pipeline.webp&quot; alt=&quot;Supply Chain Security: Trust Starts Before Code Reaches EKS&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Key practices for securing your software supply chain in a Zero Trust EKS environment include:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Source Code Security:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Vulnerability Scanning:&lt;/strong&gt; Integrate tools like Snyk, Dependabot, or Trivy to scan your source code and dependencies for known vulnerabilities (CVEs) during development.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Static Application Security Testing (SAST):&lt;/strong&gt; Analyze source code for security flaws before compilation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Dynamic Application Security Testing (DAST):&lt;/strong&gt; Test running applications for vulnerabilities.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Container Image Security:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Image Scanning:&lt;/strong&gt; Scan container images for vulnerabilities, misconfigurations, and sensitive data &lt;em&gt;before&lt;/em&gt; pushing them to a registry. Tools like Trivy, Clair, or Amazon ECR’s built-in scanning can be used.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Minimal Base Images:&lt;/strong&gt; Use minimal, hardened base images to reduce the attack surface.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Image Signing:&lt;/strong&gt; Cryptographically sign your container images using tools like &lt;strong&gt;Sigstore/Cosign&lt;/strong&gt;. This provides an immutable record of who built the image and verifies its integrity.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Registry Security:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Private Registries:&lt;/strong&gt; Store images in private, secure registries like Amazon ECR.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Access Control:&lt;/strong&gt; Implement strict IAM policies to control who can push and pull images from the registry.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Admission Control in Kubernetes:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Policy Enforcement:&lt;/strong&gt; Use Kubernetes Admission Controllers to enforce policies that prevent unsigned or unapproved images from being deployed to your cluster. Tools like &lt;strong&gt;Kyverno&lt;/strong&gt; or &lt;strong&gt;Open Policy Agent (OPA) Gatekeeper&lt;/strong&gt; can validate incoming resources against predefined policies (e.g., requiring images to be signed and from a trusted registry before admission).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;By combining these supply chain security practices with the runtime protections covered in the previous posts — SPIFFE/SPIRE identity, Network Policies, and KMS encryption — we achieve a truly comprehensive Zero Trust posture that guards workloads from development all the way through to production execution.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/summary-zero-trust-eks-takeaways.webp&quot; alt=&quot;Summary &amp;amp; Key Takeaways: Building a Zero Trust EKS Cluster&quot;/&gt;&lt;/p&gt;
&lt;p&gt;This concludes our Zero Trust in EKS series. We’ve journeyed through the fundamental principles, workload identity, network isolation, data protection, cloud identity, and supply chain security — a layered, defense-in-depth approach that embodies the Zero Trust philosophy. The &lt;a href=&quot;https://github.com/SumonMSelim/zero-trust-eks-demo&quot;&gt;Zero Trust EKS Demo&lt;/a&gt; brings all these concepts together in a practical, deployable reference architecture.&lt;/p&gt;
&lt;p&gt;Feel free to share your thoughts, questions, or experiences implementing Zero Trust in your own Kubernetes environments in the comments below!&lt;/p&gt;</content:encoded><category>AWS</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Zero Trust in EKS: Network Isolation &amp; Data Protection - Default Deny &amp; Envelope Encryption</title><link>https://www.sumonselim.com/zero-trust-eks-part3-network-data-security/</link><guid isPermaLink="true">https://www.sumonselim.com/zero-trust-eks-part3-network-data-security/</guid><description>Beyond identity, a robust Zero Trust strategy for Amazon EKS demands stringent network isolation and comprehensive data protection. This post explores how to implement a &apos;Default Deny&apos; network posture using Kubernetes Network Policies and safeguard sensitive data with AWS KMS Envelope Encryption and AWS Secrets Manager.</description><pubDate>Sun, 11 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In our journey to build a Zero Trust architecture in Amazon EKS, we’ve already established the critical role of workload identity using SPIFFE/SPIRE for East-West communication. However, a truly resilient security posture requires multiple layers of defense. This post will delve into two more crucial layers: &lt;strong&gt;Network Isolation&lt;/strong&gt; through Kubernetes Network Policies and &lt;strong&gt;Data Protection&lt;/strong&gt; using AWS Key Management Service (KMS) and AWS Secrets Manager.&lt;/p&gt;
&lt;h2 id=&quot;network-layer-implementing-a-default-deny-posture-with-kubernetes-network-policies&quot;&gt;Network Layer: Implementing a “Default Deny” Posture with Kubernetes Network Policies&lt;/h2&gt;
&lt;p&gt;Even with strong workload identities, it’s prudent to enforce network-level controls to prevent unauthorized communication and limit the blast radius of a potential compromise. The principle of &lt;strong&gt;least privilege&lt;/strong&gt; extends to the network, meaning that workloads should only be able to communicate with the specific services they need, and nothing more.&lt;/p&gt;
&lt;p&gt;Kubernetes Network Policies are a powerful tool for achieving this micro-segmentation. They allow you to define rules that specify how pods are allowed to communicate with each other and with external network endpoints. A cornerstone of Zero Trust network security is the &lt;strong&gt;“Default Deny”&lt;/strong&gt; posture.&lt;/p&gt;
&lt;h3 id=&quot;the-default-deny-strategy&quot;&gt;The Default Deny Strategy&lt;/h3&gt;
&lt;p&gt;By applying a &lt;code&gt;NetworkPolicy&lt;/code&gt; that denies all ingress and egress traffic to a namespace, you create a secure baseline. No pod within that namespace can communicate with any other pod (inside or outside the namespace) or any external service unless explicitly allowed. This forces you to think critically about every communication path and explicitly define it.&lt;/p&gt;
&lt;p&gt;In our &lt;a href=&quot;https://github.com/SumonMSelim/zero-trust-eks-demo&quot;&gt;Zero Trust EKS Demo&lt;/a&gt;, we apply a &lt;code&gt;default-deny-all&lt;/code&gt; policy to the &lt;code&gt;services&lt;/code&gt; namespace:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;yaml&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;# zero-trust-eks-demo/kubernetes/network-policies/00-default-deny-all.yaml&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;apiVersion&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;networking.k8s.io/v1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;kind&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;NetworkPolicy&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;metadata&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  name&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;default-deny-all&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  namespace&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;services&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;spec&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  podSelector&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: {}&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  policyTypes&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    - &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;Ingress&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    - &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;Egress&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This policy, with an empty &lt;code&gt;podSelector&lt;/code&gt;, applies to all pods within the &lt;code&gt;services&lt;/code&gt; namespace. By specifying &lt;code&gt;policyTypes: [Ingress, Egress]&lt;/code&gt;, it ensures that both incoming and outgoing connections are blocked by default.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/namespace-network-policies-design.webp&quot; alt=&quot;Namespace Design &amp;amp; Network Policies: Default Deny with Explicit Allow Rules&quot;/&gt;&lt;/p&gt;
&lt;h3 id=&quot;explicitly-allowing-necessary-traffic&quot;&gt;Explicitly Allowing Necessary Traffic&lt;/h3&gt;
&lt;p&gt;Once the default deny is in place, you must create specific &lt;code&gt;NetworkPolicy&lt;/code&gt; resources to allow legitimate traffic flows. For instance, to enable communication from the &lt;code&gt;frontend&lt;/code&gt; application (in the &lt;code&gt;public&lt;/code&gt; namespace) to the &lt;code&gt;api-gateway&lt;/code&gt; (in the &lt;code&gt;services&lt;/code&gt; namespace) on TCP port 8000:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;yaml&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;# zero-trust-eks-demo/kubernetes/network-policies/01-allow-frontend-to-api-gateway.yaml&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;apiVersion&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;networking.k8s.io/v1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;kind&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;NetworkPolicy&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;metadata&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  name&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;allow-frontend-to-api-gateway&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  namespace&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;services&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; # This policy applies to pods in the &amp;#39;services&amp;#39; namespace&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;spec&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  podSelector&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;    matchLabels&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;      app&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;api-gateway&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; # Target: pods with label app: api-gateway&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  ingress&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    - &lt;/span&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;from&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        - &lt;/span&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;namespaceSelector&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;            matchLabels&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;              kubernetes.io/metadata.name&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;public&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; # Source: pods in &amp;#39;public&amp;#39; namespace&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;          podSelector&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;            matchLabels&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;              app&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;frontend&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; # Source: pods with label app: frontend&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;      ports&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        - &lt;/span&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;protocol&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;TCP&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;          port&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;8000&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; # Allowed port&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This policy explicitly permits ingress traffic to &lt;code&gt;api-gateway&lt;/code&gt; pods in the &lt;code&gt;services&lt;/code&gt; namespace, but only from &lt;code&gt;frontend&lt;/code&gt; pods in the &lt;code&gt;public&lt;/code&gt; namespace, and only on port 8000. All other ingress traffic to &lt;code&gt;api-gateway&lt;/code&gt; remains blocked. Similar policies are defined for other necessary communications, such as &lt;code&gt;api-gateway&lt;/code&gt; to &lt;code&gt;url-service&lt;/code&gt; (on port 8443, where mTLS is enforced), and egress rules for database or SQS access.&lt;/p&gt;
&lt;p&gt;Network Policy enforcement can be handled by the &lt;strong&gt;AWS VPC CNI&lt;/strong&gt; (with the Network Policy Agent enabled) or by third-party solutions like &lt;strong&gt;Cilium&lt;/strong&gt;, which offers advanced L7 policy capabilities and eBPF-based enforcement.&lt;/p&gt;
&lt;h2 id=&quot;data-layer-protecting-sensitive-data-with-encryption-and-secrets-management&quot;&gt;Data Layer: Protecting Sensitive Data with Encryption and Secrets Management&lt;/h2&gt;
&lt;p&gt;Even with robust identity and network controls, data itself must be protected. In a Zero Trust model, we assume that data stores could be compromised, making encryption at rest and in transit paramount. Furthermore, the management of sensitive credentials (secrets) requires a secure, dynamic approach.&lt;/p&gt;
&lt;h3 id=&quot;aws-kms-envelope-encryption-for-kubernetes-secrets&quot;&gt;AWS KMS Envelope Encryption for Kubernetes Secrets&lt;/h3&gt;
&lt;p&gt;Kubernetes Secrets, by default, are only Base64 encoded, not encrypted, and are stored in &lt;code&gt;etcd&lt;/code&gt;. This is a significant security risk. &lt;strong&gt;AWS KMS Envelope Encryption&lt;/strong&gt; provides a solution by encrypting your Kubernetes Secrets using a Customer Managed Key (CMK) in AWS KMS before they are written to &lt;code&gt;etcd&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/data-security-kms-secrets-manager.webp&quot; alt=&quot;Data Security: Secrets Encryption with AWS KMS and Secrets Manager&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Here’s how it works:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;When a Secret is created or updated, the EKS control plane generates a unique Data Encryption Key (DEK) for that Secret.&lt;/li&gt;
&lt;li&gt;The DEK is then encrypted by a CMK in AWS KMS (the Envelope Encryption).&lt;/li&gt;
&lt;li&gt;The encrypted DEK and the encrypted Secret data are stored in &lt;code&gt;etcd&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When the Secret is retrieved, the EKS control plane uses the CMK in KMS to decrypt the DEK, which then decrypts the Secret data.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This ensures that your sensitive data in &lt;code&gt;etcd&lt;/code&gt; is always encrypted with a key that you control in KMS, adding a crucial layer of protection against unauthorized access to the &lt;code&gt;etcd&lt;/code&gt; datastore.&lt;/p&gt;
&lt;h3 id=&quot;dynamic-secrets-management-with-aws-secrets-manager&quot;&gt;Dynamic Secrets Management with AWS Secrets Manager&lt;/h3&gt;
&lt;p&gt;Storing long-lived credentials directly in Kubernetes Secrets, even if encrypted by KMS, still presents challenges related to rotation, auditing, and least privilege. A more secure approach is to use a dedicated secrets management service like &lt;strong&gt;AWS Secrets Manager&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;AWS Secrets Manager allows you to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Store, manage, and retrieve database credentials, API keys, and other secrets securely.&lt;/li&gt;
&lt;li&gt;Automatically rotate secrets, reducing the risk of compromised long-lived credentials.&lt;/li&gt;
&lt;li&gt;Integrate with IAM to grant fine-grained access to secrets.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In our demo, the &lt;code&gt;url-service&lt;/code&gt; needs to connect to an RDS PostgreSQL database. Instead of hardcoding credentials or storing them in a static Kubernetes Secret, it retrieves them dynamically from AWS Secrets Manager at runtime. This is achieved by leveraging &lt;strong&gt;AWS IRSA&lt;/strong&gt; (IAM Roles for Service Accounts), which we will cover in detail in the next post.&lt;/p&gt;
&lt;p&gt;Here’s a snippet from the &lt;code&gt;url-service&lt;/code&gt; (Go) showing how it fetches database credentials from Secrets Manager:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;go&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// apps/url-service/main.go&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;func&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; buildDbURI&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;ctx&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt; context&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;Context&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) (&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;string&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;error&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    secretArn &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; os.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Getenv&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;DB_SECRET_ARN&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// ARN of the secret in Secrets Manager&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; secretArn &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;        return&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, errors.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;New&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;DB_SECRET_ARN environment variable not set&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Load AWS configuration (credentials are provided via IRSA)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    cfg, err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; config.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;LoadDefaultConfig&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ctx)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; nil&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;        return&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, fmt.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Errorf&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;failed to load AWS config: &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%w&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, err)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Create a Secrets Manager client&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    sm &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; secretsmanager.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;NewFromConfig&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(cfg)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Retrieve the secret value&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    out, err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; sm.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;GetSecretValue&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ctx, &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;secretsmanager&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;GetSecretValueInput&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;{SecretId: &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;secretArn})&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; nil&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;        // Handle errors like ResourceNotFoundException&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;        return&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, fmt.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Errorf&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;failed to get secret value for &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%s&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%w&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, secretArn, err)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Parse the secret string (assumed to be JSON)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    var&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; sec &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;dbSecret&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; json.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Unmarshal&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;([]&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;byte&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;out.SecretString), &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;sec); err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; nil&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;        return&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, fmt.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Errorf&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;failed to parse secret JSON: &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%w&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, err)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Construct the PostgreSQL connection URI&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; fmt.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Sprintf&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;postgres://&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%s&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%s&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;@&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%s&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;:&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%d&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%s&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, sec.Username, sec.Password, sec.Host, sec.Port, sec.Database), &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;nil&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This approach ensures that database credentials are never exposed in plaintext, are dynamically retrieved, and are managed with least privilege, significantly enhancing the data security posture.&lt;/p&gt;
&lt;h2 id=&quot;the-synergy-of-layers&quot;&gt;The Synergy of Layers&lt;/h2&gt;
&lt;p&gt;The combination of Network Policies, KMS Envelope Encryption, and AWS Secrets Manager creates a powerful defense-in-depth strategy:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Security Control&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Layer&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Benefit in Zero Trust EKS&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Kubernetes Network Policies&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Network (L3/L4)&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Enforces micro-segmentation, prevents unauthorized lateral movement, and reduces attack surface by blocking all traffic by default.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;AWS KMS Envelope Encryption&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Data at Rest&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Protects sensitive Kubernetes Secrets stored in &lt;code&gt;etcd&lt;/code&gt; with customer-managed keys, even if &lt;code&gt;etcd&lt;/code&gt; is compromised.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;AWS Secrets Manager&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Data Access&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Provides dynamic, least-privilege access to credentials, enabling automated rotation and reducing the risk of hardcoded secrets.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;By meticulously implementing these controls, we move closer to a comprehensive Zero Trust environment where every interaction, whether network-based or data-related, is explicitly verified and secured. In our final post, we will complete our Zero Trust EKS series by exploring &lt;strong&gt;AWS IRSA&lt;/strong&gt; for secure North-South communication and the crucial aspects of &lt;strong&gt;Supply Chain Security&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;What are your thoughts on implementing network policies and managing secrets in EKS? Share your experiences in the comments below!&lt;/p&gt;</content:encoded><category>AWS</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Zero Trust in EKS: Workload Identity with SPIFFE/SPIRE - The New Firewall</title><link>https://www.sumonselim.com/zero-trust-eks-part2-spiffe-spire-identity/</link><guid isPermaLink="true">https://www.sumonselim.com/zero-trust-eks-part2-spiffe-spire-identity/</guid><description>In a Zero Trust architecture, relying on network location for security is a relic of the past. This post delves into how SPIFFE/SPIRE provides cryptographically verifiable identities to workloads in Amazon EKS, enabling robust mutual TLS for East-West communication.</description><pubDate>Sat, 10 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In the previous installment of our Zero Trust in EKS series, we established that the traditional perimeter model is obsolete in dynamic cloud-native environments. We highlighted that &lt;strong&gt;identity is the new firewall&lt;/strong&gt;, emphasizing the need to verify every access request regardless of its origin. This post will dive deeper into how we achieve this workload identity for East-West (service-to-service) communication within our EKS cluster using &lt;strong&gt;SPIFFE&lt;/strong&gt; and &lt;strong&gt;SPIRE&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/identity-foundation-east-west-north-south.webp&quot; alt=&quot;Identity Foundation: Workload Identity (East-West) and Cloud Identity (North-South)&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;the-challenge-of-workload-identity-in-kubernetes&quot;&gt;The Challenge of Workload Identity in Kubernetes&lt;/h2&gt;
&lt;p&gt;Kubernetes pods are inherently ephemeral and dynamic. They are frequently created, destroyed, and rescheduled, leading to constantly changing IP addresses. This fluidity makes traditional IP-based security mechanisms, such as network ACLs or security groups, difficult to manage and prone to misconfiguration when applied at the workload level. Furthermore, relying solely on network-level controls doesn’t provide cryptographic proof of a workload’s identity, leaving systems vulnerable to IP spoofing or compromised network segments.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;SPIFFE&lt;/strong&gt; (Secure Production Identity Framework for Everyone) addresses this challenge by providing a universal, cryptographically verifiable identity to every software workload. &lt;strong&gt;SPIRE&lt;/strong&gt; (SPIFFE Runtime Environment) is the production-ready implementation of the SPIFFE specification, acting as an identity control plane that issues and manages these identities.&lt;/p&gt;
&lt;h2 id=&quot;how-spiffespire-establishes-trust&quot;&gt;How SPIFFE/SPIRE Establishes Trust&lt;/h2&gt;
&lt;p&gt;The core concept behind SPIFFE/SPIRE is to move from &lt;strong&gt;network-based trust&lt;/strong&gt; to &lt;strong&gt;cryptographic identity&lt;/strong&gt;. Each workload receives a unique &lt;strong&gt;SPIFFE ID&lt;/strong&gt;, a URI that uniquely identifies a workload within a trust domain (e.g., &lt;code&gt;spiffe://your-trust-domain.com/ns/namespace/sa/service-account-name&lt;/code&gt;). Along with this ID, the workload is issued a &lt;strong&gt;SPIFFE Verifiable Identity Document (SVID)&lt;/strong&gt;, typically an X.509 certificate, which serves as its cryptographic passport.&lt;/p&gt;
&lt;p&gt;The process generally involves:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Workload Attestation:&lt;/strong&gt; The SPIRE Agent, running on each node, attests the identity of the underlying node (e.g., using AWS EC2 instance metadata). It then attests the identity of the workloads running on that node (e.g., using Kubernetes service account tokens, pod labels, or namespaces).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SVID Issuance:&lt;/strong&gt; Based on pre-defined &lt;strong&gt;Registration Entries&lt;/strong&gt; (which map workload attributes to SPIFFE IDs), the SPIRE Server issues an SVID to the SPIRE Agent. The Agent then delivers this SVID to the workload via the Workload API.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;mTLS Communication:&lt;/strong&gt; Workloads use their SVIDs to establish mutual TLS (mTLS) connections. During the TLS handshake, both the client and server present their SVIDs, allowing them to cryptographically verify each other’s identity and authorize access based on their SPIFFE IDs.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/spiffe-spire-identity-issuance-flow.webp&quot; alt=&quot;How SPIFFE Connects to SPIRE: Workload Identity Issuance Flow&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;implementing-spiffespire-in-our-zero-trust-eks-demo&quot;&gt;Implementing SPIFFE/SPIRE in our Zero Trust EKS Demo&lt;/h2&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/url-shortener-demo-architecture.webp&quot; alt=&quot;URL Shortener Demo Architecture&quot;/&gt;&lt;/p&gt;
&lt;p&gt;In our &lt;a href=&quot;https://github.com/SumonMSelim/zero-trust-eks-demo&quot;&gt;URL Shortener Demo&lt;/a&gt;, we have an &lt;code&gt;api-gateway&lt;/code&gt; service (built with Laravel) that needs to securely communicate with a &lt;code&gt;url-service&lt;/code&gt; (built with Go). Instead of relying on network policies alone, we enforce mTLS using SPIFFE/SPIRE.&lt;/p&gt;
&lt;h3 id=&quot;1-defining-service-accounts-and-registration-entries&quot;&gt;1. Defining Service Accounts and Registration Entries&lt;/h3&gt;
&lt;p&gt;First, we define Kubernetes Service Accounts for our &lt;code&gt;api-gateway&lt;/code&gt; and &lt;code&gt;url-service&lt;/code&gt; in the &lt;code&gt;services&lt;/code&gt; namespace. These service accounts are then used in SPIRE Registration Entries to define their unique SPIFFE IDs.&lt;/p&gt;
&lt;p&gt;For the &lt;code&gt;url-service&lt;/code&gt;, a simplified registration entry might look like this:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;yaml&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;# kubernetes/identity/spire-registration-entries.yaml (conceptual example)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;apiVersion&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;spire.spiffe.io/v1alpha1&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;kind&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;ClusterRegistrationEntry&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;metadata&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  name&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;url-service-entry&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;spec&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  spiffeId&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;spiffe://mol.la/ns/services/sa/url-service&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  parentID&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;: &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;spiffe://mol.la/spire/agent&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; # The SPIRE Agent&amp;#39;s ID&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#22863A;--shiki-dark:#7EE787&quot;&gt;  selectors&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;:&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    - &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;k8s:container-image:url-service&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; # Example: Select by container image&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    - &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;k8s:namespace:services&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    - &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;k8s:pod-label:app:url-service&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    - &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;k8s:serviceaccount:url-service&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;  # Other selectors like k8s:pod-uid, k8s:node-name can also be used&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This entry tells SPIRE that any workload running in the &lt;code&gt;services&lt;/code&gt; namespace with the &lt;code&gt;url-service&lt;/code&gt; service account should be issued the SPIFFE ID &lt;code&gt;spiffe://mol.la/ns/services/sa/url-service&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/spiffe-spire-attestation-flow.webp&quot; alt=&quot;SPIFFE/SPIRE Attestation Flow: How api-gateway Gets Its Identity&quot;/&gt;&lt;/p&gt;
&lt;h3 id=&quot;2-workload-integration-the-url-service-go&quot;&gt;2. Workload Integration: The &lt;code&gt;url-service&lt;/code&gt; (Go)&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;url-service&lt;/code&gt; acts as the mTLS server. It uses the &lt;code&gt;go-spiffe&lt;/code&gt; library to obtain its SVID from the local SPIRE Agent and configure its TLS server to require and validate client SVIDs.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;go&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// apps/url-service/main.go&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;func&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; buildTLSConfig&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#E36209;--shiki-dark:#FFA657&quot;&gt;ctx&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt; context&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;Context&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;) &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;*&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;tls&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;Config&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // The SPIRE Agent exposes its Workload API via a Unix Domain Socket.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // The environment variable SPIFFE_ENDPOINT_SOCKET typically points to this.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    socket &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; os.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Getenv&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;SPIFFE_ENDPOINT_SOCKET&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; socket &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;==&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        socket &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;unix:///spire/sockets/agent.sock&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt; // Default path in our setup&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Create an X509Source to fetch SVIDs and trusted CAs from the SPIRE Agent.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // This source automatically refreshes certificates.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    source, err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; workloadapi.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;NewX509Source&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ctx, workloadapi.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;WithClientOptions&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(workloadapi.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;WithAddr&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(socket)))&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; nil&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        log.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Fatalf&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;Failed to create X509Source: &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%v&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, err)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Store globally for an identity endpoint (for demonstration/debugging)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    globalX509Source &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; source&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Define the expected SPIFFE ID of the authorized client (api-gateway).&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // The url-service will only accept connections from this specific identity.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    authorizedID &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; spiffeid.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;RequireFromString&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;spiffe://mol.la/ns/services/sa/api-gateway&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Create an mTLS server TLS configuration using the SPIFFE X509Source.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // The AuthorizeID option ensures that only clients with the specified SPIFFE ID are allowed.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    tlsConfig &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; tlsconfig.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;MTLSServerConfig&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        source,                              &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// Our own identity (server&amp;#39;s SVID)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        source,                              &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// Trust bundle for validating peer (client) SVIDs&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        tlsconfig.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;AuthorizeID&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(authorizedID), &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// Authorization rule: only api-gateway is allowed&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    )&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    return&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; tlsConfig&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;func&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt; main&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;() {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // ... database initialization and other setup ...&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    srv &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; &amp;amp;&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;http&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;Server&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;{&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        Addr:      &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;:8443&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;// Listen on port 8443 for mTLS traffic&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        Handler:   api,&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        TLSConfig: &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;buildTLSConfig&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(ctx),&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    log.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Printf&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;url-service listening mTLS on :8443&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6A737D;--shiki-dark:#8B949E&quot;&gt;    // Start the mTLS server. The key and cert files are managed by the TLSConfig.&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;    if&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;:=&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; srv.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;ListenAndServeTLS&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;); err &lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;!=&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; nil&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;        log.&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#D2A8FF&quot;&gt;Fatalf&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;mTLS server error: &lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;%v&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;, err)&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;3-workload-integration-the-api-gateway-laravelphp&quot;&gt;3. Workload Integration: The &lt;code&gt;api-gateway&lt;/code&gt; (Laravel/PHP)&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;api-gateway&lt;/code&gt; acts as the mTLS client. While the demo uses Laravel (PHP), the principle remains the same: the client obtains its SVID from the SPIRE Agent and uses it to establish an mTLS connection to the &lt;code&gt;url-service&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For a Go client, the setup would be similar to the server, but using &lt;code&gt;tlsconfig.MTLSClientConfig&lt;/code&gt; and specifying the server’s expected SPIFFE ID for authorization.&lt;/p&gt;
&lt;h2 id=&quot;benefits-of-spiffespire-for-zero-trust-in-eks&quot;&gt;Benefits of SPIFFE/SPIRE for Zero Trust in EKS&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Strong Workload Identity:&lt;/strong&gt; Each workload has a cryptographically verifiable identity, independent of network location or IP address.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Automated Certificate Management:&lt;/strong&gt; SPIRE handles the issuance, rotation, and revocation of SVIDs, reducing operational overhead and improving security posture.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fine-grained Authorization:&lt;/strong&gt; Services can authorize incoming connections based on the client’s SPIFFE ID, enabling precise access control at the application layer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Defense in Depth:&lt;/strong&gt; Even if network controls are bypassed, mTLS ensures that only authorized workloads can communicate, preventing unauthorized lateral movement.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;No Sidecar Proxy Overhead:&lt;/strong&gt; Unlike some service mesh implementations, SPIFFE/SPIRE can be integrated directly into applications, avoiding the overhead of a sidecar proxy if desired.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By implementing SPIFFE/SPIRE, we’ve established a robust identity layer for our EKS workloads, ensuring that all East-West communication is authenticated and authorized based on cryptographic identities. In the next post, we will explore how &lt;strong&gt;Kubernetes Network Policies&lt;/strong&gt; provide a crucial network layer of defense and how we protect sensitive data with &lt;strong&gt;KMS Envelope Encryption&lt;/strong&gt; and &lt;strong&gt;AWS Secrets Manager&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Feel free to leave your questions or insights on workload identity and mTLS in the comments below!&lt;/p&gt;</content:encoded><category>AWS</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Zero Trust in EKS: Beyond the Perimeter Model - An Introduction</title><link>https://www.sumonselim.com/zero-trust-eks-part1-beyond-perimeter/</link><guid isPermaLink="true">https://www.sumonselim.com/zero-trust-eks-part1-beyond-perimeter/</guid><description>The traditional perimeter-based security model is no longer sufficient for modern cloud-native applications, especially within dynamic environments like Amazon EKS. This post introduces the fundamental principles of Zero Trust, its critical importance in Kubernetes, and the five core pillars that form a robust security architecture.</description><pubDate>Fri, 09 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;In the era of monolithic applications and on-premise data centers, security strategies often revolved around a &lt;strong&gt;perimeter-based model&lt;/strong&gt;. This approach, frequently likened to a castle-and-moat defense, assumed that everything inside the network was trustworthy, while anything outside was inherently hostile. Firewalls and intrusion detection systems guarded the network’s edge, creating a hard shell around a soft interior.&lt;/p&gt;
&lt;p&gt;However, the advent of cloud-native architectures, microservices, and container orchestration platforms like &lt;strong&gt;Amazon Elastic Kubernetes Service (EKS)&lt;/strong&gt; has fundamentally reshaped the threat landscape. In these dynamic environments, the traditional perimeter has dissolved. Workloads are &lt;strong&gt;ephemeral&lt;/strong&gt;, with pods constantly being created, scaled, and terminated, leading to ever-changing IP addresses. The network within Kubernetes is often &lt;strong&gt;flat&lt;/strong&gt;, meaning pods can communicate freely by default, blurring the lines between trusted and untrusted zones. In this new reality, &lt;strong&gt;identity is the new firewall&lt;/strong&gt;, and a new security paradigm is required: &lt;strong&gt;Zero Trust&lt;/strong&gt;.&lt;/p&gt;
&lt;h2 id=&quot;why-the-perimeter-model-fails-in-eks&quot;&gt;Why the Perimeter Model Fails in EKS&lt;/h2&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/perimeter-model-collapsed.webp&quot; alt=&quot;Why Zero Trust Exists: The Perimeter Model Has Collapsed&quot;/&gt;&lt;/p&gt;
&lt;p&gt;The shift to Kubernetes introduces several challenges that render the traditional perimeter model ineffective:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Flat Network:&lt;/strong&gt; By default, Kubernetes allows any pod to communicate with any other pod. This open communication model, while flexible, creates a vast attack surface if not properly secured.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Ephemeral IPs:&lt;/strong&gt; Pods are assigned dynamic IP addresses that change frequently. Relying on static IP-based firewall rules becomes impractical and brittle.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shared Kernel:&lt;/strong&gt; All containers on a node share the same underlying operating system kernel. A compromise in one container could potentially impact others on the same node, increasing the blast radius.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Complex Configuration:&lt;/strong&gt; Securing Kubernetes often involves intricate YAML configurations for various resources, increasing the risk of misconfigurations that can lead to security vulnerabilities.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/kubernetes-zero-trust-challenges.webp&quot; alt=&quot;Zero Trust Challenges in Kubernetes&quot;/&gt;&lt;/p&gt;
&lt;p&gt;These challenges necessitate a security approach that doesn’t implicitly trust any entity, regardless of its network location. This is the core tenet of Zero Trust.&lt;/p&gt;
&lt;h2 id=&quot;introduction-to-zero-trust-never-trust-always-verify&quot;&gt;Introduction to Zero Trust: Never Trust, Always Verify&lt;/h2&gt;
&lt;p&gt;Zero Trust is a strategic cybersecurity model that operates on the principle of &lt;strong&gt;“Never Trust, Always Verify.”&lt;/strong&gt; It mandates that every user, device, application, and workload attempting to access resources must be authenticated, authorized, and continuously validated before being granted access, and access should be limited to the absolute minimum required.&lt;/p&gt;
&lt;p&gt;The foundational principles of Zero Trust include:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Explicit Verification:&lt;/strong&gt; All access requests must be explicitly verified based on all available data points, including user identity, device posture, location, service being accessed, and data sensitivity. This moves beyond simple network location as a trust indicator.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Least Privilege Access:&lt;/strong&gt; Access is granted on a “need-to-know” and “least-privilege” basis. This often involves Just-In-Time (JIT) and Just-Enough-Access (JEA) principles, ensuring that entities only have the permissions necessary for their current task and for a limited duration.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Assume Breach:&lt;/strong&gt; Organizations must operate under the assumption that a breach is inevitable or has already occurred. This mindset drives the design of security controls that minimize the “blast radius” of a compromise and prevent lateral movement within the network.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/zero-trust-principles.webp&quot; alt=&quot;Introduction to Zero Trust: Never Trust, Always Verify&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;the-five-core-pillars-of-zero-trust-in-eks&quot;&gt;The Five Core Pillars of Zero Trust in EKS&lt;/h2&gt;
&lt;p&gt;Implementing Zero Trust in an EKS environment requires a holistic approach, addressing security across multiple dimensions. The following five pillars provide a comprehensive framework:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Pillar&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Focus Area&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Relevance in EKS&lt;/th&gt;
&lt;th style=&quot;text-align:left&quot;&gt;Example Implementation&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Identity&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Verifying the identity of users and workloads.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Critical for authenticating pods, service accounts, and human users accessing the cluster or applications.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;SPIFFE/SPIRE&lt;/strong&gt; for workload identity, &lt;strong&gt;AWS IRSA&lt;/strong&gt; for cloud identity, IAM for user identity.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Device/Workload&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Ensuring the security posture of devices and containerized workloads.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Securing container images, runtime protection, and ensuring only authorized workloads run.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;mTLS&lt;/strong&gt; between services, &lt;strong&gt;Image Scanning&lt;/strong&gt; (e.g., Trivy, Clair), &lt;strong&gt;Admission Controllers&lt;/strong&gt; (e.g., Kyverno, OPA).&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Network&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Micro-segmentation and secure communication channels.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Isolating pods and namespaces, encrypting traffic, and controlling ingress/egress.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Kubernetes Network Policies&lt;/strong&gt; (e.g., AWS VPC CNI, Cilium), &lt;strong&gt;mTLS&lt;/strong&gt; for encrypted communication.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Application&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Securing applications and APIs.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Protecting APIs from unauthorized access, ensuring secure coding practices, and runtime application self-protection.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;API Gateway&lt;/strong&gt; security, Web Application Firewalls (WAF), secure API design.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;Data&lt;/strong&gt;&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Protecting sensitive data at rest and in transit.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;Encrypting secrets, databases, and storage volumes.&lt;/td&gt;
&lt;td style=&quot;text-align:left&quot;&gt;&lt;strong&gt;AWS KMS Envelope Encryption&lt;/strong&gt; for Kubernetes Secrets, &lt;strong&gt;AWS Secrets Manager&lt;/strong&gt; for dynamic credentials, database encryption.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/five-pillars-zero-trust.webp&quot; alt=&quot;Five Core Pillars of Zero Trust&quot;/&gt;&lt;/p&gt;
&lt;h2 id=&quot;defense-in-depth-a-layered-security-model&quot;&gt;Defense in Depth: A Layered Security Model&lt;/h2&gt;
&lt;p&gt;Our &lt;a href=&quot;https://github.com/SumonMSelim/zero-trust-eks-demo&quot;&gt;Zero Trust EKS Demo&lt;/a&gt; exemplifies a &lt;strong&gt;defense-in-depth&lt;/strong&gt; strategy, where multiple security layers are implemented to provide comprehensive protection. This layered approach ensures that even if one control fails, others are in place to prevent or mitigate a breach.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/zero-trust-eks/defense-in-depth-layered-model.webp&quot; alt=&quot;Zero Trust Layered Security Model: Defense in Depth Strategy&quot;/&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identity Layer (L7):&lt;/strong&gt; Utilizing &lt;strong&gt;SPIFFE/SPIRE&lt;/strong&gt; to assign cryptographically verifiable identities to workloads, enabling mutual TLS (mTLS) for secure service-to-service communication.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Network Layer (L3/L4):&lt;/strong&gt; Implementing a &lt;strong&gt;“Default Deny”&lt;/strong&gt; posture with &lt;strong&gt;Kubernetes Network Policies&lt;/strong&gt; to strictly control traffic flow between pods and namespaces.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cloud Identity Layer:&lt;/strong&gt; Leveraging &lt;strong&gt;AWS IRSA&lt;/strong&gt; (IAM Roles for Service Accounts) to grant fine-grained, least-privilege access to AWS resources for specific Kubernetes service accounts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data Protection Layer:&lt;/strong&gt; Employing &lt;strong&gt;AWS KMS&lt;/strong&gt; for envelope encryption of Kubernetes secrets and &lt;strong&gt;AWS Secrets Manager&lt;/strong&gt; for dynamic management of database credentials.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Supply Chain Security:&lt;/strong&gt; Ensuring the integrity of container images through scanning, signing, and admission control.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This multi-faceted approach significantly enhances the security posture of applications deployed on EKS. In the next post of this series, we will dive deep into the &lt;strong&gt;Identity Foundation&lt;/strong&gt; and explore how &lt;strong&gt;SPIFFE/SPIRE&lt;/strong&gt; replaces traditional IP-based trust with robust cryptographic identities for East-West traffic within your EKS cluster.&lt;/p&gt;
&lt;p&gt;Stay tuned for a deeper dive into the technical implementations! If you have any initial thoughts or questions on the Zero Trust philosophy in EKS, feel free to share them in the comments below.&lt;/p&gt;</content:encoded><category>AWS</category><author>Muhammad Sumon Molla Selim</author></item><item><title>My Journey as an AWS Community Builder: Benefits, How to Apply, and What to Expect</title><link>https://www.sumonselim.com/my-journey-as-an-aws-community-builder-benefits-how-to-apply-and-what-to-expect/</link><guid isPermaLink="true">https://www.sumonselim.com/my-journey-as-an-aws-community-builder-benefits-how-to-apply-and-what-to-expect/</guid><description>Becoming part of the AWS Community Builders program has been one of the best decisions in my cloud career. I’m now in my third year…</description><pubDate>Fri, 12 Dec 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/my-journey-as-an-aws-community-builder-benefits-how-to-apply-and-what-to-expect/cb.webp&quot; alt=&quot;AWS Community Builders from Netherlands&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Becoming part of the &lt;a href=&quot;https://builder.aws.com/community/community-builders&quot;&gt;&lt;strong&gt;AWS Community Builders&lt;/strong&gt;&lt;/a&gt; program has been one of the best decisions in my cloud career. I’m now in my &lt;strong&gt;third year&lt;/strong&gt; in the program, and the experience has been rewarding both personally and professionally. When I first applied, I did not fully understand how impactful it would be—yet today I’ve used the program to attend &lt;a href=&quot;https://www.facebook.com/SumonMSelim/posts/pfbid0anh8jvWGG9ic7JXsHpsSyi9F8k39VxjXUGbby2bcomK1j7D6cTVLtHibti36KsDCl&quot;&gt;&lt;strong&gt;AWS re:Invent 2024&lt;/strong&gt;&lt;/a&gt;, taken multiple certifications using &lt;strong&gt;free exam vouchers&lt;/strong&gt;, and used the &lt;strong&gt;CloudAcademy subscription&lt;/strong&gt; to keep learning and practicing new AWS services.&lt;/p&gt;
&lt;p&gt;In this post, I will share:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What the AWS Community Builders (CB) program is&lt;/li&gt;
&lt;li&gt;The benefits you actually get&lt;/li&gt;
&lt;li&gt;My experience over three years&lt;/li&gt;
&lt;li&gt;How to prepare and apply successfully&lt;/li&gt;
&lt;li&gt;Tips to stand out when applying&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;what-is-the-aws-community-builders-program&quot;&gt;What is the AWS Community Builders Program?&lt;/h2&gt;
&lt;p&gt;The AWS Community Builders program is AWS’s initiative to support and recognize passionate community members who contribute through blogging, workshops, open-source projects, social media content, and public knowledge sharing.&lt;/p&gt;
&lt;p&gt;The program runs for one year and gives members access to AWS experts, technical learning, and exclusive resources that help them grow. Members can select a specialty track such as:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Serverless&lt;/li&gt;
&lt;li&gt;Security&lt;/li&gt;
&lt;li&gt;Containers&lt;/li&gt;
&lt;li&gt;Machine Learning&lt;/li&gt;
&lt;li&gt;Networking&lt;/li&gt;
&lt;li&gt;Databases&lt;/li&gt;
&lt;li&gt;Developer Tools&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I have been part of the DevTools category.&lt;/p&gt;
&lt;h2 id=&quot;my-experience-as-a-three-year-aws-community-builder&quot;&gt;My Experience as a Three-Year AWS Community Builder&lt;/h2&gt;
&lt;h3 id=&quot;1-attending-aws-reinvent-2024&quot;&gt;1. Attending AWS re:Invent 2024&lt;/h3&gt;
&lt;p&gt;One of my favorite experiences was attending AWS re:Invent 2024. Being part of the CB program made it easier to engage with AWS product teams, other builders, and global community members.&lt;/p&gt;
&lt;h3 id=&quot;2-using-free-aws-certification-vouchers&quot;&gt;2. Using Free AWS Certification Vouchers&lt;/h3&gt;
&lt;p&gt;Each year, CBs receive a &lt;strong&gt;free certification voucher&lt;/strong&gt; and &lt;strong&gt;discounted vouchers&lt;/strong&gt;from different events, which makes it easier to pursue more certifications without the financial burden.&lt;/p&gt;
&lt;h3 id=&quot;3-cloudacademy-subscription&quot;&gt;3. CloudAcademy Subscription&lt;/h3&gt;
&lt;p&gt;The free annual &lt;strong&gt;CloudAcademy subscription&lt;/strong&gt; is one of the benefits I use the most. It helps me practice real labs, prepare for exams, and learn new AWS features hands-on.&lt;/p&gt;
&lt;h3 id=&quot;4-technical-sessions-with-aws-teams&quot;&gt;4. Technical Sessions with AWS Teams&lt;/h3&gt;
&lt;p&gt;Community Builders get exclusive deep-dive sessions with AWS product teams—these are not public webinars, but technical, focused sessions where we get to ask questions and understand upcoming improvements.&lt;/p&gt;
&lt;h3 id=&quot;5-networking-with-builders-worldwide&quot;&gt;5. Networking With Builders Worldwide&lt;/h3&gt;
&lt;p&gt;The private Slack community is active, helpful, and global. I have connected with engineers, architects, and experts from different countries, collaborated on content, and learned a lot from community discussions.&lt;/p&gt;
&lt;h2 id=&quot;swag-you-receive-yes-its-awesome&quot;&gt;Swag You Receive (Yes, It’s Awesome)&lt;/h2&gt;
&lt;p&gt;You also get a welcome package each year. Below are photos of the swag I received in last three years:&lt;/p&gt;
&lt;div class=&quot;grid gap-3 my-6 grid-cols-2&quot;&gt;&lt;button class=&quot;group relative rounded-lg overflow-hidden border border-border bg-card cursor-pointer transition-transform duration-200 hover:scale-[1.02] motion-reduce:transition-none aspect-[4/3]&quot;&gt;&lt;img src=&quot;https://www.sumonselim.com/_astro/1st-year-AWS-CB-swag.DRNYZ_yq_sPwg7.webp&quot; alt=&quot;AWS Community Builder swag year 1&quot; class=&quot;w-full h-full object-cover transition-all duration-300 group-hover:brightness-110&quot; loading=&quot;lazy&quot;/&gt;&lt;div class=&quot;absolute inset-0 bg-gradient-to-t from-background/70 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-end p-3&quot;&gt;&lt;span class=&quot;font-mono text-xs text-foreground truncate&quot;&gt;AWS Community Builder swag year 1&lt;/span&gt;&lt;/div&gt;&lt;/button&gt;&lt;button class=&quot;group relative rounded-lg overflow-hidden border border-border bg-card cursor-pointer transition-transform duration-200 hover:scale-[1.02] motion-reduce:transition-none aspect-[4/3]&quot;&gt;&lt;img src=&quot;https://www.sumonselim.com/_astro/2nd-year-AWS-CB-swag.DuXfEcuq_Z7BDJJ.webp&quot; alt=&quot;AWS Community Builder swag year 2 (the backpack)&quot; class=&quot;w-full h-full object-cover transition-all duration-300 group-hover:brightness-110&quot; loading=&quot;lazy&quot;/&gt;&lt;div class=&quot;absolute inset-0 bg-gradient-to-t from-background/70 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-end p-3&quot;&gt;&lt;span class=&quot;font-mono text-xs text-foreground truncate&quot;&gt;AWS Community Builder swag year 2 (the backpack)&lt;/span&gt;&lt;/div&gt;&lt;/button&gt;&lt;/div&gt;&lt;!--astro:end--&gt;
&lt;p&gt;&lt;strong&gt;Note: I won the Meta Ray-Ban glass at the AWS re:Invent 2024 event in a giveaway.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/my-journey-as-an-aws-community-builder-benefits-how-to-apply-and-what-to-expect/3rd-year-AWS-CB-swag.webp&quot; alt=&quot;AWS Community Builder swag year 3&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Typically, the swag includes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Cap&lt;/li&gt;
&lt;li&gt;T-shirt or banner&lt;/li&gt;
&lt;li&gt;Stickers&lt;/li&gt;
&lt;li&gt;Notebook&lt;/li&gt;
&lt;li&gt;Water bottle&lt;/li&gt;
&lt;li&gt;Patches or pins&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The swags do not define the program, but they definitely make it feel special.&lt;/p&gt;
&lt;h2 id=&quot;benefits-of-the-aws-community-builders-program&quot;&gt;Benefits of the AWS Community Builders Program&lt;/h2&gt;
&lt;h3 id=&quot;1-technical-enablement&quot;&gt;1. Technical Enablement&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Deep-dive technical sessions&lt;/li&gt;
&lt;li&gt;Live Q&amp;amp;A with AWS product managers&lt;/li&gt;
&lt;li&gt;Early access learning materials&lt;/li&gt;
&lt;li&gt;Service roadmap insights&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;2-aws-credits&quot;&gt;2. AWS Credits&lt;/h3&gt;
&lt;p&gt;Many CBs receive AWS credits to support tutorials, blog posts, and demos.&lt;/p&gt;
&lt;h3 id=&quot;3-training-and-certification&quot;&gt;3. Training and Certification&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;One free certification voucher&lt;/li&gt;
&lt;li&gt;Discounted certification voucher&lt;/li&gt;
&lt;li&gt;CloudAcademy subscription&lt;/li&gt;
&lt;li&gt;Exam prep sessions&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;4-community-support&quot;&gt;4. Community Support&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Private Slack workspace&lt;/li&gt;
&lt;li&gt;Networking with AWS Heroes and staff&lt;/li&gt;
&lt;li&gt;Mentorship opportunities&lt;/li&gt;
&lt;li&gt;Co-create content with other builders&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;5-swag&quot;&gt;5. Swag&lt;/h3&gt;
&lt;p&gt;Annual welcome packages with exclusive AWS CB branded items.&lt;/p&gt;
&lt;h3 id=&quot;6-branding-and-professional-visibility&quot;&gt;6. Branding and Professional Visibility&lt;/h3&gt;
&lt;p&gt;Being an AWS CB increases your visibility and credibility in the industry. It often leads to more speaking opportunities, collaborations, and recognition.&lt;/p&gt;
&lt;h3 id=&quot;7-event-participation&quot;&gt;7. Event Participation&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Priority access to AWS events&lt;/li&gt;
&lt;li&gt;AWS Summit perks&lt;/li&gt;
&lt;li&gt;Special sessions during AWS re:Invent&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;how-to-prepare-and-apply-for-the-program&quot;&gt;How to Prepare and Apply for the Program&lt;/h2&gt;
&lt;p&gt;The application process is competitive, so preparation matters. Here’s a step-by-step approach to improve your chances.&lt;/p&gt;
&lt;h3 id=&quot;1-build-your-public-presence&quot;&gt;1. Build Your Public Presence&lt;/h3&gt;
&lt;p&gt;You don’t need to be an influencer. A few meaningful contributions are enough:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Publishing technical blog posts&lt;/li&gt;
&lt;li&gt;Speaking at community meetups&lt;/li&gt;
&lt;li&gt;Open-source projects&lt;/li&gt;
&lt;li&gt;Sharing AWS tips on LinkedIn or X&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;2-provide-specific-evidence&quot;&gt;2. Provide Specific Evidence&lt;/h3&gt;
&lt;p&gt;When AWS asks how you contribute, be specific. Mention:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Links to posts or videos&lt;/li&gt;
&lt;li&gt;Impact of your content&lt;/li&gt;
&lt;li&gt;Workshops or talks you delivered&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;3-choose-the-right-track&quot;&gt;3. Choose the Right Track&lt;/h3&gt;
&lt;p&gt;Select a track that matches your work. AWS prefers applicants who already use the services they want to represent.&lt;/p&gt;
&lt;h3 id=&quot;4-be-clear-and-genuine-in-your-application&quot;&gt;4. Be Clear and Genuine in Your Application&lt;/h3&gt;
&lt;p&gt;Avoid buzzwords. Demonstrate real passion through concrete actions.&lt;/p&gt;
&lt;h3 id=&quot;5-highlight-consistency&quot;&gt;5. Highlight Consistency&lt;/h3&gt;
&lt;p&gt;Continuous contribution matters more than one-time efforts.&lt;/p&gt;
&lt;h3 id=&quot;6-share-future-plans&quot;&gt;6. Share Future Plans&lt;/h3&gt;
&lt;p&gt;Explain how you intend to contribute &lt;em&gt;during the program&lt;/em&gt;—meetups, tutorials, videos, open-source work, etc.&lt;/p&gt;
&lt;h2 id=&quot;tips-that-helped-me-get-accepted-and-renewed&quot;&gt;Tips That Helped Me Get Accepted (and Renewed)&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Post 2–4 helpful AWS tutorials every year&lt;/li&gt;
&lt;li&gt;Focus on practical, hands-on examples&lt;/li&gt;
&lt;li&gt;Engage with others on social platforms&lt;/li&gt;
&lt;li&gt;Teach and mentor juniors&lt;/li&gt;
&lt;li&gt;Stay consistent throughout the year&lt;/li&gt;
&lt;li&gt;Be yourself—authenticity is valued&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;who-should-apply&quot;&gt;Who Should Apply?&lt;/h2&gt;
&lt;p&gt;You should apply if you:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Enjoy learning AWS&lt;/li&gt;
&lt;li&gt;Share knowledge with others&lt;/li&gt;
&lt;li&gt;Want to grow in your cloud career&lt;/li&gt;
&lt;li&gt;Want access to AWS experts and a global network&lt;/li&gt;
&lt;li&gt;Want to build your technical brand&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You don’t need to be a senior engineer. Many CBs are early-career developers and students.&lt;/p&gt;
&lt;h2 id=&quot;final-thoughts&quot;&gt;Final Thoughts&lt;/h2&gt;
&lt;p&gt;Being an AWS Community Builder has been one of the most impactful parts of my cloud journey. It opened doors, pushed me to create more content, and connected me with amazing people around the world.&lt;/p&gt;
&lt;p&gt;If you love AWS and enjoy helping others, definitely apply when the next window opens. And if you want help reviewing your application, feel free to reach out—I would be happy to help.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://pulse.aws/application/BM2AKLSX?p=0&quot;&gt;Join The Waitlist!&lt;/a&gt;&lt;/p&gt;</content:encoded><category>AWS</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Accessing &amp; Installing Web Server (LEMP) on Amazon EC2 Instance</title><link>https://www.sumonselim.com/installing-web-server-lemp-amazon-ec2-instance/</link><guid isPermaLink="true">https://www.sumonselim.com/installing-web-server-lemp-amazon-ec2-instance/</guid><description>SSH into an Ubuntu EC2 instance with your .pem key, install Nginx, MySQL and PHP 8.2 FPM, and configure the default Nginx server block to run PHP.</description><pubDate>Sun, 09 Jul 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; To turn a fresh Ubuntu EC2 instance into a LEMP web server: open port 22 in the security group, &lt;code&gt;chmod 400&lt;/code&gt; your &lt;code&gt;.pem&lt;/code&gt; key and &lt;code&gt;ssh ubuntu@&amp;lt;public-ip&amp;gt;&lt;/code&gt;; install &lt;code&gt;nginx&lt;/code&gt;, &lt;code&gt;mysql-server&lt;/code&gt; (then run &lt;code&gt;mysql_secure_installation&lt;/code&gt;) and &lt;code&gt;php8.2-fpm php8.2-mysql php8.2-cli php8.2-curl&lt;/code&gt;; edit &lt;code&gt;/etc/nginx/sites-available/default&lt;/code&gt; so &lt;code&gt;location ~ \.php$&lt;/code&gt; passes requests to &lt;code&gt;unix:/var/run/php8.2-fpm.sock&lt;/code&gt;; restart Nginx and open the instance’s public DNS in a browser.&lt;/p&gt;
&lt;p&gt;On my last post, I wrote about how to create and &lt;a href=&quot;http://www.sumonselim.com/launching-free-amazon-ec2-instance/&quot;&gt;launch an Amazon EC2 instance &lt;/a&gt;on Amazon Web Services (AWS). We had created an Amazon EC2 instance under &lt;em&gt;&lt;strong&gt;“&lt;a href=&quot;http://aws.amazon.com/free/&quot;&gt;AWS Free Tier&lt;/a&gt;”&lt;/strong&gt;&lt;/em&gt; and launched it successfully. Now we will go through step-by-step guide to SSH into the instance and then install &lt;strong&gt;Nginx, MySQL &amp;amp; PHP (LEMP)&lt;/strong&gt; – which will be enough for us to host a simple PHP application.&lt;/p&gt;
&lt;p&gt;We can use the public IPv4 address or the public IPv4 DNS name to SSH into the instance that we just created.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/installing-web-server-lemp-amazon-ec2-instance/Screenshot-2023-07-13-at-02.40.17.webp&quot; alt=&quot;Amazon EC2 - Instance Summary&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Make sure to set access permission to the ports by which we will need to communicate under the security group inbound rules. For example, here we are allowing access from anywhere to port 22 via SSH/TCP; so that we can SSH into the instance.&lt;/p&gt;
&lt;p&gt;It’s time to login to our instance via SSH using the &lt;em&gt;&lt;strong&gt;.pem file –&lt;/strong&gt;&lt;/em&gt; we have gotten it earlier while launching our instance.&lt;/p&gt;
&lt;p&gt;We will need to change the permission of the file first by running the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; chmod&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 400&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ~/Keys/kodeeo-sumonmselim-ec2.pem&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Replace the file name and location according to your environment.&lt;/p&gt;
&lt;p&gt;Then we will run the SSH command to login:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;ssh&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ubuntu@PUBLIC_IP_ADDRESS&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; OR&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; DNS_OF_THE_INSTANCE&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You will need to replace the private key file name and server IP address as per your environment and information.&lt;/p&gt;
&lt;p&gt;After successful login, you will see something like this on your terminal.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/installing-web-server-lemp-amazon-ec2-instance/Screenshot-2023-07-13-at-02.45.27-e1689209434948-1024x640.webp&quot; alt=&quot;AWS EC2 - SSH into the instance&quot;/&gt;&lt;/p&gt;
&lt;p&gt;We have successfully got access to our instance and now we will install &lt;strong&gt;Nginx, MySQL and PHP&lt;/strong&gt; to prepare a simple web server so that we can run and host our PHP application there.&lt;/p&gt;
&lt;p&gt;First of all, we will install &lt;strong&gt;Nginx&lt;/strong&gt; by running the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; nginx&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will install the Nginx server on our instance. Next we will install &lt;strong&gt;MySQL&lt;/strong&gt;.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; mysql-server&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You will need to provide some information like MySQL root password while installing the MySQL server.&lt;/p&gt;
&lt;p&gt;Next we will run &lt;code&gt;sudo mysql_secure_installation&lt;/code&gt; to configure and set some basic settings for the MySQL server.&lt;/p&gt;
&lt;p&gt;At last, we will install &lt;strong&gt;PHP&lt;/strong&gt; (php-fpm) to our instance along with some other modules.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; php8.2-fpm&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; php8.2-mysql&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; php8.2-cli&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; php8.2-curl&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we will need to configure the default virtual host so that we can access our web pages.&lt;/p&gt;
&lt;p&gt;Run the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; nano&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /etc/nginx/sites-available/default&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Edit the file according to your need and you will be ready. We need to tell Nginx that all our PHP files should be run by php-fpm. Here’s the information from my file:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;server&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    listen&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 80&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    //&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; replace&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; with&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; your&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; Amazon&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; EC2&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; public&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; DNS&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; name&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; or&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; domain&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; name&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    server_name&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; _&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    //&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; location&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; to&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; your&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; root&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; folder&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    root&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /usr/share/nginx/html&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    index&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; index.php&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    charset&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; utf-8&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    location&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;        try_files&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; $uri $uri&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;/&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /index.php?&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;$query_string;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    location&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /favicon.ico&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; {&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; access_log&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; off&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;log_not_found&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; off&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    location&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /robots.txt&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;  {&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; access_log&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; off&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;log_not_found&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; off&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;; }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    error_page&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 404&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /index.php&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    sendfile&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; off&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    location&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ~&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt; \.&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;php&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;$ &lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;{&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;        fastcgi_split_path_info&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ^&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;(&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;.&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;+&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;\&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;.php&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)(&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;/.+&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;)$;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;        fastcgi_pass&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; unix:/var/run/php8.2-fpm.sock&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;        fastcgi_index&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; index.php&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;        include&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; fastcgi_params&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    &lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;    location&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ~&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#FF7B72&quot;&gt;\.&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;ht&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; {&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;        deny&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; all&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;;&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;    }&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;}&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You need to restart Nginx by running the following command and then you can visit your Public DNS name or domain name address to see the default folder of your web server.&lt;/p&gt;
&lt;p&gt;Hope this helps. If you have any questions, feel free to ask on the comment section.&lt;/p&gt;</content:encoded><category>PHP</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Launching An Amazon EC2 Instance</title><link>https://www.sumonselim.com/launching-free-amazon-ec2-instance/</link><guid isPermaLink="true">https://www.sumonselim.com/launching-free-amazon-ec2-instance/</guid><description>Launch a free-tier Amazon EC2 instance step by step: pick the Ubuntu 22.04 AMI, choose t2.micro, create and download a key pair, set a security group, add an 8 GiB EBS volume.</description><pubDate>Sun, 02 Jul 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; To launch a free-tier EC2 instance: open &lt;strong&gt;EC2&lt;/strong&gt; in the AWS Console and click &lt;strong&gt;Launch Instance&lt;/strong&gt;; pick the &lt;strong&gt;Ubuntu Server 22.04 LTS&lt;/strong&gt; AMI; choose the &lt;strong&gt;t2.micro&lt;/strong&gt; instance type (the only free-tier-eligible size); create a new key pair and download the &lt;code&gt;.pem&lt;/code&gt; file, because it cannot be downloaded again; keep the default VPC and subnet; pick a security group (the permissive default is fine for a test, not for production); add an 8 GiB General Purpose SSD volume; click &lt;strong&gt;Launch instance&lt;/strong&gt;. Part two covers SSH access and installing a web server.&lt;/p&gt;
&lt;p&gt;I am a great fan of cloud hosting as it gives me ease and control to manage my own production environment as per my need. Luckily, Amazon Web Services (AWS) offers &lt;strong&gt;“&lt;a href=&quot;http://aws.amazon.com/free/&quot;&gt;AWS Free Tier&lt;/a&gt;”&lt;/strong&gt; by using which we can get hands-on experience with AWS Cloud Services at no charge for 12 months. So, I took the chance to test drive their services. Today I am going to write about launching and preparing my first instance on &lt;strong&gt;Amazon EC2&lt;/strong&gt; service where we will host a web application developed using PHP (Laravel).&lt;/p&gt;
&lt;p&gt;First, we will need to login to our AWS Management Console and select &lt;strong&gt;EC2&lt;/strong&gt;. We will see a dashboard like below:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/launching-free-amazon-ec2-instance/Screenshot-2023-07-13-at-01.55.39.webp&quot; alt=&quot;AWS EC2 Dashboard&quot;/&gt;&lt;/p&gt;
&lt;p&gt;You can see lots of options there. But to launch our first instance, click on the blue “&lt;strong&gt;Launch Instance&lt;/strong&gt;” button. You will then be prompted to choose an AMI to launch your instance. An &lt;strong&gt;AMI&lt;/strong&gt; is a template that contains the software configuration (operating system, application server, and applications) required to launch your instance. You will also be able to set a name for your instance. Try to give a meaningful name for the instance.&lt;/p&gt;
&lt;p&gt;I am going to select &lt;strong&gt;Ubuntu Server 22.04 LTS&lt;/strong&gt; for our instance and luckily it’s eligible to use with AWS Free Tier.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/launching-free-amazon-ec2-instance/Screenshot-2023-07-13-at-02.01.31.webp&quot; alt=&quot;AWS EC2 Instance - Select AMI&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Next, we will need to select our &lt;em&gt;&lt;strong&gt;instance type&lt;/strong&gt;&lt;/em&gt;. We will choose &lt;strong&gt;t2.micro&lt;/strong&gt; type instance this time as our AMI is eligible to run on this instance type. You should know that free tier is only eligible for micro instances. If you are ready to afford some money to get more powerful instance, you can choose any other instance type that fits you the best.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/launching-free-amazon-ec2-instance/Screenshot-2023-07-13-at-02.06.52.webp&quot; alt=&quot;AWS EC2 Instance - Select Instance Type&quot;/&gt;&lt;/p&gt;
&lt;p&gt;You will need to &lt;em&gt;&lt;strong&gt;create new key pair&lt;/strong&gt;&lt;/em&gt; which you will need to login to your instance. You can choose between RSA or ED25519 key pair type. Give the key pair a name and download the &lt;strong&gt;Key Pair (.pem or .ppk)&lt;/strong&gt; file. Please keep in mind that you must download the &lt;strong&gt;private key file&lt;/strong&gt; before you can continue. &lt;strong&gt;Store it in a secure and accessible location.&lt;/strong&gt; You will not be able to download the file again after it’s created.&lt;/p&gt;
&lt;p&gt;In the next section, we will need to set the network settings for our instance. For now, you can keep using the default VPC and use the default subnet. We will discuss more about these in a future post.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/launching-free-amazon-ec2-instance/Screenshot-2023-07-13-at-02.15.44.webp&quot; alt=&quot;AWS EC2 Instance - Network Settings&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Then we will need to &lt;em&gt;&lt;strong&gt;configure security group&lt;/strong&gt;&lt;/em&gt; to set firewall rules that control the traffic to and from our instance. For now, I am going to select the &lt;strong&gt;existing&lt;/strong&gt; security group which will allow all traffic to access our instance and all traffic from our instance to the public internet. &lt;strong&gt;Please keep in mind, it’s not recommended at all for production usage.&lt;/strong&gt; We will learn about security and best practices in a future post. For better security, you will need to modify these rules to prevent unauthorized or unintended access.&lt;/p&gt;
&lt;p&gt;After that, we will need to &lt;em&gt;&lt;strong&gt;add storage&lt;/strong&gt;&lt;/em&gt; to our instance. For now, I will add an EBS General Purpose (SSD) volume and allocate 8 GiB of space.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/launching-free-amazon-ec2-instance/Screenshot-2023-07-13-at-02.20.47.webp&quot; alt=&quot;AWS EC2 Instance - Configure storage&quot;/&gt;&lt;/p&gt;
&lt;p&gt;You can skip the &lt;strong&gt;Advance details&lt;/strong&gt; section for now and see the summary of the instance that you will be creating. Click on the “&lt;strong&gt;Launch instance&lt;/strong&gt;” button to start creating the instance. If needed you can make necessary changes, before starting the launch process.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/launching-free-amazon-ec2-instance/Screenshot-2023-07-13-at-02.31.24.webp&quot; alt=&quot;AWS EC2 Instance - Launch instance&quot;/&gt;&lt;/p&gt;
&lt;p&gt;It will take some time to complete the instance launching process. After that, you will see a page with Launch Status of your instance. Voila! You are ready with your first Amazon EC2 instance now 🙂&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/launching-free-amazon-ec2-instance/Screenshot-2023-07-13-at-02.32.31.webp&quot; alt=&quot;AWS EC2 Instance - Instance created&quot;/&gt;&lt;/p&gt;
&lt;p&gt;If you visit the “&lt;strong&gt;Instances&lt;/strong&gt;” section now, you will see that your running instance is listed there. On our next part, we will connect with our newly created instance via SSH and install the necessary software to run a web server.&lt;/p&gt;</content:encoded><category>AWS</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Sync Forked Github Repository With Master</title><link>https://www.sumonselim.com/sync-forked-github-repository-master/</link><guid isPermaLink="true">https://www.sumonselim.com/sync-forked-github-repository-master/</guid><description>Sync a forked GitHub repository with the original: add the source repo as an upstream remote, fetch, merge upstream/master into your master, and push.</description><pubDate>Fri, 08 Jul 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; To sync a forked GitHub repository with the original project, add the original repo as a remote named &lt;code&gt;upstream&lt;/code&gt; (&lt;code&gt;git remote add upstream &amp;lt;url&amp;gt;&lt;/code&gt;), then run &lt;code&gt;git fetch upstream &amp;amp;&amp;amp; git checkout master &amp;amp;&amp;amp; git merge upstream/master&lt;/code&gt; and push with &lt;code&gt;git push origin master&lt;/code&gt;. GitHub then shows “This branch is even with upstream:master”. Re-run the fetch/merge line whenever the original repo changes.&lt;/p&gt;
&lt;h2 id=&quot;the-problem-cant-sync-forked-github-repository-withmasterupstream-changes&quot;&gt;The problem: can’t sync forked github repository with master/upstream changes&lt;/h2&gt;
&lt;p&gt;While working with &lt;strong&gt;Github&lt;/strong&gt; recently, I was facing a problem that – while I have forked a project repositorywhere I want to contribute but during the time I am working on the &lt;strong&gt;forked github repository&lt;/strong&gt;**,**there may be some changes or major updates pushed on the &lt;strong&gt;master repository of the project&lt;/strong&gt; by the original author or other collaborators. So, I need to sync my &lt;strong&gt;forked github repository&lt;/strong&gt;with master repository of the project to get the latest changes.&lt;/p&gt;
&lt;h3 id=&quot;the-solution&quot;&gt;The Solution&lt;/h3&gt;
&lt;p&gt;I love to contribute on open source projects on my leisure time. So, I used to &lt;strong&gt;fork projects on &lt;a href=&quot;https://github.com/SumonMSelim?tab=repositories#&quot;&gt;Github&lt;/a&gt;&lt;/strong&gt; frequently which seems interesting to me and I feel I can contribute on. So, I was in need of a solution.&lt;/p&gt;
&lt;p&gt;I have seen on &lt;a href=&quot;https://www.bitbucket.org/SumonMSelim&quot;&gt;&lt;strong&gt;Bitbucket&lt;/strong&gt;&lt;/a&gt;, this can be done from their panel by just clicking on a single button. But in case of Github, there’s no option available. So, after searching on Google I’ve found the right way to sync my forked github repository with the original master repository. I am documenting the steps here on my blog for future reference 🙂&lt;/p&gt;
&lt;h2 id=&quot;sync-forked-github-repositorywith-master&quot;&gt;Sync forked github repository with master&lt;/h2&gt;
&lt;p&gt;First I need to set &lt;strong&gt;upstream&lt;/strong&gt; remote by running the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; remote&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; add&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; upstream&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; https://github.com/techjewel/DevConByPHPxperts.git&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In your case, you will need to change the repo url to your one.&lt;/p&gt;
&lt;p&gt;Next, I will need to fetch the changes from &lt;strong&gt;upstream (master repo)&lt;/strong&gt;.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; fetch&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; upstream&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will bring all the updated changes to &lt;strong&gt;upstream&lt;/strong&gt; branch. Then I can merge the updates from &lt;strong&gt;upstream/master&lt;/strong&gt; with my local &lt;strong&gt;forked master&lt;/strong&gt; branch by running the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; checkout&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; master&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; &amp;amp;&amp;amp; &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; merge&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; upstream/master&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Great! Now my forked master branch has all the changes and updates from the original master branch of the repo I had forked.&lt;/p&gt;
&lt;p&gt;Now I can just push the update to Github.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; push&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; origin&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; master&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If I visit Github now, I will see that my forked repo is showing the following message:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;This branch is even with techjewel:master.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/sync-forked-github-repository-master/Screenshot-2016-07-08-03.32.47.webp&quot; alt=&quot;sync forked github repository with master repository&quot;/&gt;&lt;/p&gt;
&lt;p&gt;That was it. From now, every time if there is any new changes on the &lt;strong&gt;master repository&lt;/strong&gt; of the project, I can easily sync them to my &lt;strong&gt;forked repository&lt;/strong&gt; just by running the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; fetch&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; upstream&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; &amp;amp;&amp;amp; &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; checkout&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; master&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; &amp;amp;&amp;amp; &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; merge&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; upstream/master&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;</content:encoded><category>Git</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Lets Learn Coding @ Tech Life Asian Radio FM 90.8</title><link>https://www.sumonselim.com/lets-learn-coding-tech-life-asian-radio-fm-90-8/</link><guid isPermaLink="true">https://www.sumonselim.com/lets-learn-coding-tech-life-asian-radio-fm-90-8/</guid><description>I (Founder, Lets Learn Coding) along with my friend Rakibul Hasan Rashed (Faculty, Department of CSE, IUBAT) were special guests on the show “Lets Learn Coding…</description><pubDate>Tue, 09 Feb 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I (Founder, Lets Learn Coding) along with my friend &lt;a href=&quot;https://www.facebook.com/rakibulhasan.rashed1&quot;&gt;Rakibul Hasan Rashed&lt;/a&gt; (Faculty, Department of CSE, IUBAT) were special guests on the show &lt;strong&gt;“Lets Learn Coding @ Tech Life”&lt;/strong&gt; on &lt;strong&gt;Asian Radio FM 90.8&lt;/strong&gt; this Saturday.&lt;/p&gt;
&lt;p&gt;We talked about coding/programming and ICT industry of Bangladesh. Discussed about the mission and vision of Lets Learn Coding. You can hear the full recorded version of the program below.&lt;/p&gt;
&lt;p&gt;The show was hosted by RJ &lt;a href=&quot;https://www.facebook.com/hopperduke&quot;&gt;Nazib Rafe&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;tech-life--asian-radio-fm-908&quot;&gt;Tech Life @ Asian Radio FM 90.8&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Part 1&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;rounded-lg overflow-hidden border border-border my-6&quot;&gt;&lt;iframe src=&quot;https://w.soundcloud.com/player/?url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F246063493&amp;amp;auto_play=false&amp;amp;hide_related=false&amp;amp;visual=true&amp;amp;show_comments=true&amp;amp;color=false&amp;amp;show_user=true&amp;amp;show_reposts=false&quot; title width=&quot;100%&quot; height=&quot;150&quot; loading=&quot;lazy&quot; class=&quot;border-0 block&quot; allow=&quot;encrypted-media&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Part 2&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;rounded-lg overflow-hidden border border-border my-6&quot;&gt;&lt;iframe src=&quot;https://w.soundcloud.com/player/?url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F246065623&amp;amp;auto_play=false&amp;amp;hide_related=false&amp;amp;visual=true&amp;amp;show_comments=true&amp;amp;color=false&amp;amp;show_user=true&amp;amp;show_reposts=false&quot; title width=&quot;100%&quot; height=&quot;150&quot; loading=&quot;lazy&quot; class=&quot;border-0 block&quot; allow=&quot;encrypted-media&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;</content:encoded><category>Podcasts</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Increase Your WordPress Maximum File Upload Size Limit</title><link>https://www.sumonselim.com/increase-your-wordpress-maximum-file-upload-size-limit/</link><guid isPermaLink="true">https://www.sumonselim.com/increase-your-wordpress-maximum-file-upload-size-limit/</guid><description>Two ways to raise the WordPress upload limit on shared hosting: set upload_max_filesize and post_max_size via .htaccess (php_value) or a php.ini file in the site root.</description><pubDate>Tue, 24 Mar 2015 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; To increase the WordPress maximum file upload size on shared hosting, raise PHP’s &lt;code&gt;upload_max_filesize&lt;/code&gt; and &lt;code&gt;post_max_size&lt;/code&gt; (and optionally &lt;code&gt;max_execution_time&lt;/code&gt; and &lt;code&gt;max_input_time&lt;/code&gt;). Either add &lt;code&gt;php_value upload_max_filesize 32M&lt;/code&gt; and &lt;code&gt;php_value post_max_size 32M&lt;/code&gt; to the &lt;code&gt;.htaccess&lt;/code&gt; file in the WordPress root, or create a &lt;code&gt;php.ini&lt;/code&gt; in the same directory with &lt;code&gt;upload_max_filesize = 32M&lt;/code&gt; and &lt;code&gt;post_max_size = 32M&lt;/code&gt;. Use &lt;code&gt;.htaccess&lt;/code&gt; when the host blocks &lt;code&gt;php.ini&lt;/code&gt; overrides.&lt;/p&gt;
&lt;p&gt;I’m a part-time &lt;strong&gt;WordPress developer&lt;/strong&gt; and use it mostly to develop sites for my clients.  As most of the clients use shared hosting, sometimes I find it difficult to upload/install plugin and themes for the default maximum file upload size limit of the hosting.&lt;/p&gt;
&lt;h2 id=&quot;using-htaccess-file&quot;&gt;Using .htaccess file&lt;/h2&gt;
&lt;p&gt;The most common solution to this problem is to use a &lt;strong&gt;.htaccess file&lt;/strong&gt; in the root directory and add the following code to it:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;php_value&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; upload_max_filesize&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; 32M&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;php_value&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; post_max_size&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; 32M&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;php_value&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; max_execution_time&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 300&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;php_value&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; max_input_time&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 300&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will override the existing values set by the host and you’ll be able to set the value as much as you want. Here, I am increasing the maximum file upload size limit to 32 MB.&lt;/p&gt;
&lt;h2 id=&quot;using-phpini-file&quot;&gt;Using php.ini file&lt;/h2&gt;
&lt;p&gt;You can also fix the problem by creating a php.ini file in your directory and add the following code to it:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;upload_max_filesize&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; 32M&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;post_max_size&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; 32M&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;max_execution_time&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 300&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;max_input_time&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; =&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; 300&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But some hosting providers might not allow you to override the php.ini settings and .htaccess method can come handy then.&lt;/p&gt;
&lt;p&gt;Hope this small piece of information will help you if you face this problem. Feel free to share your method of solving this problem with us.&lt;/p&gt;</content:encoded><category>WordPress</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Installing LAMP (PHP 5.6, Apache 2.4, MySQL 5.6) on Elementary OS</title><link>https://www.sumonselim.com/installing-php-5-6-apache-2-4-mysql-5-6-elementary-freya/</link><guid isPermaLink="true">https://www.sumonselim.com/installing-php-5-6-apache-2-4-mysql-5-6-elementary-freya/</guid><description>Install a LAMP stack on elementary OS Freya: Apache 2.4, PHP 5.6 and MySQL 5.6 from the ondrej PPAs, then verify with a phpinfo() page.</description><pubDate>Mon, 27 Oct 2014 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; This guide installs a LAMP development stack on elementary OS Freya without &lt;code&gt;tasksel&lt;/code&gt;. Add the &lt;code&gt;ppa:ondrej/apache2&lt;/code&gt;, &lt;code&gt;ppa:ondrej/php5-5.6&lt;/code&gt; and &lt;code&gt;ppa:ondrej/mysql-5.6&lt;/code&gt; repositories, run &lt;code&gt;sudo apt-get update&lt;/code&gt;, then install &lt;code&gt;apache2&lt;/code&gt;, &lt;code&gt;php5&lt;/code&gt; and &lt;code&gt;mysql-server&lt;/code&gt;. Verify by opening &lt;code&gt;http://localhost&lt;/code&gt; and by placing a file containing &lt;code&gt;&amp;lt;?php phpinfo();&lt;/code&gt; in &lt;code&gt;/var/www/html&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I’m a web and mobile application developer by profession and developing on &lt;strong&gt;LAMP&lt;/strong&gt; (Linux, Apache, MySQL and PHP) stack for last couple of years. Now it’s time to get development environment ready on my newly installed &lt;strong&gt;elementary OS “Freya”.&lt;/strong&gt; I will install everything separately instead of using the &lt;strong&gt;tasksel&lt;/strong&gt; command.&lt;/p&gt;
&lt;p&gt;At the time of writing this article, I’m installing the latest stable version of all the things I am going to need.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;PHP 5.6&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Apache 2.4&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;MySQL 5.6&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;installing-apache-24&quot;&gt;Installing Apache 2.4&lt;/h2&gt;
&lt;p&gt;We will add the repository of the latest Apache version to our system by using the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; add-apt-repository&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ppa:ondrej/apache2&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then run the following two commands to install &lt;strong&gt;Apache 2.4&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; update&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apache2&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;installing-php-56&quot;&gt;Installing PHP 5.6&lt;/h2&gt;
&lt;p&gt;First, we will add the repository of the latest PHP version to our system by using the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; add-apt-repository&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ppa:ondrej/php5-5.6&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then run the following two commands to install &lt;strong&gt;PHP&lt;/strong&gt; &lt;strong&gt;5.6&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; update&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; php5&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will install PHP on our system.&lt;/p&gt;
&lt;h2 id=&quot;installing-mysql-56&quot;&gt;Installing MySQL 5.6&lt;/h2&gt;
&lt;p&gt;We will add the repository of the latest MySQL version to our system by using the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; add-apt-repository&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ppa:ondrej/mysql-5.6&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then run the following two commands to install &lt;strong&gt;MySQL&lt;/strong&gt; &lt;strong&gt;5.6&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; update&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; mysql-server&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will install MySQL on our system.&lt;/p&gt;
&lt;p&gt;You will be asked to set password for the “root” user for the MySQL server during the process.&lt;/p&gt;
&lt;p&gt;Voila! Our development environment is ready now 🙂&lt;/p&gt;
&lt;p&gt;If you visit &lt;a href=&quot;http://localhost&quot;&gt;http://localhost&lt;/a&gt; now, you will see the Apache2 Ubuntu Default Page.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/installing-php-5-6-apache-2-4-mysql-5-6-elementary-freya/apache-default-page.webp&quot; alt=&quot;Apache2 Ubuntu default page&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Now let’s write some PHP code to check if everything is working properly. Let’s create a PHP file named &lt;em&gt;&lt;strong&gt;info.php&lt;/strong&gt;&lt;/em&gt; on the default document root folder of Apache web server which is&lt;strong&gt;&lt;em&gt;/var/www/html&lt;/em&gt;&lt;/strong&gt; and add the following code to the file:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;php&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;&amp;lt;?&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;php&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;phpinfo&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;();&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Save the file. Then visit the file on your browser: &lt;a href=&quot;http://localhost/info.php&quot;&gt;http://localhost/info.php&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;You should get an output like this:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/installing-php-5-6-apache-2-4-mysql-5-6-elementary-freya/phpinfo.webp&quot; alt=&quot;PHP info page output&quot;/&gt;&lt;/p&gt;
&lt;p&gt;You may need to install some other PHP extensions and libraries according to your need manually. I will cover this in future. Feel free to comment if you have any queries.&lt;/p&gt;</content:encoded><category>PHP</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Customizing Terminal with Guake, oh-my-zsh and screenFetch on Elementary OS Freya</title><link>https://www.sumonselim.com/customizing-terminal-elementary-freya/</link><guid isPermaLink="true">https://www.sumonselim.com/customizing-terminal-elementary-freya/</guid><description>Set up a developer terminal on elementary OS Freya: install Guake for an F12 drop-down terminal, oh-my-zsh for a better shell, and screenFetch for system info at startup.</description><pubDate>Sun, 26 Oct 2014 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; This guide sets up a developer terminal on elementary OS Freya in three steps: install &lt;strong&gt;Guake&lt;/strong&gt; (&lt;code&gt;sudo apt-get install guake&lt;/code&gt;) for a drop-down terminal toggled with F12 and add it to Startup Applications; install &lt;strong&gt;zsh&lt;/strong&gt; and &lt;strong&gt;oh-my-zsh&lt;/strong&gt; and set &lt;code&gt;/bin/zsh&lt;/code&gt; as Guake’s default interpreter; install the elementary-specific &lt;strong&gt;screenFetch&lt;/strong&gt; build and call &lt;code&gt;screenfetch -D &amp;quot;Elementary&amp;quot;&lt;/code&gt; from &lt;code&gt;.zshrc&lt;/code&gt; so system info prints on every new shell.&lt;/p&gt;
&lt;p&gt;As I stated previously that I am a great &lt;strong&gt;elementary OS&lt;/strong&gt; fan and installed the latest beta of elementary OS titled “&lt;strong&gt;Freya&lt;/strong&gt;” few days ago. Now, it’s time to customize it and making it ready as my primary development environment. The first thing I am going to customize is my terminal because I am not that much fan of the default bash terminal.&lt;/p&gt;
&lt;p&gt;First, I am going to install &lt;strong&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Guake&quot;&gt;Guake&lt;/a&gt;&lt;/strong&gt; to change the appearance behavior of my terminal. I really liked the drop-down approach of Guake which helps me to work without any flaw with so many things within the workspace.  I can just press the “&lt;strong&gt;F12&lt;/strong&gt;” key to toggle the visibility of my terminal after installing Guake. There are couple of others handy customization options available too.&lt;/p&gt;
&lt;p&gt;So, let’s install Guake. First we may update our system by running the following command on the terminal:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; update&lt;/span&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt; &amp;amp;&amp;amp; &lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; dist-upgrade&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then run the following command to install Guake:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; guake&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There may be some others dependencies that need to be installed. If needed, you may install those.&lt;/p&gt;
&lt;p&gt;After installing Guake, you may run it from the terminal by just running &lt;em&gt;“guake”&lt;/em&gt; on the terminal or from the Applications menu.&lt;/p&gt;
&lt;p&gt;You can customize the preferences according to your need by right clicking on the Guake terminal and clicking on the &lt;strong&gt;Preferences&lt;/strong&gt; option.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/customizing-terminal-elementary-freya/guake-preferences.webp&quot; alt=&quot;Guake terminal preferences&quot;/&gt;&lt;/p&gt;
&lt;p&gt;To use it instead of your default Terminal, you will need to add it on the Startup Applications so that every time you run your system you can use Guake immediately by just pressing “F12”. You may also change it according to your need.&lt;/p&gt;
&lt;p&gt;To add Guake on the Startup Applications, go to your “&lt;strong&gt;System Settings&lt;/strong&gt;” and select “&lt;strong&gt;Applications&lt;/strong&gt;”. Then click on the “&lt;strong&gt;Startup&lt;/strong&gt;” tab. Click on the “&lt;strong&gt;+&lt;/strong&gt;” icon placed at the bottom left of the screen and select “Guake Terminal” from there.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/customizing-terminal-elementary-freya/guake-startup-applications.webp&quot; alt=&quot;Guake added to Startup Applications&quot;/&gt;&lt;/p&gt;
&lt;p&gt;From now, every time you start your system, Guake will run automatically.&lt;/p&gt;
&lt;p&gt;Next, I am going to install &lt;strong&gt;oh-my-zsh&lt;/strong&gt;as I like it very much. But first, I need some other things to install first such as &lt;em&gt;curl&lt;/em&gt;, &lt;em&gt;git&lt;/em&gt;, &lt;em&gt;vim&lt;/em&gt; and &lt;em&gt;zsh&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;To install them run the following:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; -y&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; curl&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; git&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; vim&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; zsh&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we can use the automatic installer to install &lt;em&gt;oh-my-zsh&lt;/em&gt; on our system easily.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;curl&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; -L&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt; |&lt;/span&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt; bash&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After installation, we just need to set &lt;em&gt;oh-my-zsh&lt;/em&gt; as the default terminal from our Guake terminal. To do that open the &lt;strong&gt;Preferences&lt;/strong&gt; option and just set “&lt;em&gt;&lt;strong&gt;/bin/zsh&lt;/strong&gt;&lt;/em&gt;” as the default interpreter.&lt;/p&gt;
&lt;p&gt;Re-start the terminal now. And we will be ready to go 🙂&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/customizing-terminal-elementary-freya/guake-oh-my-zsh.webp&quot; alt=&quot;Guake terminal with oh-my-zsh&quot;/&gt;&lt;/p&gt;
&lt;p&gt;At last, I will add &lt;a href=&quot;https://github.com/KittyKatt/screenFetch&quot;&gt;&lt;strong&gt;screenFetch&lt;/strong&gt;&lt;/a&gt; to add some system/theme information in terminal. For elementary OS, run the following commands on terminal:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;mkdir&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; screenfetch&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;cd&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; screenfetch&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;wget&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; https://raw.github.com/memoryleakx/screenFetch/master/screenfetch-dev&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; mv&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; screenfetch-dev&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /usr/bin/screenfetch&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt;cd&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; ..&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;rm&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; -rf&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; screenfetch&lt;/span&gt;&lt;/span&gt;
&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; chmod&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; +rx&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /usr/bin/screenfetch&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thanks to &lt;a href=&quot;https://github.com/memoryleakx/screenFetch&quot;&gt;memoryleakx&lt;/a&gt; for his screenFetch special version for elementary OS.&lt;/p&gt;
&lt;p&gt;At last, we have to add the following line to the end of our &lt;strong&gt;&lt;em&gt;.zshrc&lt;/em&gt;&lt;/strong&gt;file:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;screenfetch&lt;/span&gt;&lt;span style=&quot;color:#005CC5;--shiki-dark:#79C0FF&quot;&gt; -D&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; &amp;quot;Elementary&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here’s the final look of my terminal:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/customizing-terminal-elementary-freya/guake-screenfetch.webp&quot; alt=&quot;Terminal with Guake, oh-my-zsh and screenFetch&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Let me know what you think of it!&lt;/p&gt;</content:encoded><category>Linux</category><author>Muhammad Sumon Molla Selim</author></item><item><title>Fixing Date and Time Visibility Problem on elementary OS Freya Beta</title><link>https://www.sumonselim.com/fixing-date-time-visibility-problem-elementary-os-freya/</link><guid isPermaLink="true">https://www.sumonselim.com/fixing-date-time-visibility-problem-elementary-os-freya/</guid><description>Date and time missing from the elementary OS Freya top bar (wingpanel)? Add LC_ALL=&quot;en_US.UTF-8&quot; to /etc/environment and restart.</description><pubDate>Sun, 12 Oct 2014 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; If the date and time are missing from the wingpanel on elementary OS Freya Beta, the cause is an unset locale. Add the line &lt;code&gt;LC_ALL=&amp;quot;en_US.UTF-8&amp;quot;&lt;/code&gt; (or your own locale) to &lt;code&gt;/etc/environment&lt;/code&gt; with &lt;code&gt;sudo nano /etc/environment&lt;/code&gt;, save, and restart. The clock reappears. If you prefer a GUI, open the folder with &lt;code&gt;gksu pantheon-files&lt;/code&gt; and edit the file there.&lt;/p&gt;
&lt;p&gt;I am a hardcore &lt;strong&gt;elementary OS&lt;/strong&gt; lover and now facing date and time problem on &lt;strong&gt;Freya&lt;/strong&gt;. I was using &lt;strong&gt;Luna&lt;/strong&gt; for a long time. But couldn’t wait more for the new version of elementary OS &lt;strong&gt;Freya&lt;/strong&gt;and decided to move onto it. So installed Freya Beta 1 64 bit on my HP ProBook 4420s as my primary OS replacing Luna 32 bit.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;The Problem:&lt;/em&gt;&lt;/strong&gt; But I found that time and date is missing on the top bar (&lt;em&gt;wingpanel&lt;/em&gt;).&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/fixing-date-time-visibility-problem-elementary-os-freya/date-time-problem.webp&quot; alt=&quot;Date and time missing from wingpanel&quot;/&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;The solution:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;After googling, I found out that the solution is to add a single line of information on the &lt;em&gt;/etc/environment&lt;/em&gt; file.&lt;/p&gt;
&lt;p&gt;I’m a terminal lover. So, I typed the following command on the terminal to edit the file. Remeber, you will need administration access to edit the file.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; nano&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; /etc/environment&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And the result was:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/fixing-date-time-visibility-problem-elementary-os-freya/etc-environment-file.webp&quot; alt=&quot;/etc/environment file&quot;/&gt;&lt;/p&gt;
&lt;p&gt;All I need to do was to add the following line on it and save it.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#24292E;--shiki-dark:#E6EDF3&quot;&gt;LC_ALL&lt;/span&gt;&lt;span style=&quot;color:#D73A49;--shiki-dark:#FF7B72&quot;&gt;=&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt;&amp;quot;en_US.UTF-8&amp;quot;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can set your locale (e.g. &lt;em&gt;bn_BD.UTF-8&lt;/em&gt;) too as a value.&lt;/p&gt;
&lt;p&gt;After a restart the problem was fixed and date and time was visible on the wingpanel.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://www.sumonselim.com/images/articles/fixing-date-time-visibility-problem-elementary-os-freya/date-time-fixed.webp&quot; alt=&quot;Date and time visible on wingpanel after fix&quot;/&gt;&lt;/p&gt;
&lt;p&gt;Alternatively if you are not comfortable editing on the terminal, run the following command on the terminal.&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;gksu&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; pantheon-files&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This command will open the &lt;em&gt;/etc/&lt;/em&gt; folder on the Files browser and then you can edit the &lt;em&gt;environment&lt;/em&gt; file using your default text editor.&lt;/p&gt;
&lt;p&gt;If &lt;em&gt;gksu&lt;/em&gt; is not installed, you can install it by using the following command:&lt;/p&gt;
&lt;pre class=&quot;astro-code astro-code-themes github-light github-dark-default&quot; style=&quot;background-color:#fff;--shiki-dark-bg:#0d1117;color:#24292e;--shiki-dark:#e6edf3;overflow-x:auto&quot; tabindex=&quot;0&quot; data-language=&quot;bash&quot;&gt;&lt;code&gt;&lt;span class=&quot;line&quot;&gt;&lt;span style=&quot;color:#6F42C1;--shiki-dark:#FFA657&quot;&gt;sudo&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; apt-get&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; install&lt;/span&gt;&lt;span style=&quot;color:#032F62;--shiki-dark:#A5D6FF&quot;&gt; gksu&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Basically &lt;strong&gt;&lt;em&gt;&lt;code&gt;gksu&lt;/code&gt;&lt;/em&gt;&lt;/strong&gt; is a graphical front-end for &lt;strong&gt;&lt;em&gt;sudo&lt;/em&gt;&lt;/strong&gt; that allows graphical command to be run without the need to run an X terminal emulator and using &lt;strong&gt;&lt;em&gt;su&lt;/em&gt;&lt;/strong&gt; directly. It’s effectively just a GTK+ skin for the superuser commands.&lt;/p&gt;</content:encoded><category>Linux</category><author>Muhammad Sumon Molla Selim</author></item></channel></rss>