# Swadhin's Blog - Complete Knowledge Corpus > Swadhin's blog description for SEO Author: Swadhin Biswas Site: https://blog.swadhin.cv Generated: 2026-11-15T03:57:31.881Z Total Articles: 27 --- ## Own Your Namespace: Building a Private DNS Root at Home - URL: https://blog.swadhin.cv/blog/own-your-namespace-private-dns-root-at-home/ - Published: 2026-10-23T07:49:08.000Z - Updated: 2026-10-23T08:50:19.000Z - Author: Swadhin Biswas - Categories: DevOps, Architecture - Excerpt: OpenInternet in practice: a private root, a .swadhin TLD, authoritative servers in your closet, and the honest limits of running your own corner of DNS. ### Content The sketch started with one question: what if `portfolio.swadhin` was a real address on my network, not a folder on a laptop? It had a browser asking for an IP, a resolver at `dns.openinternet.com`, root servers at `10.10.10.11` and `10.10.10.12`, a `.swadhin` TLD, and a service called `git.swadhin` on `10.10.10.2:8909`. There were arrows everywhere and one word at the top: OPENINTERNET. It is the kind of diagram that looks like a joke until you realize every box is a real protocol and every arrow is a real delegation. The sketch says `dns.openinternet.com`; the project's docs use `dns.openinternet.org`. Same resolver, different spelling. The diagram is technically correct. It is also incomplete in the way every alternative-root diagram is incomplete: it shows the delegation, not the trust. A name is not yours because you wrote it in a zone file. It is yours when the resolver that a device actually uses agrees to ask your server. That distinction is the whole article. I built the sketch as a lab: two private roots, two `.swadhin` TLD servers, an Unbound resolver, a primary and a secondary for every zone, and a handful of services. The config below is what I tested. It works. It also breaks in specific, predictable ways, and those ways are more interesting than the happy path. ## The five-hop lookup DNS is a delegation system. A resolver starts at the root, gets a referral to a TLD, gets another referral to an authoritative server, and asks that server for the record. The root does not know the answer. It knows who does. These diagrams are wide. On a phone, pan them horizontally. ```svg DNS resolution walk A browser asks a recursive resolver for portfolio.swadhin. The resolver gets a referral from the private root, asks the .swadhin TLD, reaches the authoritative server, and caches the answer. One lookup, five hops The resolver walks from the private root to the authoritative server, then caches the answer. browser stub resolver portfolio.swadhin wants an IP recursive resolver 10.10.10.53 Unbound cache: empty private root a.root.swadhin 10.10.10.11 a/b/c identities .swadhin TLD ns1.swadhin 10.10.10.13 delegated by root authoritative portfolio.swadhin A 10.10.10.20 TTL 300 service https://portfolio.swadhin 1 ask 2 refer 3 delegate 4 answer 5 cache + return reverse proxy 5 return Yellow dot: the query. Dashed mint line: the cached answer on its way back. ``` The root zone is just another zone. It has an SOA, NS records, and glue. The public root has 13 named authorities and hundreds of instances behind them; [IANA lists the identities and addresses](https://www.iana.org/domains/root/servers). A private root is the same shape at a smaller scale: an SOA, NS records for the root servers, and a delegation for every TLD you want to serve. Here is the referral from my lab. The query is non-recursive, so the root only tells the resolver where to go next: ```bash $ dig @10.10.10.11 portfolio.swadhin +norecurse ;; ->>HEADER<<- opcode: QUERY, status: NOERROR ;; flags: qr; QUERY: 1, ANSWER: 0, AUTHORITY: 2, ADDITIONAL: 3 ;; AUTHORITY SECTION: swadhin. 300 IN NS ns1.swadhin. swadhin. 300 IN NS ns2.swadhin. ;; ADDITIONAL SECTION: ns1.swadhin. 300 IN A 10.10.10.13 ns2.swadhin. 300 IN A 10.10.10.14 ``` That is the entire trick. The root says: `swadhin.` is delegated to `ns1.swadhin.` and `ns2.swadhin.`, and here are their addresses. The resolver then asks one of those servers: ```bash $ dig @10.10.10.13 portfolio.swadhin ;; ->>HEADER<<- opcode: QUERY, status: NOERROR ;; flags: qr aa; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; ANSWER SECTION: portfolio.swadhin. 300 IN A 10.10.10.20 ``` The `aa` flag means the TLD server is authoritative for the answer. The root was authoritative only for the referral. The resolver caches both the answer and the referral, which is why the second lookup does not walk the tree again. ```svg Cold vs cached DNS lookup The first lookup walks from the resolver to the root, the TLD and the authoritative server. The second lookup is answered from the resolver cache. The tree is for the first query Caching is why the hierarchy is not on the critical path of every request. first lookup (cold) browser resolver root TLD auth 1 2 3 4 answer + cache second lookup (warm) browser resolver CACHE HIT 4 round trips 1 round trip Cold path: four delegations. Warm path: one cache lookup. The cache is the point. ``` This is also why the root is not the bottleneck people imagine. A cold query costs up to four round trips; a warm query costs one cache lookup. The hierarchy matters for correctness and delegation, not for every packet. ### Delegation, glue, and the thing that makes private roots work The root zone needs to know the addresses of the nameservers it delegates to. If those nameservers are inside the delegated zone, the root has a circular dependency: to resolve `ns1.swadhin` you need to reach `swadhin`, and to reach `swadhin` you need `ns1.swadhin`. Glue records break the loop. The root includes the A and AAAA records for `ns1.swadhin` and `ns2.swadhin` in the additional section, even though the authoritative copies live in the child zone. That is why a root server can answer a referral without being authoritative for the child. It is also why a private root is easy to start and hard to make consistent: every delegation needs glue, every glue record needs a matching authoritative record, and every mismatch is a future `SERVFAIL`. ### The public root is signed; yours is not The public root is signed with DNSSEC. A validating resolver has a trust anchor for the root's KSK, and every delegation below it can be validated down the chain. A private root has no such chain unless you build one. That is not a bug in DNS; it is the difference between a globally unique namespace and a local one. You have two honest choices: 1. Mark the private zone insecure in your resolver (`domain-insecure: "swadhin"`) and rely on the fact that only your LAN can reach it. 2. Sign the private zone with your own key and install the trust anchor in every resolver that needs to validate it. Both work. They have different failure modes. Do not disable DNSSEC validation globally just to make a private name resolve; that is how a lab accident becomes a security incident. ## What OpenInternet adds OpenInternet, as the project describes itself, is a naming and DNS platform for private TLDs, authoritative DNS, and programmable resolvers. The tagline is "own your namespace." The resolver endpoints are `dns.openinternet.org` over DoH, DoT, DoQ, and plain DNS. The docs describe a CLI for creating a TLD, creating a zone, adding a record, signing it, and publishing it to every edge region. The important part is not the CLI. It is the model: - A user owns a namespace, such as `.swadhin` or `.dex`. - The user runs an authoritative server for that namespace, or delegates it to one. - The OpenInternet resolver knows about the private root and asks it first. - Everything else is forwarded to the public root. - The home server and the main DNS server keep their zones in sync, so an update made at home is visible to anyone using the opt-in resolver. The project's status page is explicit that there is no hosted service in this build. The docs describe the intended system, not a live public root. That honesty matters: a landing page that hides the `NXDOMAIN` is selling something that cannot work on install. That last point is the part the sketch is reaching for: `git.swadhin` does not have to be a local-only name. It can be a name that resolves for anyone who chooses the OpenInternet resolver, while remaining invisible to `8.8.8.8`. ```mermaid sequenceDiagram participant Home as home primary participant Main as OpenInternet secondary participant Res as opt-in resolver Main->>Home: SOA query Home-->>Main: serial 2026102301 Main->>Home: AXFR or IXFR with TSIG Home-->>Main: zone and RRSIG Main->>Res: updated zone available Res-->>Res: cache and serve ``` The hard problem is stated plainly in the project's own docs: public resolvers are configured from the public root, and the public root has no delegation for `.swadhin`. So `NXDOMAIN` is the correct answer from Google DNS, Cloudflare, and every ISP resolver. Nothing short of a root delegation changes that. An alternative root only works for people who deliberately point at your resolver. That is not a bug to hide. It is the adoption problem to solve. The project's answer is to make opting in easy: a resolver, a client, a registry, and a sync path. The lab below is the same shape at home, with standard software, so you can see exactly what the resolver is doing. ```bash $ dig api.swadhin @8.8.8.8 ;; status: NXDOMAIN $ dig api.swadhin @dns.openinternet.org ;; status: NOERROR ``` The first answer is not a failure. It is the public internet being consistent. ## Three ways to get your own names at home There are three levels of "owning" a name. They solve different problems, and mixing them up is how people end up with a broken browser and a certificate warning they cannot click through. ### Level 1: the hosts file, or a dnsmasq rewrite The smallest version is a line in `/etc/hosts`: ```text 10.10.10.20 portfolio.swadhin 10.10.10.2 git.swadhin ``` Or a dnsmasq rule: ```text address=/swadhin/10.10.10.20 ``` This is fine for one machine and one afternoon. It does not work on phones, it does not support wildcards, it does not give you a zone, and it teaches you nothing about delegation. It is a shortcut, not a namespace. ### Level 2: split-horizon DNS with a real domain You own `example.com`. You create `home.example.com` in the public zone, but you do not publish private A records publicly. Your local resolver is authoritative for `home.example.com` and returns `10.10.10.x` for `git.home.example.com`. Outside your LAN, the same name returns `NXDOMAIN` (or a public placeholder). The public certificate is issued with a DNS-01 challenge, so it does not care that the A record is private. This is the level I recommend for anything a browser touches. It gives you: - Names that work on every device, because they are ordinary DNS names. - A publicly trusted certificate, because the name is in a public TLD. - No collision with a future gTLD, because you own the domain. - A clean split between the public view and the LAN view. ```svg Split-horizon DNS The same name resolves to a private address inside the LAN and to NXDOMAIN or a public placeholder outside it. Same name, two answers Split-horizon DNS keeps the public view and the LAN view apart. git.home.example.com one name, one question inside the LAN resolver 10.10.10.53 git.home.example.com → 10.10.10.20 reverse proxy in the closet outside resolver 1.1.1.1 git.home.example.com → NXDOMAIN no route to the closet boundary The name is not the answer. The resolver and the view are. ``` The cost is that you need a real domain and a public DNS provider that supports ACME DNS-01. That is a small cost compared with the certificate and client problems of a private TLD. ### Level 3: a private root and a private TLD This is the OpenInternet shape. You run a root zone, delegate `.swadhin` to your TLD servers, run authoritative servers for `swadhin.`, and point your resolver at the private root. You can use any label you want. You do not need a registrar. You can resolve names with no internet connection at all. The cost is everything the previous levels avoid: - Every client must use your resolver. - Encrypted DNS can silently bypass it. - Public CAs will not issue certificates for the name. - The name can collide with a future public TLD. - You are now the registry, the abuse desk, and the on-call rota. That is not a reason not to do it. It is a reason to do it in a lab, with a real domain alongside it for the services that matter. | | Hosts file | Split-horizon + real domain | Private root + private TLD | |---|---|---|---| | Setup time | minutes | an afternoon | a weekend | | Works on phones | no | yes | only with resolver configuration | | Publicly trusted TLS | no | yes, with DNS-01 | no, unless you run a local CA | | Public reach | no | optional | no | | Collision risk | low | none | depends on the label | | Maintenance | one file | zone + resolver + ACME | root + TLD + resolver + clients | | Best for | a quick test | home services you actually use | learning, labs, opt-in namespaces | ```mermaid flowchart TD A[Does the name need to work outside your LAN?] -->|Yes| B[Own a real domain] B --> C[Split-horizon DNS + DNS-01 wildcard] A -->|No| D{Do phones and browsers need HTTPS?} D -->|Yes| E[.internal + local CA] D -->|No| F[Private root + private TLD] C --> G[Certificate the client trusts, private A records] E --> G F --> H[Opt-in resolver only] ``` ### Pick a namespace that will not bite you later The label matters more than the software. - **`.internal`** is reserved by ICANN for private use. The Board permanently reserved it from delegation on 29 July 2024 ([resolution 2024.07.29.06](https://www.icann.org/en/board-activities-and-meetings/materials/approved-resolutions-special-meeting-of-the-icann-board-29-07-2024-en)). It will never be a public gTLD, so it is the safest vanity-free choice for a private DNS namespace. - **`.home.arpa`** is reserved for home networks by [RFC 8375](https://www.rfc-editor.org/rfc/rfc8375). It is longer, but it is explicitly designed for this and it is delegated to blackhole servers in the public root, so queries that leak do not reach a real authority. - **`.local`** is reserved for multicast DNS by [RFC 6762](https://www.rfc-editor.org/rfc/rfc6762). Do not use it for unicast DNS. Printers, Apple devices, and service discovery will fight you. - **`.dev`, `.app`, `.page`, `.new`, and `.day`** are HSTS-preloaded at the TLD level. Every HTTP request is upgraded to HTTPS before it leaves the browser. If you use one of these for a local name, you need a valid certificate before you can serve a single page. They are great for real sites and terrible for lab names. - **`.swadhin`** is fine inside your own root. It is not fine as a name you depend on, because a future gTLD round could delegate it, and because no public CA will issue for it today. Treat it as a lab namespace, not a public identity. If you want the OpenInternet shape without the collision risk, use `.internal` for the private TLD and keep a real domain for the browser-facing services. The private root can delegate `internal.` just as easily as `swadhin.`. ## The lab I used `10.10.10.0/24` because that is what the sketch used. If your LAN already uses that subnet, change it everywhere; the protocol does not care. I tested with `172.28.10.0/24` in containers to avoid a Docker gateway collision, then translated the addresses back to the sketch for this article. | Address | Role | Software | |---|---|---| | `10.10.10.11` | root a | PowerDNS authoritative | | `10.10.10.12` | root b | PowerDNS secondary | | `10.10.10.13` | `.swadhin` TLD a | PowerDNS authoritative | | `10.10.10.14` | `.swadhin` TLD b | PowerDNS secondary | | `10.10.10.53` | recursive resolver | Unbound | | `10.10.10.20` | portfolio / preview | Caddy or nginx | | `10.10.10.2` | git | Forgejo or Gitea on `:8909` | | `10.10.10.30` | api | your app | You do not need four physical machines. Two small VMs or containers per role are enough for a lab. The important part is that the root and the TLD are separate authorities, so you can see the referral. If you put both zones on one server, PowerDNS will answer from the child zone and the delegation step disappears from the output. ### The root zone ```text $ORIGIN . $TTL 300 @ IN SOA a.root.swadhin. hostmaster.swadhin. ( 2026102301 ; serial 3600 ; refresh 900 ; retry 604800 ; expire 300 ) ; negative TTL @ IN NS a.root.swadhin. @ IN NS b.root.swadhin. a.root.swadhin. IN A 10.10.10.11 b.root.swadhin. IN A 10.10.10.12 ; delegate the user namespace swadhin. IN NS ns1.swadhin. swadhin. IN NS ns2.swadhin. ns1.swadhin. IN A 10.10.10.13 ns2.swadhin. IN A 10.10.10.14 ``` The `a.root.swadhin` and `b.root.swadhin` records are glue for the root's own nameservers. The `ns1.swadhin` and `ns2.swadhin` records are glue for the child. Both sets are necessary because both nameservers live below the root they serve. ### The `.swadhin` zone ```text $ORIGIN swadhin. $TTL 300 @ IN SOA ns1.swadhin. hostmaster.swadhin. ( 2026102301 ; serial 3600 ; refresh 900 ; retry 604800 ; expire 300 ) ; negative TTL @ IN NS ns1.swadhin. @ IN NS ns2.swadhin. ns1 IN A 10.10.10.13 ns2 IN A 10.10.10.14 a.root IN A 10.10.10.11 b.root IN A 10.10.10.12 portfolio IN A 10.10.10.20 portfolio IN AAAA fd00:10:10::20 preview IN A 10.10.10.20 git IN A 10.10.10.2 git IN AAAA fd00:10:10::2 api IN A 10.10.10.30 www IN CNAME portfolio _https._tcp.git IN SRV 0 5 8909 git.swadhin. ``` A few details that matter: - `www` is a CNAME, which is fine at a subdomain. Do not put a CNAME at the apex; use an ALIAS/ANAME if your DNS software supports it, or just an A/AAAA pair. - The SRV record documents the port for clients that understand SRV. Browsers do not. If you want `https://git.swadhin` without a port, put a reverse proxy on 443 in front of the service on 8909. - The AAAA records use a ULA prefix (`fd00:10:10::/64`). ULA is the IPv6 equivalent of RFC 1918; it is not globally routable, which is exactly what you want for a private namespace. - The negative TTL (the last SOA field) is 300 seconds. Do not set it to 0 just because you are iterating; negative caching is what stops a typo from hammering your root. Validate the child zone before you load it: ```bash $ pdnsutil check-zone swadhin 0 errors, 0 warnings. ``` The root zone is small enough that the referral itself is the best test. If `dig +norecurse` returns the NS and glue you expect, the zone is doing its job. ### The authoritative servers I used PowerDNS 4.9 with the BIND backend. The backend reads ordinary zone files, which keeps the whole lab reviewable in git. The primary serves the zone; the secondary transfers it with AXFR. `/etc/powerdns/named.conf` on the root primary: ```text options { directory "/zones"; also-notify { 10.10.10.12; }; }; zone "." { type primary; file "root.zone"; also-notify { 10.10.10.12; }; }; ``` `/etc/powerdns/pdns.conf` on the same host: ```text local-address=0.0.0.0 launch=bind bind-config=/etc/powerdns/named.conf primary=yes allow-axfr-ips=10.10.10.12,10.10.10.14 also-notify=10.10.10.12 loglevel=4 ``` `primary=yes` is the setting that bit me. In PowerDNS 4.9 it defaults to `no`. Without it, the zone loads and answers queries, but `pdns_control notify` refuses to queue a notification and the secondary never learns that the zone changed. The zone is not "primary" just because the file says `type primary`; the server has to be configured to act as one. The secondary: ```text options { directory "/zones"; }; zone "." { type secondary; file "slave/root.zone"; masters { 10.10.10.11; }; }; ``` ```text local-address=0.0.0.0 launch=bind bind-config=/etc/powerdns/named.conf secondary=yes loglevel=4 ``` The first transfer can be forced with `pdns_control retrieve .` on the secondary. After that, `pdns_control notify .` on the primary queues a NOTIFY and the secondary checks the SOA serial. The same pattern applies to the `.swadhin` zone with the TLD addresses. ```bash $ pdns_control retrieve . Added retrieval request for '.' from primary 10.10.10.11 $ dig @10.10.10.12 . NS +short b.root.swadhin. a.root.swadhin. ``` In production, restrict `allow-axfr-ips` to the secondaries, not the whole LAN, and add TSIG if your backend supports it. The BIND backend's AXFR security is IP-based; if you need signed transfers, check the backend's TSIG support or use the gsqlite3/PostgreSQL backend, and put the transfer on a private management network so the IP ACL is one layer of several. ### The resolver Unbound does two jobs in this lab: it answers for the private namespace, and it forwards everything else to public resolvers over DNS-over-TLS. ```text server: interface: 0.0.0.0 port: 53 access-control: 10.10.10.0/24 allow access-control: 127.0.0.0/8 allow do-ip6: yes prefer-ip6: no qname-minimisation: yes harden-dnssec-stripped: yes cache-min-ttl: 60 cache-max-ttl: 86400 private-domain: "swadhin" domain-insecure: "swadhin" local-zone: "swadhin." nodefault tls-cert-bundle: "/etc/ssl/certs/ca-certificates.crt" forward-zone: name: "." forward-tls-upstream: yes forward-addr: 1.1.1.1@853#cloudflare-dns.com forward-addr: 9.9.9.9@853#dns.quad9.net stub-zone: name: "swadhin." stub-addr: 10.10.10.13 stub-addr: 10.10.10.14 stub-prime: no ``` What each block is doing: - `stub-zone` sends queries for `swadhin.` directly to the TLD servers. This is a shortcut: the private root is still the delegation source, but the resolver does not need to ask it on every cold query. If you want to watch the full walk, query the root directly with `dig +norecurse`. - `forward-zone "."` sends everything else to Cloudflare and Quad9 over DoT. Unbound still caches and applies DNSSEC validation where the upstream provides it. - `domain-insecure: "swadhin"` tells Unbound not to expect a DNSSEC chain for the private zone. If you sign the zone, replace this with a `trust-anchor` for `swadhin.`. - `private-domain: "swadhin"` allows private addresses in answers for that domain. Without it, Unbound's rebinding protection can filter the `10.10.10.x` answers you just configured. - `local-zone: "swadhin." nodefault` stops Unbound from applying its default local-zone behavior to the name. - `tls-cert-bundle` is a server option, not a forward-zone option. Putting it in the wrong block is a syntax error; I know because I did it. Test both halves: ```bash $ dig +short @10.10.10.53 portfolio.swadhin 10.10.10.20 $ dig +short @10.10.10.53 example.com A 104.20.23.154 172.66.147.243 ``` If you want the resolver to walk the private root for every cold query, run a second Unbound instance with a private root hints file: ```text . 3600 IN NS a.root.swadhin. . 3600 IN NS b.root.swadhin. a.root.swadhin. 3600 IN A 10.10.10.11 b.root.swadhin. 3600 IN A 10.10.10.12 ``` ```text server: root-hints: "/etc/unbound/private-root.hints" domain-insecure: "swadhin" ``` That instance can only resolve the private namespace. It cannot also resolve `example.com`, because its root only knows about `.swadhin`. This is the architectural fork that alternative-root projects have to solve: either the private root mirrors the public root (and then DNSSEC gets complicated), or the resolver decides which root to ask based on the name (the "ours first, public fallback" model). At home, the stub-zone is the simpler version of the same decision. ### The cache, measured I ran 100 UDP queries per resolver from my laptop on 23 October 2026. The numbers are not a benchmark; they are a sanity check on where the time goes. ```chart { "type": "bar", "data": { "labels": ["cached answer", "split resolver (stub)", "full recursion (cold)"], "datasets": [{ "label": "DNS round trips", "data": [1, 2, 4], "backgroundColor": ["#a6e3a1", "#89b4fa", "#cba6f7"], "borderRadius": 6 }] }, "options": { "responsive": true, "plugins": { "legend": { "display": false } }, "scales": { "y": { "beginAtZero": true, "ticks": { "stepSize": 1 }, "title": { "display": true, "text": "round trips" } } } } } ``` ```chart { "type": "bar", "data": { "labels": ["8.8.8.8 (30.05 ms)", "1.1.1.1 (1.58 ms)", "9.9.9.9 (1.53 ms)", "local Unbound (0.01 ms)"], "datasets": [{ "label": "median query time (ms)", "data": [30.05, 1.58, 1.53, 0.01], "backgroundColor": ["#f38ba8", "#89b4fa", "#89dceb", "#a6e3a1"], "borderRadius": 6 }] }, "options": { "indexAxis": "y", "responsive": true, "plugins": { "legend": { "display": false } }, "scales": { "x": { "beginAtZero": true, "title": { "display": true, "text": "milliseconds" } }, "y": { "ticks": { "autoSkip": false } } } } } ``` The local bar is small because the resolver was on the same Docker bridge as the client. On a real LAN it will be a fraction of a millisecond to a couple of milliseconds, not 0.01. The point is not the exact number. The point is that the cache is doing the work, and the hierarchy is paid once. ### DHCP and the resolver handoff The best DNS server in the world is useless if the client never asks it. Hand out the resolver explicitly. With dnsmasq as a DHCP-only server: ```text port=0 dhcp-range=10.10.10.100,10.10.10.200,12h dhcp-option=6,10.10.10.53 dhcp-option=15,swadhin dhcp-option=option6:dns-server,[fd00:10:10::53] ``` `port=0` disables dnsmasq's DNS listener; Unbound owns port 53. If you use dnsmasq as the DNS forwarder instead, forward the private zone explicitly and allow rebinding for it: ```text server=/swadhin/10.10.10.13 server=/swadhin/10.10.10.14 rebind-domain-ok=/swadhin/ ``` If the router is your DHCP server, set the LAN DNS server in the router to `10.10.10.53` and make sure it is not also advertising the ISP resolver as a second option. A second DNS server is a fallback, not a preference: clients may use either one, and the one that does not know `.swadhin` will return `NXDOMAIN`. ## Clients are where private DNS goes to die Every client has its own resolver logic. The ones that matter are the ones that bypass DHCP without telling you. | Client | What to set | What bypasses your resolver | |---|---|---| | Linux (systemd-resolved) | `DNS=10.10.10.53`, `Domains=~.` | a per-link DNS setting or a VPN | | Linux (NetworkManager) | `ipv4.dns`, `ipv4.ignore-auto-dns yes` | a connection profile you forgot | | macOS | `networksetup -setdnsservers Wi-Fi 10.10.10.53` | a DNS profile or a VPN | | Windows | `Set-DnsClientServerAddress` | Windows 11 DoH, if enabled | | Android | Private DNS off or automatic | a Private DNS hostname | | iOS | Wi-Fi DNS settings or a DNS profile | iCloud Private Relay for Safari | | Chrome | Secure DNS off, or a custom provider you control | Secure DNS automatic mode | | Firefox | `network.trr.mode = 0` | TRR mode 2 or 3 | | Edge | Windows resolver settings | Edge Secure DNS | ### Linux With systemd-resolved: ```ini # /etc/systemd/resolved.conf [Resolve] DNS=10.10.10.53 FallbackDNS= Domains=~. DNSOverTLS=no ``` ```bash sudo systemctl restart systemd-resolved resolvectl status resolvectl query portfolio.swadhin ``` `Domains=~.` makes this resolver the default route for all names. If you only want it for the private namespace, use `Domains=~swadhin` and keep your normal resolver for everything else. That is split DNS at the stub level, and it is often the least disruptive option on a work laptop. With NetworkManager: ```bash sudo nmcli con mod "Wired connection 1" \ ipv4.dns "10.10.10.53" \ ipv4.ignore-auto-dns yes \ ipv6.dns "fd00:10:10::53" \ ipv6.ignore-auto-dns yes sudo nmcli con up "Wired connection 1" ``` ### macOS and iOS ```bash sudo networksetup -setdnsservers Wi-Fi 10.10.10.53 scutil --dns | grep nameserver sudo dscacheutil -flushcache sudo killall -HUP mDNSResponder ``` On iOS, set the DNS server manually for the Wi-Fi network, or install a DNS settings profile if you manage the device. A private TLD is not a good DoT hostname: iOS has to resolve the hostname before it can open the TLS connection, and the private name is exactly what it cannot resolve yet. Use a public hostname for the encrypted resolver, or keep plain DNS on the LAN. ### Windows ```powershell Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses 10.10.10.53 Clear-DnsClientCache Resolve-DnsName portfolio.swadhin ``` Windows 11 can use DoH automatically for resolvers it recognizes. A local resolver is not on that list, so it usually stays on plain DNS, but Edge and Chrome can still make their own choice. ### Android Android's Private DNS setting has three modes: Off, Automatic, and Private DNS provider hostname. Automatic upgrades to DNS-over-TLS when the network's resolver supports it; if your Unbound only speaks plain DNS, the phone stays on plain DNS. If you enter a hostname, Android sends all queries over DoT to that hostname and marks the network as having no internet access if it cannot connect. That means: - `dns.openinternet.org` works as a Private DNS hostname if it is reachable and has a valid certificate. - `dns.swadhin` does not, unless Android can resolve it before it connects, which it cannot because it is the thing you are trying to configure. - If you want the phone to use your home resolver over the internet, give the resolver a public hostname and a public certificate, or use a VPN. Do not put a private TLD in the Private DNS field. ### Chrome, Firefox, and Edge Chrome's Secure DNS is on by default in automatic mode. If Chrome decides to use a DoH provider, it bypasses the operating system's resolver, including your Unbound server. For the lab, open `chrome://settings/security`, turn Secure DNS off, or set a custom provider that you control. A custom provider is a DoH URL with a valid certificate; `https://dns.swadhin/dns-query` will not work unless Chrome already trusts your local CA and can resolve the name. Firefox has its own switch. In `about:config`: - `network.trr.mode = 0` disables TRR. - `network.trr.mode = 2` uses TRR as a fallback. - `network.trr.mode = 3` uses TRR only. If you run DoH on your own resolver, set `network.trr.uri` to your endpoint and make sure Firefox trusts the certificate. Firefox uses its own trust store on many platforms, so a local CA installed in the OS may not be enough. Edge follows Windows' resolver settings, but its Secure DNS feature can still make its own choice. Check `edge://settings/privacy` if a name resolves in `dig` but not in the browser. ### The one-minute test Before you blame the server, check which resolver the client is actually using: ```bash dig +short @10.10.10.53 portfolio.swadhin dig +short portfolio.swadhin resolvectl query portfolio.swadhin curl -v --resolve portfolio.swadhin:443:10.10.10.20 https://portfolio.swadhin/ ``` If the first command works and the second does not, the server is fine and the client is using a different resolver. That is the single most useful debugging fact in this entire article. ## TLS is the wall A private TLD can resolve perfectly and still be unusable in a browser. The browser does not care that your DNS works. It cares that the certificate chains to a trust anchor it recognizes. Public CAs are not allowed to issue certificates for internal names. The CA/Browser Forum's baseline requirements have prohibited new certificates for internal names and reserved IP addresses since November 2015 ([CA/Browser Forum guidance](https://cabforum.org/working-groups/server/internal-names/)). Let's Encrypt's own documentation says it cannot issue for `localhost` because nobody uniquely owns it and it is not rooted in a public TLD ([Let's Encrypt](https://letsencrypt.org/docs/certificates-for-localhost/)). A private TLD has the same problem: there is no public delegation, no domain validation, and no chain. You have three options. ### 1. A real domain with a DNS-01 wildcard (recommended) Use a subdomain of a domain you own, for example `home.example.com`. Keep the public zone at your registrar or DNS provider. Publish the `_acme-challenge` TXT record for DNS-01, but do not publish private A records. Your internal resolver answers `*.home.example.com` with `10.10.10.x`. ```bash sudo apt install certbot python3-certbot-dns-cloudflare sudo certbot certonly \ --dns-cloudflare \ --dns-cloudflare-credentials /root/.secrets/cloudflare.ini \ -d '*.home.example.com' -d home.example.com ``` The certificate is publicly trusted because the ACME server only needs the TXT record. The A record can stay private. This is the pattern I use for anything that needs to work in a browser without a warning. Caddy with the existing certificate: ```text git.home.example.com { tls /etc/letsencrypt/live/home.example.com/fullchain.pem /etc/letsencrypt/live/home.example.com/privkey.pem reverse_proxy 10.10.10.2:8909 } ``` If you want Caddy to manage the certificate itself, use a Caddy build with the DNS provider plugin, or run certbot on a timer and reload Caddy. The stock Caddy binary does not include every DNS provider. ### 2. A local CA For internal tools that never leave the LAN, a local CA is fine. `mkcert` is the shortest path: ```bash mkcert -install mkcert git.swadhin portfolio.swadhin ``` Install the generated root CA on every device that needs to trust it. Caddy can do the same thing without mkcert: ```text git.swadhin { tls internal reverse_proxy 10.10.10.2:8909 } ``` `caddy trust` installs Caddy's local root on the machine where it runs. For other devices, export the root certificate from Caddy's data directory (`~/.local/share/caddy/pki/authorities/local/root.crt` on Linux) and install it in the system trust store. The limits are real: - Android apps that target Android 7 or later do not trust user-installed CAs by default. Chrome may, depending on the trust store and the version; do not assume every app will. - Firefox uses its own trust store on many platforms. Installing the root in the OS is not always enough. - A local CA is a new root of trust. If its private key leaks, every certificate it signed is compromised. Keep it offline or on a machine that is not your web server. - Certificate rotation is manual unless you automate it. A local CA without automation becomes a yearly outage. ### 3. Plain HTTP, carefully Some services do not need a browser: SSH, git over SSH, a metrics endpoint behind a VPN. For those, plain HTTP or a private protocol is fine. Do not put a login form or a session cookie on plain HTTP, and do not enable HSTS on a lab name unless you are prepared to wait out the max-age if you change your mind. ### The cookie and public-suffix problem `.swadhin` is not on the Public Suffix List. A cookie set for `.swadhin` is sent to every service under that name. If `portfolio.swadhin` is compromised, it can set a cookie that `git.swadhin` will receive. Treat the whole private TLD as one trust domain, or use separate real subdomains for services with different trust levels. A real domain gives you the public-suffix boundary and the certificate ecosystem for free. ## Operations, security, and the things that fail at 2 a.m. ### Do not run an open resolver An open recursive resolver on the public internet is a amplification reflector. [RFC 5358](https://www.rfc-editor.org/rfc/rfc5358) explains the problem and the mitigations. Bind Unbound to the LAN, allow only your subnets, and firewall port 53 from the WAN. ```text access-control: 10.10.10.0/24 allow access-control: 127.0.0.0/8 allow ``` ```bash sudo ufw allow from 10.10.10.0/24 to any port 53 proto udp sudo ufw allow from 10.10.10.0/24 to any port 53 proto tcp ``` If you need remote access, use WireGuard and keep DNS inside the tunnel. Do not expose port 53 to the internet so you can resolve `git.swadhin` from a coffee shop. ### Rate limit and monitor Put `dnsdist` in front of PowerDNS or Unbound if you need response rate limiting, query logging, or a single place to apply ACLs. At home, the LAN ACL is usually enough; the point is to know where the control point is. Useful checks: ```bash dig +short @10.10.10.11 . SOA dig +short @10.10.10.13 swadhin. SOA pdns_control show '*' # unbound-control requires remote-control: control-enable: yes unbound-control stats_noreset ``` Alert on four things: - The secondary's SOA serial is behind the primary's. - `SERVFAIL` or `REFUSED` responses are rising. - The resolver's cache hit ratio is falling. - The authoritative servers stop answering on TCP as well as UDP. ### DNSSEC, if you want it Signing the private zone is possible. With PowerDNS: ```bash pdnsutil secure-zone swadhin pdnsutil show-zone swadhin pdnsutil export-zone-ds swadhin pdnsutil export-zone-dnskey swadhin ``` The BIND backend needs a DNSSEC database: ```text bind-dnssec-db=/var/lib/powerdns/bind-dnssec.db ``` ```bash pdnsutil create-bind-db /var/lib/powerdns/bind-dnssec.db ``` Then put the trust anchor in Unbound and remove `domain-insecure`: ```text trust-anchor: "swadhin. DNSKEY 257 3 13 " ``` Test with `dig +dnssec` and look for the `ad` flag from the resolver. Remember that a private trust anchor only means something to resolvers you configured. It does not make the zone publicly valid, and it does not give you a public certificate. ### Backups and change control Keep the zone files in git. A DNS change is a code change: review it, test it, and be able to roll it back. Bump the SOA serial on every change; `YYYYMMDDnn` is easy to read and sort. Use `pdnsutil check-zone` in CI, and keep a copy of the DNSSEC keys somewhere that is not the primary server. A simple change flow: 1. Edit the zone file in a branch. 2. Run `pdnsutil check-zone `. 3. Merge, bump the serial, reload the primary. 4. Confirm the secondary transferred: `dig @secondary SOA`. 5. Run a query for a known record from a client that uses the resolver. ### The failure modes I actually hit | Symptom | Cause | Fix | |---|---|---| | `NXDOMAIN` from `8.8.8.8` for `.swadhin` | public root has no delegation | expected; use your resolver | | `dig` works, browser searches | browser treats the name as a search term, or uses DoH | use the FQDN, disable Secure DNS | | `SERVFAIL` for public names after pointing at the private root | the private root only knows the private namespace | use a split resolver or forward public names | | Secondary has no zone | `primary=yes`/`secondary=yes` missing, or AXFR ACL | set the role, allow the secondary IP, `pdns_control retrieve` | | `SERVFAIL` for private names | missing glue, wrong NS, or `domain-insecure` not set | check the referral and the child zone | | Browser certificate warning | private TLD has no publicly trusted cert | real domain + DNS-01, or install the local CA | | Phone ignores the resolver | Android Private DNS or iOS profile | set Private DNS off/automatic, or use a public DoT hostname | | LAN client cannot reach a public name | hairpin NAT or split-horizon mismatch | return the private address internally, or enable NAT loopback | | Resolver returns a public IP for a private name | split-horizon view not applied | check the stub/forward order and the search domain | ## The honest limits of an alternative root The lab works. That does not mean the model scales. DNS is a delegation system, and delegation is a social contract. The public root works because resolvers agree to start at the same root identities and follow the same chain. A private root works because you configured your resolver to start somewhere else. Both are technically valid. Only one is universally reachable. Alternative roots have three structural problems: 1. **The namespace is ambiguous.** `api.swadhin` means one thing on your resolver and nothing on Google DNS. A user cannot tell which root they are on from the name alone. That is a phishing surface, a support burden, and a reason browsers and CAs are conservative. 2. **The trust is local.** A private TLD cannot get a public certificate. A private root cannot be validated by a resolver that does not have your trust anchor. The moment you leave your network, the name stops being an identity and becomes a string. 3. **The operations are real.** A root is not a zone file. It is a registry, an abuse desk, a trademark policy, a key ceremony, and an anycast network. ICANN is slow because coordination is hard and the alternatives have their own failure modes. A hobby root can skip all of that only because nobody depends on it. OpenInternet's honest framing is the right starting point: public resolvers return `NXDOMAIN`, and that is correct. The product cannot fix that from its side alone. What it can do is make opting in cheap: a resolver that checks the private root first, a client that configures itself, a registry that makes delegation a one-command operation, and a sync path that keeps a home authoritative server and the main service in step. That is a real product. It is not a replacement for the public root, and it does not need to be. The pragmatic architecture is the hybrid: - Own a real domain. Use it for anything a browser touches. - Delegate a subdomain to your home authoritative server. Keep the public view minimal. - Run split-horizon DNS so the LAN gets private addresses and the public gets `NXDOMAIN` or a placeholder. - Automate certificates with DNS-01. - Use a private TLD such as `.internal` for the lab, for SSH, for git, for metrics, and for names that never need to leave. - Use the OpenInternet-style private root when you want to learn how delegation works, or when you are building a namespace that people deliberately opt into. The open internet is not a single root that you replace. It is a set of protocols that let people run their own corner without asking permission. Running your own DNS is a good start. Running your own certificate authority, your own resolver, and your own registry is the rest of the lesson. The hard part is not the software. The hard part is deciding who should be able to resolve the name, and what happens when they cannot. ## A checklist for the first weekend 1. Pick a namespace you can live with: `.internal` for private names, a real subdomain for browser-facing services, `.swadhin` only inside your own root. 2. Draw the address plan. Root, TLD, resolver, services. Put the root and TLD on separate authorities so you can see the referral. 3. Write the root zone and the child zone. Add glue for every nameserver. Check the child with `pdnsutil check-zone`. 4. Run two authoritative servers per zone. Set `primary=yes` and `secondary=yes`, restrict AXFR, and test a transfer. 5. Run Unbound with a stub for the private zone and a DoT forward for everything else. Mark the private zone insecure until you sign it. 6. Hand out the resolver with DHCP option 6 and IPv6 RDNSS. Remove the ISP resolver from the list. 7. Turn off Secure DNS in Chrome and Firefox for the lab. Check Android Private DNS. Test from a phone, not just the laptop. 8. Put the browser-facing services behind a real domain and a DNS-01 wildcard. Use a local CA only for tools that never leave the LAN. 9. Firewall port 53 from the WAN. Rate limit if you expose anything. Monitor the secondary serial and the resolver's cache. 10. Write down what only works on your network. That list is the difference between a lab and a service. The sketch on my wall is not a replacement for ICANN. It is a reminder that DNS is a protocol, not a permission slip. You can run the same delegation logic in your closet, teach it to your devices, and learn more about the internet in a weekend than a year of reading. Just do not call it production until you have solved certificates, encrypted DNS, and the second server. The name is yours when the resolver agrees to ask. Everything else is configuration. --- ## OpenCode wrote 125,000 loose Git objects into my home directory and never committed once - URL: https://blog.swadhin.cv/blog/opencode-btrfs-metadata-exhaustion/ - Published: 2026-09-28T11:08:45.170Z - Updated: 2026-09-28T11:08:45.000Z - Author: Swadhin Biswas - Categories: Backend, DevOps - Excerpt: 20% of my disk free, 2% CPU, 29% RAM, and the machine still hung. Btrfs metadata was 93% full and 125,000 of the files were loose Git objects from an agent snapshot layer. ### Content My machine started hanging a few days ago. Applications crashed, the desktop stuttered, and nothing I did made it better. The numbers I reached for first all looked healthy, which is exactly why it took me a while to find the real cause. Here is what I saw: - 476 GB partition, roughly 20% still free - CPU around 2% - RAM around 29% - no runaway process, no memory pressure, no disk that was actually full Nothing about that list explains a machine that cannot keep a window open. So I went looking at the filesystem instead of the load average. ## The number that explained it Btrfs splits a device into a data block group and a metadata block group, and the two fill independently. `df` only ever shows you the data side. The metadata side is where every inode, every directory entry, and every extent record lives, and when it fills up, allocation starts failing and the filesystem gets slow even though you have a third of your disk free. ```bash btrfs filesystem usage -T /home ``` ``` Data Metadata System Id Path single DUP DUP Unallocated Total Slack -- -------------- --------- -------- -------- ----------- --------- ------- 1 /dev/nvme0n1p2 - - - 476.44GiB 476.44GiB 3.00KiB -- -------------- --------- -------- -------- ----------- --------- ------- Total 452.42GiB 12.00GiB 8.00MiB 476.44GiB 476.44GiB 3.00KiB Used 391.47GiB 11.17GiB 80.00KiB ``` Data ratio is `1.00` and metadata ratio is `2.00`, so the 12.00 GiB "Total" line is two mirrored copies of roughly 6 GiB each. The `Used` figure of 11.17 GiB is also both copies, which puts the real metadata space at 93% full. That is the whole story of the hang. 60 GiB of free data space sitting there while the part of the filesystem that has to be updated on every single file operation had almost no room left. I want to correct one number from my own issue report before going further. I originally attributed about 8 GB of that metadata to one application. That does not survive arithmetic. 125,000 files at roughly 2 KB of metadata each is about 250 MB. What the application really had was 33 GB of data and 125,000 files. The symptom was real, the attribution was wrong. ## Finding the writer The next step was to find what was creating files faster than anything else on the machine. ```bash du -sh ~/.local/share/opencode/* find ~/.local/share/opencode/snapshot -type f | wc -l ``` ``` 34G /home/swadhin/.local/share/opencode/snapshot 365M .../opencode.db 38M .../log/opencode.log 16M .../tool-output 12M .../shell ``` ``` 125829 ``` 125,829 files, 3,107 directories, 33 GB. Everything else in that directory was rounding error. Thirteen session directories, and every one of them was a Git repository. ## What the snapshot layer actually does OpenCode keeps a hidden Git repository so it can undo file changes inside a session. The docs are upfront that it is a Git repository and that it can be a problem on large trees: > For large repositories or projects with many submodules, the snapshot system > can cause slow indexing and significant disk usage as it tracks all changes > using an internal git repository. The docs also give the switch. In `opencode.json`: ```json { "$schema": "https://opencode.ai/config.json", "snapshot": false } ``` I did not have that set, on OpenCode v2.0.18. The interesting part is what the repository looked like when I got to it. ```bash cd ~/.local/share/opencode/snapshot/global/4fc815f20b5b347c8529f0d3cd0a0b48750fb6ac cat HEAD git count-objects -vH git log --oneline | wc -l ``` ``` ref: refs/heads/master count: 98935 size: 32.96 GiB in-pack: 0 packs: 0 ``` ``` 0 ``` `HEAD` points at `refs/heads/master` and `refs/` is empty. There are 98,935 loose objects and not a single commit. The `config` file in that same directory names the worktree it was built from: ``` [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true worktree = /home/swadhin/BDFASHION ``` So for that one project, OpenCode hashed essentially the entire tree into loose Git objects, wrote a 7.8 MB index, and then never wrote a commit. Twelve of the thirteen session repos were in the same state. ## Why zero commits is the bad case A Git repository with commits has a garbage collector. Objects get packed, unreferenced ones get pruned, and a repo that grew too big eventually shrinks. A repository with 98,935 loose objects and no refs has none of that. Every object is unreferenced, and unreferenced loose objects are never cleaned up because there is nothing that would ever want them gone. The size distribution explains where the 33 GB went: | Object size | Count | |---|---| | under 1 KB | 5,977 | | 1 KB to 64 KB | 11,596 | | 64 KB to 1 MB | 73,439 | | 1 MB and up | 7,924 | Those 7,924 files over 1 MB are the disk cost. The other 90,000 are the metadata cost, and they are the part that hurts on Btrfs. The mechanism is straightforward: ```mermaid graph TD A[Session starts] --> B[OpenCode creates a shadow git repo] B --> C[git hash-object per file in the tree] C --> D[objects/xx/yyyy loose object files] D --> E[No commit, no refs] E --> F[Nothing prunes them] ``` Each of those objects is a real file on disk. On ext4 or XFS that is unpleasant but survivable. On Btrfs, where the metadata pool is shared and finite and the copy-on-write log has to be updated on every allocation, it is the thing that takes the filesystem down. ## The fix ```bash du -sh ~/.local/share/opencode/snapshot rm -rf ~/.local/share/opencode/snapshot btrfs filesystem usage -T /home ``` I also set `snapshot: false` in `~/.config/opencode/opencode.json`. The cost is that I lose the revert button in the TUI for files the agent changed. I would rather have that than a filesystem that hangs the whole machine, and on my setup I almost never need a session-level undo because every real project is already a Git repository with its own history. ## What I would tell past-me Check the metadata block group, not `df`, the first time a Btrfs box starts misbehaving with free space on the display. It takes one command. If you run a coding agent on a large repository, set `snapshot: false` before you need it. The cost is one feature. The alternative is a hidden repository under your home directory that grows with no upper bound and no cleanup. And when something writes more than its share of a filesystem, go read its config files. The answer was in a `worktree` line in a bare Git config inside `~/.local/share`, and it took ten minutes once I knew to look there. --- ## Designing data pipelines that stay cheap - URL: https://blog.swadhin.cv/blog/designing-data-pipelines-that-stay-cheap/ - Published: 2026-09-24T15:00:00.000Z - Updated: 2026-09-23T20:32:27.000Z - Author: Swadhin Biswas - Categories: System Design, Data Engineering, Backend, Performance, Architecture - Excerpt: Efficient pipeline design is mostly a set of decisions about bytes scanned, work repeated, and failures survived. Here is how I reason through them, with the arithmetic shown. ### Content Every pipeline starts cheap and gets expensive in the same way. A job is written to scan everything because everything is small, the data grows, and the job keeps scanning everything. Nobody notices until the warehouse bill or the run time becomes a weekly conversation. Efficient pipeline design is mostly a set of decisions made early that keep that from happening. ## What efficient actually means Fast is the easy metric to reach for and the wrong one to optimise alone. A pipeline that finishes in two minutes but recomputes the same three years of history every night is not efficient, and neither is one that is cheap but delivers yesterday's numbers when the team needs this hour's. I hold four things at once: - **Cost per row delivered.** The bill divided by the rows that actually reach a consumer. It falls when you scan less and rise when you process data nobody reads. - **Freshness.** The gap between an event happening and it being queryable. This is a requirement you get from the consumer, not a number you pick. - **Correctness.** Results that are the same whether the job ran once or three times. Anything less and every incident becomes an argument about which numbers to trust. - **Operability.** How much attention it needs. A pipeline that pages someone every night is expensive in a way the invoice does not show. Most of the design work is choosing where to spend between these, and the usual mistake is spending on freshness when nobody asked for it. ## Work backwards from the consumer Before choosing a tool, I write down who reads the output and how often. A dashboard refreshed every morning and an alert that has to fire within a minute are different products, and the second one costs an order of magnitude more to run. The consumer sets the freshness budget, and the freshness budget sets almost everything else. A useful question early: what is the smallest useful answer? If a dashboard shows daily totals, the pipeline should produce daily totals, not raw events that the dashboard aggregates on every load. Moving aggregation upstream is the single most reliable way to cut cost, because it shrinks the number of rows that leave the pipeline. ## The shape Most of my pipelines settle into the same shape, which people call the medallion layout. Names vary; the idea is that data lands untouched, gets cleaned once, and gets modelled for a specific consumer. ```svg BATCH PATH Sources db, api, files Bronze append only Silver typed, deduped Gold marts one per question Serving bi, api, cache STREAM PATH Event bus retained log Windowed jobs short windows Live tables low latency SHARED Object storage Catalog and lineage Orchestrator Quality checks ``` The important property of this layout is that each layer has one job. Bronze keeps what arrived, exactly as it arrived, so you can replay it. Silver is where typing, deduplication, and business rules live, and it is the layer you can rebuild from bronze at any time. Gold shapes data for a specific consumer. When a number turns out to be wrong, the layer tells you where to look, which is worth more than any amount of cleverness in a single monolithic job. The stream path exists only where freshness demands it, and it feeds the same serving layer rather than becoming a second source of truth. ## Decision one: batch or streaming The default answer is batch, and streaming is the exception you earn. Streaming costs more in every dimension. The compute has to stay warm, state has to live somewhere durable, late and out-of-order events become your problem, and testing a windowed job is harder than testing a query over a partition. If the consumer reads the result once a day, batch is the correct answer and streaming is complexity you will pay for forever. The signal to go streaming is a real latency requirement that cannot be met any other way: an alert that must fire within a minute, or a counter that a user watches live. When that is genuinely the case, stream the small number of things that need it and let everything else stay on the batch path. A hybrid is normal. A fully streaming platform that nobody asked for is the expensive mistake. ## Decision two: how data arrives, and whether it can run twice Ingestion decisions are where correctness is won or lost. A full snapshot every run is simple and gets expensive as the table grows. Change data capture reads the write-ahead log or the replication stream and delivers only the changes, which is far cheaper, at the cost of a pipeline that must handle out-of-order updates, schema changes mid-stream, and the occasional gap that needs a backfill. Start with snapshots if the table is small. Move to CDC when the scan volume forces it. Whichever you pick, make the write idempotent. No broker gives you exactly-once delivery on its own. The practical way to get it is at-least-once delivery plus a sink that can absorb the same record twice. On object storage that means writing into a partition and replacing it atomically, or merging on a stable key with a deterministic tie-break. In a warehouse it means a merge on the natural key rather than an insert. The test I apply is blunt: run the loader twice for the same window and check that the row count and the contents are identical. If they are not, the pipeline is not safe to rerun, and every backfill becomes a risk. ## Decision three: storage layout does more than any query tuning Two pipelines can run the same SQL and differ by an order of magnitude in cost because of how the files are laid out. Columnar formats like Parquet matter because a query that reads four columns out of forty should not pay for the other thirty-six. Compression matters because the bill is bytes scanned, and compressed bytes are fewer bytes. Sorting and clustering within a file matter because the reader can skip row groups whose min and max statistics rule out the predicate. Partitioning is the lever with the largest range, and it is easy to overdo. Partitioning by day turns a query for one day from a full scan into a scan of one directory, which in the worked example below is the difference between a terabyte and a gigabyte. Partitioning by a high-cardinality key such as user id creates hundreds of thousands of tiny directories and slows everything down. Partition by the columns people actually filter on, and keep the count in the hundreds or low thousands. The small file problem is the tax you pay for streaming or frequently-appended ingestion: thousands of kilobyte files, each with its own metadata read. Compaction, which rewrites small files into larger ones on a schedule, is not an optimisation you add later. It is part of running a lakehouse. ```mermaid sequenceDiagram participant S as Source participant L as Loader participant B as Bronze participant T as Transform participant G as Gold Note over L: read watermark for this dataset S->>L: rows where updated_at > watermark L->>L: dedupe on natural key L->>B: write into partition batch_id B->>T: merge on key, watermark advances T->>T: run quality checks T->>G: replace partition atomically Note over T: safe to rerun for the same window ``` ## Decision four: incremental work, and honest backfills Recomputing everything is the habit that makes pipelines expensive. Incremental processing reads only what changed since the last successful run and merges it into the target. The watermark is the small piece of state that makes this safe, and it should advance only after the write it depends on has succeeded. Late data is the complication. Events arrive after the window closed, and a pipeline that ignores them is quietly wrong. The two honest options are a short grace period during which a window stays open, and a scheduled restatement that reprocesses the last few days on purpose. Both are fine. Silently dropping late rows is not. Backfills deserve the same care as the daily run. A backfill should be a parameter, not a script someone edits at midnight: reprocess this range, write into the same idempotent sink, and check the result with the same tests. The pipeline I trust is the one where the backfill and the scheduled run are the same code path with a different window. ## Decision five: spend compute where the data shrinks Where you put a transform changes what the next stage has to read. An aggregation placed early means every stage downstream handles fewer rows, and one placed late means everything upstream pays for the full volume. ```chart { "type": "bar", "data": { "labels": ["Raw events", "Bronze", "Silver", "Gold", "Serving"], "datasets": [{ "label": "Rows per day (millions, worked example)", "data": [1000, 1000, 180, 6, 6], "backgroundColor": ["#cba6f7", "#89b4fa", "#94e2d5", "#a6e3a1", "#f9e2af"], "borderWidth": 0 }] }, "options": { "responsive": true, "plugins": { "legend": { "display": false } }, "scales": { "y": { "beginAtZero": true, "title": { "display": true, "text": "millions of rows" } } } } } ``` A day of this workload produces a billion raw events at about a kilobyte each, so roughly a terabyte before compression and a few hundred gigabytes once it is Parquet. Deduplication and typing bring it to a couple hundred million rows, and the aggregates a consumer actually reads are single-digit millions. Filtering and aggregating early is what turns a terabyte problem into a gigabyte one, and it costs nothing but thinking about the order of operations. ## Decision six: the compute engine is a detail, the plan is not Whether the work runs on a warehouse, a distributed engine, or a single machine with a columnar file, the shape of the efficient plan is the same. Read fewer columns, read fewer rows, shuffle less, and avoid the join that explodes. Three habits carry most of the weight. Push filters down so the engine reads only matching rows, and avoid wrapping a column in a function in a predicate, because that defeats the statistics. Filter before you join, and put the smaller side of the join first so the engine can broadcast it instead of shuffling both sides. Watch for skew, where one key holds a disproportionate share of the rows and a single task becomes the whole job. Salting the hot key or splitting the job by a second dimension fixes it, and detecting it is as simple as looking at the slowest tasks in the job history. ## Decision seven: orchestration is where reliability lives A pipeline is a set of tasks with dependencies, and the orchestrator's job is to run them in order, retry the ones that failed, and stop the ones whose input is wrong. The details that matter are unglamorous. Every task should be idempotent, because retries are normal. Dependencies should be on data, not on the clock, so a task does not start because it is 2am but because its input partition exists. Failures should fail loudly, because a task that logs an error and exits zero is worse than one that crashes. And the retry policy should be bounded, because a task that retries forever while upstream is broken is a way to turn one incident into an outage. ## Decision eight: quality checks that page someone Checks are only worth writing if a failure is actionable. Row counts that drop to zero, nulls in a key column, a freshness gap that exceeds the SLA, and referential integrity between a fact and its dimension will catch most real breakages. Anomaly checks on volume catch the rest, because a pipeline that suddenly processes ten times the usual rows is either a launch or a bug, and both deserve a look. The cheapest version of this is a small set of assertions attached to the transform layer, where the pipeline fails before the bad data reaches the consumer. ## The levers, ranked If I had to order the work by return on effort, it would look like this. | Lever | Mechanism | What it buys | |---|---|---| | Partition pruning | Filter on the partition column so the engine skips directories | A one-day query over a terabyte becomes a gigabyte | | Incremental processing | Read only rows past the watermark | Work scales with change, not with history | | Aggregating early | Shrink rows before they move | Every downstream stage gets cheaper | | Column pruning | Select only needed columns in a columnar format | Bytes scanned fall roughly with column count | | Compaction | Merge small files on a schedule | Fewer metadata reads, faster scans | | Join ordering | Broadcast the small side, filter before joining | Avoids the shuffle that dominates run time | | Caching | Reuse a materialised intermediate | Removes repeated work between jobs | | Compression | Encode Parquet more tightly | Fewer bytes billed and moved | The top three are architectural. The bottom five are tuning. Getting the order wrong is how teams end up micro-optimising a query that should never have scanned the whole table. ## What breaks first Small files accumulate and quietly slow everything down. Skew turns a parallel job into a single-threaded one. Late data makes yesterday's numbers change tomorrow, and if nobody planned for it the change looks like a bug. Schema drift, where an upstream adds or renames a column, breaks a transform that assumed the old shape. Duplicate rows from a retry that was not idempotent corrupt a total in a way that is hard to find. And backfills that were never tested quietly overwrite good data with wrong data. ## Trade-offs The efficient design is not the simplest one, and I try to be honest about the cost. Incremental processing needs a watermark, a merge, and a reconciliation job to catch drift. Medallion layers need storage and a catalog. Quality checks need someone to act on them. A simpler pipeline that recomputes a small dataset every night is a perfectly good answer when the dataset is small, and the right moment to add complexity is when a number forces it. The thing I would keep regardless of scale is the arithmetic. Writing down rows per day, bytes per row, and the partition a query actually reads turns a vague sense that the pipeline is slow into a specific fix, usually before anyone has written a line of code. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Designing an API for 100,000 requests a second - URL: https://blog.swadhin.cv/blog/designing-an-api-for-100000-requests-a-second/ - Published: 2026-09-24T10:00:00.000Z - Updated: 2026-09-23T20:17:57.000Z - Author: Swadhin Biswas - Categories: System Design, Backend, Performance, Architecture, Distributed Systems - Excerpt: The requirement was 100K rps. The work was arithmetic, a stateless tier, a cache that absorbs most of it, and a long list of things that break before the CPU does. ### Content A number like 100,000 requests per second is a requirement, and the moment you write it down it turns into a set of constraints you can reason about. This is how I would work through it: the arithmetic first, then the decisions, then the parts that fail long before the machine runs out of CPU. ## Do the arithmetic before drawing anything The first useful thing about a throughput target is that it converts into other numbers you can reason about. Little's law says the number of requests in flight equals the arrival rate multiplied by the time each one spends in the system. If the average response takes 10 milliseconds, then 100,000 requests per second means roughly 1,000 requests are being handled at any instant. ```chart { "type": "doughnut", "data": { "labels": ["Edge and TLS", "Load balancer", "Application", "Serialization", "Cache lookup", "Database (on a miss)"], "datasets": [{ "data": [5, 2, 12, 4, 3, 24], "backgroundColor": ["#cba6f7", "#89b4fa", "#a6e3a1", "#f9e2af", "#94e2d5", "#fab387"], "borderWidth": 0 }] }, "options": { "responsive": true, "plugins": { "legend": { "position": "bottom" } } } } ``` That chart is the budget I allocate, not a measurement. Every stage gets a slice and the slices have to add up to the p99 target of 50 milliseconds, with the database getting the largest slice because it is the only stage I do not fully control. Deciding the budget first is what turns "make it fast" into "make the application stage finish in 12 milliseconds". The rest of the arithmetic follows the same pattern. | Question | Working | Answer | |---|---|---| | Requests in flight | 100,000/s × 10 ms | about 1,000 concurrent | | Egress bandwidth | 100,000/s × 2 KB | about 200 MB/s, or 1.6 Gbps | | Origin load at a 95% cache hit rate | 100,000 × 0.05 | 5,000 database reads/s | | Instances at 3,000 rps each | 100,000 ÷ 3,000 | 34, so about 70 for real headroom | Two things stand out. The bandwidth is large but not exotic, and the cache hit rate is doing more work than any amount of clever code. A 95% hit rate turns a database problem into a rounding error, and a 90% hit rate doubles the load the database has to survive. Hit ratio is an architectural decision you make up front, long before there is anything to watch. ## The shape of the system With the budget fixed, the topology mostly writes itself. ```svg REQUEST PATH Clients browser / mobile / svc Edge TLS / HTTP3 / WAF Load balancer L4 anycast API tier (stateless, N instances) thread-per-core, in-process cache Shared cache redis / memcached Read replicas pooled connections read WRITE PATH Queue durable log Workers batched writes Primary single writer Replication to read pool writes enqueue and return early ``` Every arrow in that diagram is a decision about what has to be synchronous. Reads can be served by a cache or a replica. Writes go to a durable queue and return as soon as the queue has them, which keeps the write path short and lets the workers batch. The moment a write has to touch the primary inside the request, the primary becomes the ceiling for the whole system, and no amount of horizontal scaling in the API tier fixes that. ## Decision: what actually runs a request Runtime choice matters less than people expect for the shape of the system, and more than they expect for tail latency. An event-loop runtime handles a thousand concurrent requests on one thread, which is why the c10k problem stopped being a problem. The catch is that anything blocking on that loop stops every other request, so a synchronous database driver turns a fast runtime into a slow one. A thread-per-core runtime runs several event loops, one per CPU, and uses `SO_REUSEPORT` so the kernel spreads connections across them. That gives you parallelism without a shared lock on the hot path. Garbage collection is the part I would think hardest about. A stop-the-world pause is a tail-latency event, and at 100,000 requests per second a 20 millisecond pause stacks 2,000 requests behind it. A runtime with short, concurrent collection or no collection at all is worth real money here. If the language does pause, allocate carefully: reuse buffers, avoid per-request object churn, and watch the allocation rate rather than the heap size. ## Decision: the wire between client and server HTTP/1.1 with keep-alive is fine and simple, but it gives you one in-flight request per connection unless the client opens several. To carry 1,000 concurrent requests over HTTP/1.1 you may need thousands of sockets, and every socket is kernel memory and a file descriptor. HTTP/2 multiplexes many streams on one connection, which cuts the socket count, at the cost of head-of-line blocking when a packet is lost. HTTP/3 moves that problem onto QUIC, where streams are independent, and it is the reason a public API in front of mobile networks should terminate HTTP/3 at the edge even if everything behind it is HTTP/2 or gRPC. TLS is real CPU, and it is the first place people get surprised. A full handshake is expensive relative to the request itself, so session resumption has to be the default path. Terminate TLS at the edge, keep the connection alive, and let the clients reuse the session. The internal hop between the load balancer and the API tier can drop TLS entirely if the network is trusted, which removes a whole class of CPU cost from the tier that has to scale. ## Decision: how to parse and serialize Parsing is the silent bottleneck. A JSON body costs allocation and CPU to turn into memory, then the response costs the same in reverse, and at 100,000 requests per second that work is a large share of the 12 millisecond application budget. Two ways to reduce it: serialise less, and serialise faster. Serialising less means returning only the fields the caller asked for, and pushing pagination and filtering into the data layer so the API tier never materialises rows it will throw away. Serialising faster means choosing a compact format for internal hops, where nobody is debugging it by eye. Protobuf or flatbuffers cut both the CPU and the bytes. Keep JSON at the public edge if your clients expect it, and stop using it between services that you also control. ## Decision: make the cache the first line of defence A cache in front of the database is the highest-value component in the whole design. At 95% hit rate the database sees 5,000 reads per second instead of 100,000, and the difference between those two numbers is the difference between a design that works and one that does not. The details matter more than the choice of cache. Add a small in-process cache for the hottest keys so the shared cache is not a network hop on every request. Guard the misses with request coalescing, so a thousand concurrent requests for the same expired key turn into one database read and a thousand waiters. Add jitter to expiry times, because a thousand keys that expire on the same second will send a wave to the database that looks like a denial of service. Cache negative results too, so a request for something that does not exist does not become a database query every time. ```mermaid sequenceDiagram participant C as Client participant LB as Load balancer participant API as API instance participant L1 as In-process cache participant L2 as Shared cache participant DB as Replica C->>LB: GET /items/42 LB->>API: route to an instance API->>L1: lookup alt in-process hit L1-->>API: value else miss API->>L2: lookup alt shared hit L2-->>API: value API->>L1: backfill else miss API->>API: coalesce waiters API->>DB: one query DB-->>API: row API->>L2: store with jittered TTL API->>L1: store end end API-->>C: 200, cache hit ``` ## Decision: the data layer has fewer knobs than you think The API tier scales by adding instances. The database does not, so it gets the careful treatment. Connections are the first constraint. Each connection costs memory on both sides, and a pool that is too large makes the database slower, not faster, because the database spends its time context switching. Pool at the database side, not per instance, and size the pool to the CPU cores the database actually has. Reads go to replicas, and replicas introduce a consistency decision. A client that writes and immediately reads may not see its own write, so either route that specific read to the primary or accept the staleness explicitly and document it. Sharding comes later, and only when the primary is genuinely out of vertical room, because a shard key is very hard to change once data is on it. Choose a key with high cardinality and even access, or you will discover a hot shard on your busiest day. ## Decision: surviving the load you did not plan for Everything above is about handling the traffic you expect. Most incidents are about the traffic you did not. The failure mode of a system near saturation is a steep curve rather than a flat one: latency climbs slowly and then goes vertical, because a queue that is filling serves fewer requests, which adds more arrivals to the queue. The way out is to refuse work on purpose before that point. Admission control that sheds a small percentage of traffic keeps the requests you do accept fast, and a fast 429 is worth more to a caller than a slow timeout. Timeouts are a correctness requirement. Every outbound call needs a deadline shorter than the caller's, retries need exponential backoff with jitter, and a circuit breaker needs to open when a dependency is failing so the failing dependency is not finished off by your retries. Retry storms are a self-inflicted outage, and the only defence is that jitter plus a budget on how much of your traffic can be retries at all. ## What breaks first If I had to bet on the order of failures, it would look like this. Tail latency amplification comes first. A request that fans out to ten backends is as slow as the slowest of the ten, so a 1% slow backend becomes a 10% slow endpoint. Reduce fan-out and set per-call deadlines. Then garbage collection and allocation. Trimming the allocation rate on the hot path buys more headroom than a faster CPU. Then connection churn. A client that reconnects on every request turns a request problem into a TLS problem, and the edge spends its CPU on handshakes instead of requests. Then hot shards and hot keys. Uniform keys look fine in staging and concentrate under real traffic. Then logging and I/O. Writing a log line per request at 100,000 requests per second is a disk problem waiting to happen. Sample the logs, and keep the counter metrics cheap. ## How I would prove it Load tests that never lose a packet, from a single machine on the same network, tell you very little. The useful tests are the ugly ones. Ramp the load slowly to find the knee of the latency curve, where p99 starts to climb, and treat that point as your real capacity. Run a soak at 70% of that for hours, because memory leaks and connection leaks do not show up in a five-minute test. Then spike, well past the knee, and check that the system sheds load and recovers rather than collapsing. Run the generators from several machines, or the generator becomes the bottleneck and you end up measuring your load tool. And always report percentiles, never the average, because the average is where the incidents hide. ## What I would do differently The honest trade-off is that a 100K rps design is expensive and complicated, and most systems do not need it. If your real requirement is 5,000 requests per second, the stateless tier, one cache, and one database with a pool will get you there with a fraction of the operational surface. Reach for sharding, queues, and multi-region only when a number forces you to. The other thing I would keep from this exercise is the arithmetic. Writing down concurrency, bandwidth, and instance count before choosing any technology makes the conversation concrete, and it usually reveals that the cache or the serialisation is the real lever. Writing that arithmetic down first is the part that transfers to the next system, whatever the number turns out to be. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Flare: self-hosted webmail for my own domain - URL: https://blog.swadhin.cv/blog/flare-self-hosted-webmail/ - Published: 2026-09-21T12:49:27.780Z - Updated: 2026-09-21T13:28:52.000Z - Author: Swadhin Biswas - Categories: Backend, DevOps, Architecture - Excerpt: I built Flare to run mail for my own domain without an IMAP server. Astro on a Worker, Turso for state, Resend or Maileroo for delivery, webhooks for inbound. ### Content I run my blog on Astro and Turso. I wanted the same shape for mail: one small app I control, mail for my own domain, no mailbox quota to watch, no third party keeping a copy I cannot see. I built Flare for that. Source is at [github.com/swadhinbiswas/flare](https://github.com/swadhinbiswas/flare), MIT licensed. Flare is a self-hosted webmail client for a single owner. It sends through Resend, Maileroo, or any SMTP relay, receives through provider webhooks, keeps everything in Turso, and serves from a single Cloudflare Worker. There is no IMAP bridge. The repo sat at 109 commits on main when I wrote this. ## What it is The runtime is Astro 7.3.3 on `@astrojs/cloudflare` 14.3.2, with a React 19.3.0 island for the mail client. The database client is `@libsql/client` 0.18.0 over HTTP. Styling is Tailwind 4.3.3 with shadcn primitives. Node requirement is 20 or newer, package manager is pnpm 11.9.0, tests run on Vitest 5, types on TypeScript 5.9.3. A Worker has two halves here. Astro server-renders every page behind session middleware, then a React island called `MailClient` takes over selection, compose, search, and shortcuts. API routes live under `src/pages/api` and read Turso through `@libsql/client/web`. I designed it for a handful of accounts and one login. The whole thing deploys as one Worker with a static asset bundle. It also runs on a laptop with no Cloudflare account, using a local libSQL server. ## Flare never speaks SMTP This part matters before you touch DNS. Flare talks to a provider HTTP API. The provider owns the MX record and the sending reputation. That split is why the app can run on Workers at all. ```mermaid flowchart LR B[Browser Astro SSR plus React island] --> W[Cloudflare Worker] W --> T[Turso libSQL] W --> S[Blob storage Turso or R2] W --> P[Mail provider] P --> W ``` Sending and receiving need different records. SPF and DKIM verify sending. MX points at the provider for receiving. DMARC tells receivers what to do when checks fail. A tracking CNAME is optional for open and click events. I use a subdomain such as `mail.example.com` for this. It keeps root domain mail untouched and it makes the records easier to read. Verify the domain in the provider dashboard, publish exactly what it shows, and wait for verified status before pointing a webhook at the app. Settings mirrors that health check inside Flare. ## How outbound works The composer posts to `/api/messages/send`. Flare validates recipients and attachments first, then writes a `messages` row with status `queued`, or `scheduled` when I picked a delivery time. This happens before the provider call so the message shows in Sent at once. If the provider rejects it, the row flips to `failed` with a reason. The provider adapter sends it. Resend goes through its SDK to `api.resend.com`. Maileroo posts to `smtp.maileroo.com/api/v2/emails` with an `X-Api-Key` header. Reply headers carry `In-Reply-To` and `References` so the recipient client threads the reply. Delivery events come back as webhooks. Each one appends to `email_events`, and `messages.status` moves forward only: `queued` to `sent` to `delivered` to `opened` to `clicked` `bounced`, `complained`, `failed`, and `canceled` are terminal. Opening a thread clears its unread count. Folder badges come from one grouped query. If a webhook never arrives, the sync path asks the provider for current state. On Resend that is `emails.get` with `last_event`. On Maileroo it is webhooks only. The same code backs the Sync button, the one minute background pull while the tab is visible, and the pull on window focus. ## How inbound works Someone sends mail to my domain. Their server looks up MX, which points at the provider. The provider accepts SMTP, checks SPF, DKIM, and DMARC, parses MIME, and stores body and attachments. Then it notifies Flare. The two providers differ here and I kept both paths explicit: | Concept | Resend | Maileroo | |---|---|---| | Send | POST /emails through SDK 6.28.1 | POST /api/v2/emails with X-Api-Key | | Delivery webhook auth | Svix signature, `whsec_` secret | HMAC-SHA256 hex in `x-maileroo-signature` | | Inbound model | Metadata webhook, then fetch content | Full message in the webhook | | Inbound auth | Svix signature | One-time `validation_url` | | Attachments | Signed URLs, valid 1 hour | Signed URLs in payload, 72 hour retention | | Status lookup | `emails.get` reports `last_event` | Webhooks only | | Scheduling | `scheduledAt`, cancel by id | `scheduled_at`, list and delete | The handler verifies before it touches the database. A bad signature returns 400 and nothing is written. An ingest failure returns 500 so the provider retries. Inserts are idempotent per provider message id. Body fetch depends on provider. For Resend I call the Receiving API with `html_format=cid`. For Maileroo I read the payload directly. Attachment bytes copy into my own storage while signed URLs are valid. Maileroo keeps its copy for 72 hours and exposes a `deletion_url` that Flare calls once everything is stored. Threading resolves in order: `In-Reply-To`, then `References`, then normalized subject plus a shared participant, then a new thread. That fallback keeps mail from clients with broken headers in one place. The message lands with `status = received`, thread unread and participants update, `cid:` image references rewrite to authenticated attachment URLs. ```mermaid sequenceDiagram participant U as Sender participant P as Provider participant W as Flare Worker participant T as Turso plus blobs U->>P: SMTP to your domain P->>W: received webhook W->>P: fetch body and attachments W->>T: match thread, insert message, store bytes ``` ## Provider interface Everything mail related goes through one interface in `src/lib/providers`. `MAIL_PROVIDER` picks the default backend and each account picks its own. ```typescript export interface MailProvider { readonly id: string; readonly label: string; readonly defaultWebhookEvents: string[]; isConfigured(): boolean; send(message: ProviderOutboundMessage): Promise<{ id: string }>; getMessageStatus(providerMessageId: string): Promise; listReceived(limit: number): Promise; getReceived(providerEmailId: string): Promise; verifyWebhook(payload: string, headers: Headers, secret: string): Promise; listDomains(): Promise; listWebhooks(): Promise; createWebhook(input: { endpoint: string; events: string[] }): Promise; deleteWebhook(id: string): Promise; getMetrics(days: number): Promise; } ``` Optional members declare what an API can do: `classifyWebhook`, `parseInbound`, `finalizeInbound`, `cancelScheduled`, `listScheduled`, `addSuppression`. The UI degrades when one is missing instead of failing. To add a provider I implement `MailProvider` from `src/lib/providers/types.ts` and add a case in `src/lib/providers/index.ts`. SMTP is send-only in this model. Workers cannot listen for inbound SMTP, so an SMTP account sends and receiving stays with the account that owns MX. Maileroo taught me two lessons during live verification. The Email API needs a Sending Key created per domain under Domains then Sending Keys. An Account API key alone returns `invalid API key`. Account keys also carry scopes and an IP allowlist. `0.0.0.0/32` allows only the address `0.0.0.0`. I use `0.0.0.0/0` plus `::/0` or no allowlist, because Workers egress from dynamic addresses. For SMTP relays I use implicit TLS on 465. STARTTLS on 587 depends on the runtime upgrading the socket at connect time and some servers reject that. ## Accounts There are two ways to define a mail account and they mix. From Settings is the quick path. I pick Resend, Maileroo, or SMTP, fill in From address and credentials, and it becomes active. Secrets encrypt with AES-GCM under a key derived from `SESSION_SECRET` before they reach Turso. Provider keys never sit in clear text. Accounts created this way can be removed from the same card. From environment suits infrastructure as code. `MAIL_ACCOUNTS` in `wrangler.jsonc` is a JSON array where every entry names credentials by env var. `wrangler.jsonc` takes JSON, so the value is that array as a single string. ```bash node -e "console.log(JSON.stringify(require('./accounts.json')))" ``` One rule ties both together. The environment account is present as `primary` unless a database row claims that id. Existing mail never disappears when I add accounts. Threads and messages carry `account_id`. The active account lives in a cookie and I switch from the sidebar, the mobile drawer, or the account card. Every account has its own webhook endpoint such as `/api/webhooks/resend/` so signatures verify with the right secret. Profile adds display name used in the `From` header and a picture uploaded or set from URL. Uploads replace the URL. The From header order is `account.fromName`, then profile display name, then `MAIL_FROM_NAME`. ## Interface Three-pane layout with resizable panels. Command palette across every folder. Keyboard shortcuts throughout: | Key | Action | |---|---| | c | Compose | | r | Reply | | e | Archive, or move back to inbox | | # | Trash | | j / k | Move focus in thread list | | Enter | Open focused thread | | / | Focus search | | Cmd-K or Ctrl-K | Command palette | | Cmd-Enter | Send from compose | Shortcuts stay out of the way while I type in inputs or contenteditable. Four palettes ship in light and dark mode: Proton, Zinc, Nord, Rose. Proton is default. Message bodies follow the palette. Below `md` the layout collapses to a single pane with a drawer, and `/thread/[id]` deep-links a conversation. Compose supports attachments and scheduled send, with cancel from the conversation before it leaves. Settings holds provider tools: webhook registration with signing secret, suppression list management, and 7-day deliverability metrics. ## Where state lives The first migration creates `users`, `sessions`, `threads`, `messages`, `attachments`, and `email_events`. Later migrations add `blobs`, profile fields, mail accounts, and the account vault. A few decisions from that schema are worth stating. `attachments.message_id` is nullable on purpose. Outbound files upload before the message exists and the send handler claims them. Timestamps come from JavaScript as ISO strings, not SQLite `datetime('now')`, because mixing formats breaks lexicographic ordering. libSQL over HTTP has no interactive transactions, so multi-statement writes use `client.batch` with write mode. Foreign keys are not enforced over HTTP, so deletes are explicit. A reply keeps its thread folder. Replying to an inbox thread does not file it under Sent. Scheduled messages hold `scheduled` status until a webhook or cancel moves them. Blob storage is pluggable. Default keeps attachment bytes in Turso, so R2 is optional. If I enable R2 I add the binding back to `wrangler.jsonc` and set `BLOB_STORE` to `r2` or `auto`. | Concern | Stored in | Why | |---|---|---| | Threads and messages | Turso | Small rows, queried constantly | | Delivery history | `email_events` | Append-only audit for the timeline | | Attachment bytes | `blobs` or R2 | Binaries stay out of message rows | | Avatars | Same blob store | One code path for binaries | | Sessions | Turso | Server-side revocation, hashed tokens only | | Active account | Cookie | Per browser, no server cleanup | ## Security Passwords use PBKDF2-SHA256, 210,000 iterations, 16-byte salt, constant-time compare. There is no sign-up page. I create the user from CLI and only the hash reaches Turso. Sessions store `sha256(token)` in the database. The cookie holds `token.HMAC(SESSION_SECRET, token)` so a dump cannot replay. Cookies are `HttpOnly`, `Secure`, `SameSite=Lax`, 30-day sliding expiry, revoked on password change. Message HTML renders in a sandboxed iframe without `allow-scripts`, so mail cannot run JavaScript in the app. Attachment and avatar downloads pass an auth check. Storage keys never go public. State-changing endpoints accept JSON only and sessions are `SameSite=Lax`, which is why Astro origin check stays off: providers post webhooks cross-site. Login rate limit is in memory per isolate, 10 attempts per 15 minutes per IP. That is fine for one owner. I would put Cloudflare Access in front if I wanted a second gate. ## Run it Node 20 or newer and pnpm. Turso CLI only if I want local libSQL instead of hosted. Provider key only if I want to send. ```bash pnpm install # Local libSQL server, no Turso account required PATH="$HOME/.turso:$PATH" turso dev -f local.db -p 8080 & cp .dev.vars.example .dev.vars cp .env.example .env pnpm migrate pnpm create-admin pnpm dev ``` `pnpm dev` runs Astro on workerd, so bindings and secrets behave like production. The CLI scripts read `.dev.vars` first and fall back to `.env`. Only `.dev.vars` reaches the Worker runtime during dev. `.env.example` documents the full credential set. | Command | What it does | |---|---| | pnpm dev, dev:stop, dev:status, dev:logs | Dev server lifecycle | | pnpm build, pnpm preview | Production build, then built Worker on workerd | | pnpm typecheck | `astro check` across Astro and TS | | pnpm test | Vitest over status ranking, mail helpers, MIME building | | pnpm types | `wrangler types` regenerates `worker-configuration.d.ts` | | pnpm migrate | Applies `migrations/*.sql` once each | | pnpm create-admin | Creates or updates user, revokes old sessions | | pnpm seed-demo | Fictional threads for UI work, refuses remote DB unless forced | | pnpm deploy | `wrangler deploy` | `pnpm seed-demo` is how I explore UI without real mail. ## Deploy Cloudflare Git integration is the intended path. Connect the repo once and every push to `main` builds and deploys. No Cloudflare credentials live in GitHub. Build command is `pnpm build`. Deploy command is `npx wrangler deploy`. Root is `/`. I set `NODE_VERSION=22` when the builder picks older Node. Secrets go once under Worker Variables and Secrets: `RESEND_API_KEY`, `RESEND_WEBHOOK_SECRET`, `TURSO_DATABASE_URL`, `TURSO_AUTH_TOKEN`, `SESSION_SECRET`, plus Maileroo pair when used. Then seed production: ```bash TURSO_DATABASE_URL="libsql://..." TURSO_AUTH_TOKEN="..." pnpm migrate TURSO_DATABASE_URL="libsql://..." TURSO_AUTH_TOKEN="..." pnpm create-admin ``` Attach the domain under Worker Settings then Domains and Routes, update `PUBLIC_APP_URL`, then register the webhook from Settings. The page shows the signing secret to store. The remaining workflow `.github/workflows/ci.yml` runs tests, typecheck, and build on pushes and pull requests. There is no deploy job. One builder note bit me: pnpm 10 and later refuse install scripts unless approved, which fails with `ERR_PNPM_IGNORED_BUILDS`. The repo approves `esbuild`, `workerd`, `@tailwindcss/oxide`, and `sharp` through `allowBuilds` in `pnpm-workspace.yaml`, with `onlyBuiltDependencies` kept for pnpm 10. ## Troubleshooting notes Login returning blank 500 after deploy almost always means missing runtime secrets. I added `/api/health` for this. It returns `{ ok, missing[] }` with names only and a 503, and login returns that list in its error body. The fix is to set `TURSO_DATABASE_URL`, `TURSO_AUTH_TOKEN`, `SESSION_SECRET`, and provider keys, then redeploy. `Invalid webhook signature` on every event means the secret is wrong or the body was parsed before verification. For Resend it must be base64 after `whsec_`. Paste the exact value. No inbound mail means checking Settings for domain and webhook health. For Resend the domain must be verified with receiving enabled. For Maileroo the inbound route must point at `/api/webhooks/maileroo/`. Scheduled cancel can fail with "Email is not scheduled" when Resend accepts send slightly before it flips state. Flare retries that error a few times. If it still fails, the message had not settled yet. For local webhooks providers cannot reach localhost. I tunnel with `cloudflared tunnel --url http://localhost:8787`, then register a second dev webhook or use the Settings button and store the returned secret in `.dev.vars`. `code: 10042` on deploy means R2 binding is declared but R2 is not enabled. Enable R2 or switch `BLOB_STORE` to `database` and remove the binding. Types drifting after editing `wrangler.jsonc` means running `pnpm types`. ## Limits Single admin user by design, with multiple mail accounts. Message bodies stay forever, there is no retention job yet. Search covers the selected folder in the list and all folders from the palette. Templates, broadcasts, automations, and dedicated IPs from provider APIs stay out on purpose. They are marketing features more than webmail. There is no IMAP or SMTP bridge, so Flare cannot run from Apple Mail or Thunderbird. SMTP accounts send only. That constraint keeps the Worker model intact, and for my use it is acceptable. If I need desktop clients later, that bridge would be a separate service, not part of the Worker. If you self-host mail for a custom domain and you are comfortable pointing MX at Resend or Maileroo, Flare gives you a client you can read end to end. Start with a subdomain, verify DNS, register the webhook from Settings, and send your first message to yourself. --- ## A filesystem event log in SQLite - URL: https://blog.swadhin.cv/blog/filesystem-event-log-in-sqlite/ - Published: 2026-09-20T10:00:00.000Z - Updated: 2026-09-23T12:05:47.000Z - Author: Swadhin Biswas - Categories: Data Engineering, Backend, Programming - Excerpt: Point it at a folder and every create, edit, rename and delete lands in a local database. Undo, replay, fork and diff, without git in the way. ### Content Git tracks the snapshots you choose to commit. It does not track the folder you have been editing for three hours without committing, which is exactly where people lose work. Kalpa watches a directory and logs every filesystem event into a local SQLite database, so any folder gets a history whether or not it is a repository. Repo: [swadhinbiswas/kalpa](https://github.com/swadhinbiswas/kalpa) · Install: `pip install kalpa` ## What it does Point it at a folder and it starts watching. State lives in a `.kalpa/` directory beside the files, with no remote server and no staging area. ``` kalpa watch ./my-project --background rm -rf src/ kalpa undo # restores what was just destroyed kalpa timeline kalpa replay --speed 3x kalpa fork --from "1 hour ago" kalpa diff "2 hours ago" "now" kalpa snapshot --label "before-refactor" ``` Time arguments accept natural language: `5 minutes ago`, `yesterday`, `yesterday 6pm`, or an absolute timestamp. `fork` materializes a copy of the folder at a past state, `diff` compares two points in time, and `undo` restores the last destructive change. ## How it stores history The watcher uses `watchdog` to receive create, modify, rename and delete events, and each one is written to SQLite as a row in a timeline. File contents are stored as incremental deltas compressed with zstandard, which keeps the database small even for an active directory. The architecture is flat: no daemon to manage and no background server. The `--background` flag forks the watcher and records a PID file. The modules are separated by job: `watcher` for events, `snapshot` for deltas, `storage` for SQLite and compression, plus `replay`, `fork`, `diff`, `timeline`, `config`, and a Textual TUI. That separation is why `fork` and `diff` are cheap: they read from the same event log that the watcher wrote, rather than reconstructing state from files. ## Why not just git Git answers a different question. It records intent at commit time and ignores everything between commits, and some folders should never be a repository at all: config directories, data folders, scratch work. Kalpa records what actually happened, including the `rm -rf` you did not mean. The two coexist fine. A repository can have a Kalpa watch on top of it for the uncommitted hours. ## Working on it 106 tests cover the modules across Linux, macOS and Windows on Python 3.12 and 3.13, run through GitHub Actions. Building it reinforced a lesson I keep meeting in data systems: an append-only event log with a query layer is a small idea that answers a surprising number of questions. Replay, diff and fork are all reads against the same log, which is why the storage layer is the part worth getting right first. The repository above has the source and the TUI. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Treating a directory of TOML as a database - URL: https://blog.swadhin.cv/blog/treating-toml-as-a-database/ - Published: 2026-09-13T10:00:00.000Z - Updated: 2026-09-23T12:05:56.000Z - Author: Swadhin Biswas - Categories: Data Engineering, Architecture, Programming - Excerpt: Hand-curated source data, generated gold tables, and a published dataset. How I keep a directory of TOML honest with code generation and CI. ### Content There is a list of software companies in Bangladesh that people keep asking for, and every version of it I found was a spreadsheet that aged badly. So I built one where the data is the source of truth and everything else is generated, including the README. Repo: [swadhinbiswas/software-companies-in-bangladesh](https://github.com/swadhinbiswas/software-companies-in-bangladesh) ## The rule The README says, in a comment at the top, `AUTO-GENERATED FILE - DO NOT EDIT`. If you want to change a company, you edit a TOML file under `data/` and open a pull request. That one rule is what keeps 140 entries consistent: no one can quietly fix a row by hand and drift from the canonical record. ## The layout The source data is a small set of TOML files: `companies.toml` for the rows, `schema.toml` for the allowed company types and technologies, and `ignore.toml` for exclusions. There is an `info.json` and a `job-posts.json` feed alongside. Everything downstream is derived, and it lands in `data/gold/` as a set of small JSON files, one per question someone might ask: ``` companies.json company_tech.json employment_breakdown.json jobs_per_company.json location_heatmap.json recent_jobs.json salary_stats.json tech_demand.json stats.json ``` That split between raw and gold is the whole point. The TOML is curated and reviewed, and the gold files are rebuildable. When a new technology type shows up, I add it to `schema.toml` and the aggregates follow. ## The pipeline A `warehouse/` directory holds `schema.sql`, a `build.py` that turns the source into the gold tables, a dataset card template, and an `hf_push.py` that publishes the result as a Hugging Face dataset. A `tools/` directory holds a Rust crate, and there is a `crawl.sh` for collecting job pages plus a `dashboard/` for the public view. `jobs.md` is generated from the same data and currently reflects openings from 140 companies. Because the jobs feed and the company list come from one source, they cannot disagree. ## Why this is data engineering Parsing job pages was the easy part. Designing a small schema that stays honest under contribution was the work. Types and technologies are constrained lists rather than free strings, so `tech_demand.json` and `employment_breakdown.json` are groupable without a normalization pass. The README and the dashboard are both outputs of the same build, so the thing people read first is never stale relative to the data. It is the same discipline as any warehouse, at a scale one person can hold in their head. Curated source layer, constrained schema, generated aggregates, and a published artifact with a card that explains what it is. The repository, the schema and the published dataset are linked above. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## A scholarship ingestion pipeline that dedupes across three sources - URL: https://blog.swadhin.cv/blog/scholarship-ingestion-pipeline/ - Published: 2026-09-06T10:00:00.000Z - Updated: 2026-09-23T12:05:53.000Z - Author: Swadhin Biswas - Categories: Data Engineering, Backend, Programming - Excerpt: Playwright for the pages that need JavaScript, cron for the schedule, and a dedupe key that keeps DAAD, Erasmus and Chevening from colliding. ### Content Most scrapers are a script. This one is a small pipeline with the seams in the right places, because scholarship listings change often and a flaky source should not take the whole run down. Repo: [swadhinbiswas/fundmystudy-scraper](https://github.com/swadhinbiswas/fundmystudy-scraper) It is a Node.js service that pulls opportunities from public sources and submits them to the FundMyStudy API for moderation. Three sources ship today: the DAAD scholarship database, the Erasmus Mundus catalogue, and Chevening programmes. ## Shape of the code Each source implements one interface with a name, a cron schedule, a URL and an async `fetch()` that returns a list of raw listings. Adding a source is a new file and one line in the registry, plus its name in the `SOURCES` environment variable. ``` scheduler -> runner (per source) -> normalize -> dedupe -> API client ``` The scheduler is a thin node-cron wrapper. The runner walks each enabled source through the pipeline. The normalizer handles the shared cleanup. The deduper keys on `external_id`, then URL, then a normalized title plus provider, which is what stops the same scholarship arriving by two routes from becoming two rows. Every stage emits counters, so a run reports what each source produced and what was dropped. Playwright is in the mix because some of these catalogues render client-side and a plain HTTP fetch returns an empty shell. It downloads Chromium on first install, which is worth knowing before you run it in CI. ## Running and testing ``` npm run typecheck npm run run:once npm run test:source -- daad ``` The `test:source` script fetches and normalizes one source and prints the result without posting anything, and `run-once` takes a single source end to end. That split is the part I use most, because debugging a parser against a printed listing is faster than watching a full run. ## What I would carry forward Two habits made this maintainable. Every source is isolated behind the same interface, so a selector change or a 429 is contained to one module and one retry policy. And dedupe keys are explicit and ordered, because "is this the same listing" is a data-model question, not a string comparison you invent at the last minute. The repository above has the source implementations and the moderation API client. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## A real-time video analytics pipeline that refuses to store unknown faces - URL: https://blog.swadhin.cv/blog/real-time-video-analytics-pipeline/ - Published: 2026-08-30T10:00:00.000Z - Updated: 2026-09-23T12:05:51.000Z - Author: Swadhin Biswas - Categories: Machine Learning, Data Engineering, Backend - Excerpt: Detect, track, check liveness, embed, match. One worker per camera, a SQLite source of truth, and a vector index that heals itself when the model changes. ### Content A camera that records everything is a liability. AegisVision turns a CCTV feed, webcam or RTSP stream into something that answers questions about a space, and it does that with a deliberate rule: people it does not recognise are tagged on the frame and never written to disk. Repo: [swadhinbiswas/AegisVision](https://github.com/swadhinbiswas/AegisVision) ![AegisVision system architecture](https://cdn.jsdelivr.net/gh/swadhinbiswas/AegisVision@main/docs/diagrams/architecture.svg) ## The frame pipeline One background capture worker runs per configured camera and shares the latest frame with back-pressure and automatic reconnect. Each frame moves through a fixed pipeline: detect, track, check liveness, embed, match. Detection uses SCRFD-500M through ONNX, small enough to run in under ten milliseconds on CPU. An IoU tracker keeps an identity across frames and only re-runs the embedding when a track window elapses, which is the difference between a model that keeps up and one that does not. A liveness gate checks face texture so a printed photo or a phone screen scores lower, then ArcFace produces a 512-dimensional aligned embedding, and a top-N cosine lookup happens in Chroma. The backend is swappable without code changes. `FACE_BACKEND=auto` prefers insightface and falls back to dlib if the package or model is unavailable, and the vector index repairs itself when the embedding dimension changes from 128 to 512. ## Two stores, one truth Relational rows in SQLite are the source of truth. The Chroma vector index mirrors `person_id` to embedding so a person can own many photos as they age, change angle or get re-enrolled. Enrollment is a folder drop: create `data/known_persons/_/` with an `info.json` and photos, and the person is live in minutes through a startup sync and a folder watchdog. ## What it actually watches Beyond recognition, the behavioral engines consume identities and liveness to produce gate in and out events with a 30-second cooldown, live occupancy, per-person active, idle-lazy, bunking and phone-distraction minutes, and drowsiness signals. A spatial memory tracks registered assets against their owner and raises a theft suspicion when something moves. Rules escalate on repeated unknowns, repeated phone use or repeated drowsiness, and the alert goes out over WebSocket to the dashboard plus a Telegram or JSON webhook. There is a Generative-AI copilot that answers plain-English questions over the live database, with a rule-based fallback when no API key is set. ## How it deploys Docker Compose puts NGINX in front of uvicorn with persistent volumes for SQLite, ChromaDB, the roster and logs. One host runs the whole thing, and cameras are added by ID. The test suite has 51 passing tests. The design decision I would defend hardest is the unknown-face rule. Recognition systems accumulate data by default, and most of it is people who never consented. Making the default "tag and move on" forced the rest of the system to be explicit about what it stores, which made the privacy story clearer and the storage footprint smaller. The diagrams, the data model and the deployment topology are in the repository above. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Load-testing an encrypted API gateway toward a billion requests - URL: https://blog.swadhin.cv/blog/load-testing-an-encrypted-api-gateway/ - Published: 2026-08-23T10:00:00.000Z - Updated: 2026-09-23T12:05:50.000Z - Author: Swadhin Biswas - Categories: Encryption, Backend, Performance, Distributed Systems - Excerpt: Paillier homomorphic encryption, an honest-but-curious proxy, and a simulator that measures what the network costs when the server never sees plaintext. ### Content Homomorphic encryption is usually discussed in theory. I wanted the numbers: if a server can add and count encrypted values without ever decrypting them, what does that actually cost on a real network under real concurrency. So I built a measurement environment. Repo: [swadhinbiswas/Partially-Homomorphic-Encryption](https://github.com/swadhinbiswas/Partially-Homomorphic-Encryption) ## The setup The whole thing is one Go process with no third-party modules, standard library only, tested on Go 1.25. That constraint is deliberate. When you are measuring cryptography and queueing, a dependency you did not write is a variable you cannot explain. ```mermaid flowchart LR S[Simulation engine
N goroutines] -->|encrypted JSON| P[External proxy pool] P --> U[Untrusted proxy
latency + fault injection] U --> G[Gateway :8082
no plaintext access] G --> W[PHE worker pool
homomorphic sum + count] ``` The simulation engine generates payloads, encrypts them with Paillier, sends them, and measures latency. Traffic can route through an optional pool of more than a thousand HTTP, SOCKS5 or SOCKS4 proxies, or through a built-in untrusted proxy simulator on port 8081 that injects latency and faults and observes metadata while being honest-but-curious. The gateway on port 8082 is stateless and has no plaintext access. It routes to a worker pool implemented with Go channels that performs homomorphic sum and count while tracking queue wait and compute time separately. That separation is the point. Queue wait and compute time are different problems, and a single latency number hides which one is growing. ## What it measures The metrics recorder streams CSV and JSONL, chunked and written to disk, so a long run does not exhaust memory. The experiments cover throughput, latency percentiles, the effect of the untrusted proxy, and the overhead of the Paillier operations themselves. The repository documents scaling to a billion requests, and since all components run in one process, the failure modes are the ones under test rather than the ones coming from your orchestrator. One thing I would tell anyone doing this: measure with the proxy in the path. Encryption cost on a loopback interface tells you about your CPU. Encryption cost behind a proxy at a realistic latency tells you whether the design is viable, and those two answers can differ by an order of magnitude. ## Why this matters for data systems Encrypted compute is often proposed as a way to keep PII out of an analytics layer while still aggregating it. That only works if the latency is acceptable, and the only honest way to know is to measure end to end. This project is the measurement harness, with key management and reproducibility notes so a run can be repeated rather than trusted. The source and the experiment definitions are in the repository above. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Veet: the Linux uninstaller that cleans what package managers leave behind - URL: https://blog.swadhin.cv/blog/veet-the-linux-uninstaller-that-cleans-what-package-managers-leave-behind/ - Published: 2026-08-18T10:00:00.000Z - Updated: 2026-09-21T13:08:48.000Z - Author: Swadhin Biswas - Categories: DevOps, Technology, Programming - Excerpt: Removing a Linux app often leaves configs and caches on disk. Veet scans 17 sources at once, stages every residual path, and removes them in one confirmed step. ### Content I created [github.com/swadhinbiswas/veet](https://github.com/swadhinbiswas/veet) on 15 August 2026 after getting tired of disk space disappearing on a machine where I had already removed the apps. The repo is Go, MIT licensed, 150 stars and 6 forks when I pulled these notes, with 30 commits on main and 2 open issues. The short description fits in one line: universal Linux application uninstaller and deep clean residual purger. Standard removal only touches package managed files under paths like `/usr/bin` and `/usr/share`. It leaves user space behind. I kept finding the same leftovers: - `~/.config/` with settings and credentials - `~/.cache/` with runtime and shader caches - `~/.local/share/` with local databases and state - `~/.local/state/` with session history - `~/.var/app/` for Flatpak data - `~/snap/` for Snap data - `/var/log/` and journal archives One app never costs much. Fifty apps across native packages, Flatpak, Snap, AppImage, Homebrew, Nix, and language toolchains add up to gigabytes. I built Veet to scan all of those sources at once, show me exactly what would go, and remove it in one confirmed action. ## What it scans Veet queries 17 sources concurrently and skips tools that are not installed at zero cost. The detector files under `internal/detector/` name them plainly: `pacman.go`, `apt.go`, `dnf.go`, `zypper.go`, `flatpak.go`, `snap.go`, `appimage.go`, `brew.go`, `nix.go`, `npm.go`, `pipx.go`, `cargo.go`, `gem.go`, `goinstall.go`, plus `cache.go`, `orphans.go`, and `systemlogs.go`. That list covers system managers, sandboxed containers, portable bundles, and language toolchains including `npm -g`, `pipx`, `cargo`, `gem`, and `go install`. Orphan detection uses the native queries you would run by hand: `pacman -Qdt`, `apt autoremove`, and `dnf repoquery --unneeded`. Journal handling shells out to `journalctl --vacuum` for bloated systemd storage alongside rotated compressed logs. ```mermaid flowchart TD SCAN[Concurrent scan of 17 sources] --> STAGE[Stage residual paths] STAGE --> REVIEW[Inspect paths in TUI or dry run] REVIEW --> CONFIRM[Confirm once] CONFIRM --> REMOVE[Atomic removal with single sudo batch] ``` The stack is small and current. `go.mod` states Go 1.24.2 with Bubble Tea 1.3.10, Lip Gloss 1.1.0, Cobra 1.10.2, Viper 1.21.0, Afero 1.15.0, and `golang.org/x/sys` 0.38.0. The layout is easy to walk: `main.go` holds the Cobra entrypoint, `internal/model/` holds types like `AppInfo` and `RemovableFiles`, `internal/detector/` holds source handlers, `internal/uninstaller/` holds staging and filesystem removal, `internal/history/` holds the audit log, and `internal/ui/` holds Bubble Tea components with a theme engine. ## TUI and CLI I use both modes. The TUI is the daily driver. The CLI is for scripts and audits. Launch the dashboard: ```bash veet ``` List everything without interaction: ```bash veet scan veet scan --json ``` Remove with a preview of staged paths: ```bash veet clean app1 app2 veet clean code --dry-run veet clean code --yes ``` Orphans and caches get their own subcommands: ```bash veet orphans --clean --yes veet cache --clean --yes veet history veet history --clear ``` `main.go` defines `scan`, `clean`, `orphans`, `cache`, `history`, and `tui`. The `clean` command accepts `--source` to limit matching to one origin, `--yes` for non interactive runs, and `--dry-run` to stage and print paths without deleting. `orphans` and `cache` accept `--json`, `--clean`, and `--yes` with a 60 second context timeout. `history` accepts `--json`, `--clear`, and `--limit` with a default of 50 entries. Output tables print `APP/PACKAGE`, `VERSION`, `SOURCE`, and `SIZE`, with `-` when size is unknown. One behavior surprised me the first time: the TUI refuses to run as root. Elevation happens per command through sudo instead. That choice keeps the interactive process unprivileged while system paths still get removed in one batched transaction. ## Staging before deleting Veet never deletes on scan. It stages candidate paths for inspection, then executes after confirmation. `runClean` in `main.go` prints each match with reclaimable size and file count, lists every path with a `[requires sudo]` tag where needed, and totals the run before asking `[y/N]`. Dry run stops there with the line `Dry-run mode: no files or packages were removed.` The comparison in the README states the difference well: | Task | pacman or apt remove | flatpak uninstall | bleachbit | veet | |---|---|---|---|---| | Binary removal | Yes | Yes | No | Yes across 17 sources | | Config cleanup in config dir | No | No | Partial | Yes, staged for inspection | | Cache cleanup | No | No | Yes | Yes, staged for inspection | | Sandbox cleanup in var app and snap dir | No | Partial | No | Yes, deep detection | | Orphan pruning | Manual query | No | No | Yes, live detection | | AppImage discovery | No | No | No | Yes | | Dry run with full path list | Partial | Partial | Yes | Yes with `--dry-run` | | Single sudo prompt per batch | Per command | Not applicable | Full root required | Yes | I rely on the staged list because config directories sometimes hold credentials or project state I want to back up first. Seeing `/home/swadhin/.config/Code` in the list before anything runs is the whole point. ## Search that matches how I think Press `/` in the TUI to focus search. The modifiers are few and they compose: | Syntax | Example | Meaning | |---|---|---| | `@source` | `@flatpak` | Limit to one manager | | `>size` | `>100M` | Larger than given size | | `200M gimp` finds Flatpak apps over 200 MB matching gimp. I use `@aur >500M` after a few months of Arch use to find the packages that grew without me noticing. ## Safety Veet protects `glibc`, `linux`, `systemd`, and the active shell from selection. Config can extend that list. `runClean` refuses with `refusing: %s is a protected system component` when a match is protected, and config `protected_packages` in `~/.config/veet/config.yaml` adds project specific entries like a custom kernel module or proprietary driver. System paths batch into a single elevated transaction instead of prompting per file. Filesystem removal goes through Afero, which also makes the uninstaller testable without touching a real home directory. History appends to `~/.local/share/veet/history.log` with date, app, source, status, freed size, and detail, so I can review what left the machine last month. ## Themes and config Veet ships 7 palettes: cyan as default, plus catppuccin, nord, dracula, gruvbox, tokyo-night, and monokai. I run catppuccin because it matches the rest of my terminal. Config lives at `~/.config/veet/config.yaml`: ```yaml theme: catppuccin icons: auto protected_packages: - custom-kernel-module - my-critical-service - proprietary-driver ``` Icons accept `auto`, `nerd`, `unicode`, or `ascii`. Auto uses Nerd Fonts unless the session is a raw Linux console or dumb terminal. Unicode falls back to symbols like check and cross marks. ASCII uses plain labels like `[pac]` and `[aur]` with zero font requirements. The installer downloads Nerd Font Symbols v3.3.0 with SHA256 verification when fontconfig reports no Nerd Font, and otherwise leaves fonts alone. ## Install and remove Four paths, same binary. Arch users get an AUR package: ```bash yay -S veet paru -S veet yay -S veet-git ``` The script path compiles with `-ldflags="-s -w"`, installs to `~/.local/bin/veet`, and writes bash, zsh, and fish completions: ```bash curl -sSL https://raw.githubusercontent.com/swadhinbiswas/veet/main/install.sh | bash curl -sSL https://raw.githubusercontent.com/swadhinbiswas/veet/v1.1.0/install.sh | VEET_VERSION=v1.1.0 bash ./install.sh ``` Go users install directly with Go 1.24 or newer: ```bash go install github.com/swadhinbiswas/veet@latest ``` Manual build uses the Makefile: ```bash git clone https://github.com/swadhinbiswas/veet.git cd veet make build make install ``` The Makefile has `build`, `run`, `test` with `go test -v -cover ./...`, `fmt`, `lint` through `go vet`, `install` to `~/.local/bin`, and `clean`. If `~/.local/bin` is missing from `PATH`, I add `export PATH="$PATH:$HOME/.local/bin"` to shell rc. Removal is symmetric: ```bash ./uninstall.sh rm -f ~/.local/bin/veet rm -rf ~/.local/share/veet ~/.config/veet ``` The manual path also removes bash, zsh, and fish completion files. I keep audit logs until I am sure a removal did not take something I wanted, then clear them with `veet history --clear`. ## Keys I press | Press | Effect | |---|---| | 1 to 6 | Jump to stat group for All, Flatpak, Snap, Tools, Cache, Reclaim | | bracket or arrow keys | Cycle stat categories | | up, down, j, k | Move cursor | | space | Toggle multi select | | d | Delete highlighted app with Yes or No popup | | a | Select all visible rows except protected | | o | Cycle sort by size, name, source, date | | p | Toggle staged path inspector | | / | Focus search | | Tab | Cycle source filter | | Enter | Stage and open confirmation preview, Enter again confirms | | c | Clear audit log in history, quick purge for cache in table | | e | Export report to `apps-report.json` | | r | Rescan all detectors | | l | Open history | | s | Open settings and protected registry | | h | Toggle keybinding overlay | | Esc | Close modal or blur search | | q | Quit | Enter twice to confirm feels right in practice. The first Enter stages and shows the full preview modal. The second runs it. ## Limits I accept Veet is Linux only. It does not manage macOS or Windows apps. It stages paths it can see from detectors and home directory scans, so a weird custom install prefix still needs a manual look. Audit export writes to `~/.local/share/veet/apps-report.json`, history caps display at 50 entries unless I raise `--limit`, and scan contexts time out at 60 seconds per the Cobra handlers. Contributions go through `CONTRIBUTING.md`. Detector guides and testing protocols live there. If your root disk keeps filling after removals, start with `veet scan`, then `veet cache`, then one `veet clean --dry-run` on the largest match. That sequence shows the exact paths before anything leaves the disk. --- ## A self-hosted LLM gateway with cost, safety, and MLOps in one container - URL: https://blog.swadhin.cv/blog/self-hosted-llm-gateway-and-mlops/ - Published: 2026-08-16T10:00:00.000Z - Updated: 2026-09-23T12:05:54.000Z - Author: Swadhin Biswas - Categories: Machine Learning, Data Engineering, Backend, DevOps - Excerpt: An OpenAI-compatible endpoint, guardrails, a model registry, drift detection, and Prometheus metrics, packaged as a single Docker container. ### Content Everyone ships an LLM feature by calling a provider directly from the app. It works until you need to know what it costs, what it said, which model version produced it, and whether it is drifting. Eco-Guard is the control plane I wanted in front of that call: one container that speaks the OpenAI API, enforces safety and budgets, and tracks models like software. Repo: [swadhinbiswas/Ecoguard](https://github.com/swadhinbiswas/Ecoguard) ![Eco-Guard architecture](https://cdn.jsdelivr.net/gh/swadhinbiswas/Ecoguard@main/docs/media/architecture.svg) ## Drop-in, not a rewrite The gateway implements `/v1/chat/completions`, `/v1/embeddings` and `/v1/models`, so any OpenAI SDK client points at it by changing the base URL. Behind that it can talk to llama.cpp, Ollama, vLLM, HuggingFace TGI, or any OpenAI-compatible endpoint, and it keeps going with streaming SSE, chat templates for Llama 3, Mistral, ChatML, Gemma and Zephyr, function calling, and batch inference of up to 100 prompts. Fallback chains matter more than they sound. A request can define Model A then Model B then Model C with a timeout per step, which turns a provider hiccup into a slower answer instead of an error page. ## The parts that are usually missing Cost. Every request gets a token count through tiktoken, with a heuristic fallback for unknown models, and a price from a per-model table that covers GPT-4, GPT-4o, GPT-3.5, Claude 3 Sonnet and Haiku, and Llama 3. That feeds a budget cap per workspace with alert thresholds and a comparison view across six providers before the request is made. Safety. Guardrails are a pipeline with per-stage actions: block, flag, sanitize or allow. It detects prompt injection patterns, redacts PII like card numbers, emails and IPs, classifies self-harm, violence and hate keywords by severity, and flags prompt anomalies such as repeated prompts or character-pattern attacks. Lifecycle. The model registry promotes a model through Registered, Staging, Production and Archived with checksum verification and rollback. Deployments can be direct, canary, blue-green or an A/B test. A Z-score drift check can trigger retraining, an evaluation suite can gate a rollout on pass or fail thresholds, and a leaderboard ranks models by latency, accuracy, token efficiency and drift. ## Observability and tenancy Prometheus metrics, OpenTelemetry tracing to Jaeger or Tempo, structured JSON logs with a request UUID, and a 17-panel Grafana dashboard ship with the project. A WebSocket pushes live GPU, queue depth and concurrency data to the UI. Multi-tenancy runs through workspaces with roles and token quotas. Auth is JWT in HTTP-only cookies with scrypt password hashing, or hashed API keys with scopes and expiry, plus Google and GitHub OIDC. Redis backs a sliding-window rate limiter and a circuit breaker, and admin endpoints can be limited to a CIDR range. Configuration is a YAML file with hot reload for routes, keys, guardrails and pricing. ## Stack and how it runs Python 3.12 with FastAPI, Vue 3 for the UI, PostgreSQL 15, Redis, and Docker or Kubernetes. The test suite is at 169 of 173 passing, and there is a Python SDK plus a CLI for chat, cost comparison and guardrail checks. The design bent toward one idea: the model is a dependency you operate, with a version and a price attached. Once the gateway holds the routing, the prices, the checks and the lifecycle, the application can change models without a deploy, and every answer has a cost and a version attached to it. The source, the Grafana dashboard and the deployment docs are in the repository above. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Anomaly detection on free satellite data, end to end for nothing - URL: https://blog.swadhin.cv/blog/anomaly-detection-on-free-satellite-data/ - Published: 2026-08-09T10:00:00.000Z - Updated: 2026-09-23T12:05:45.000Z - Author: Swadhin Biswas - Categories: Machine Learning, Data Engineering, Architecture - Excerpt: Four public sources, a versioned lake on Hugging Face, dbt transforms, an IsolationForest, and a dashboard at the edge. The compute bill is zero. ### Content Public satellite data is free and enormous, which is why most people look at it once and never load it again. TerraSentinel is a full pipeline over that data: ingestion, a versioned lake, SQL transforms, unsupervised ML, and a dashboard, running on free tiers from end to end. Repo: [swadhinbiswas/TerraSentinel](https://github.com/swadhinbiswas/TerraSentinel) · Dashboard: [terrasentinel-dashboard.pages.dev](https://terrasentinel-dashboard.pages.dev) It watches four things: wildfire, deforestation, glacier and ice melt, and (as a fourth source) European power load. On the current run the dashboard reports 268,543 fire detections and 32 flagged days. ## Who does the work GitHub Actions runs the compute. Hugging Face Hub stores the bronze lake and the model registry. Turso serves the gold tables. Cloudflare Pages serves the dashboard. Nothing on the request path runs Python. ![TerraSentinel architecture: four public sources feed cron-scheduled collectors into a versioned Hugging Face bronze lake, which dbt and DuckDB turn into gold marts synced to Turso, while an ML branch trains an IsolationForest and batch scores predictions back into Turso.](https://cdn.jsdelivr.net/gh/swadhinbiswas/TerraSentinel@main/docs/architecture.svg) The transform layer is dbt on DuckDB, reading Parquet straight over HTTPS from the Hub. Bronze to staging dedupes detections and unifies MODIS and VIIRS brightness. Intermediate models build a dense region-by-day spine so zero days actually exist, a sparse H3 cell count for the map, and a seasonal baseline using a median and MAD over a circular window of fifteen days. The gold layer has one mart per source arm, and that split is deliberate. A single combined "all ice" mart required every input to exist, so a missing Sentinel source also removed sea-ice results that were healthy and unrelated. Splitting the marts means an outage can only remove its own table, and the dashboard just reads whichever tables are present. ## Lineage that means something The model registry cannot share the dataset repo, because repo type is part of the address on the Hub and model cards are a model-repo feature. That is why there are two repos: one dataset, one model. Keeping the lake in a git-backed dataset repo is what gives model lineage a real answer. MLflow logs the exact dataset commit hash behind every training run, and the published model is an IsolationForest on 27 strictly causal features traced to bronze commit `445d10f3`. A bucket would not have given me that. The model card measures instead of asserting. Model flags are compared against an independent median/MAD rule in the gold table, and precision, reference recall and Jaccard are printed. When the two agree almost completely, the card says so and gives the reason: the top 2.5 percent of fire days run about twenty times the rest, so the anomaly is easy to separate and every method finds the same days. That is the honest result, and it is more useful than a headline number. ## Serving without a backend Batch scoring applies the registered model to the latest gold features and writes `anomaly_score` into Turso as part of the scheduled job. The dashboard's API routes only do a fast SQL read, which keeps the edge functions inside Cloudflare's CPU budget and the pages quick. On the current run 76,607 rows are synced into Turso, including 1,462 model predictions, and the dashboard reads it in under ten milliseconds through Pages Functions. One detail worth stealing: DuckDB's `hf://` filesystem goes out anonymously unless a token is registered, and anonymous reads share the Hub's public rate-limit pool, so a scheduled job eventually returns HTTP 429. The token is registered deliberately outside dbt so it never reaches compiled SQL or an uploaded artifact. ## What the data says The numbers are real and checkable: 592 unit tests, a dbt build of 117 nodes, and a type-checked dashboard build, all runnable offline against a synthetic lake with deliberately injected anomalies. Arctic sea-ice extent in June 2026 is running about 1.3 million square kilometres below the 1981 to 2010 norm, a z-score near minus 3.3. The project also ships a Databricks path (Asset Bundle, Unity Catalog, Workflows, MLflow) as a tested reference. The free path stays primary, and the point of the exercise is that the same lake and the same SQL move between them without a rewrite. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## JustAPI: a Python web framework with a Rust core — the story, the numbers, and what I actually learned - URL: https://blog.swadhin.cv/blog/just-api-a-python-framework/ - Published: 2026-08-08T18:19:06.325Z - Updated: 2026-08-08T18:19:06.000Z - Author: swadhinbiswas - Categories: AI, Render Tests, Encryption, Backend, Performance, Architecture, Technology, Tutorials, News, APIs - Excerpt: JustAPI is a Python web framework where the web server, the router, the TLS termination, the request validation, the JSON serialization, and the database access all run in Rust. Your Python code handles the application logic. That is the entire premise, and it is the one sentence that explains every design decision in the project. ### Content > **Read this first.** I built JustAPI — I'm Swadhin Biswas — with agentic AI as > a guide: AI helped me design, implement, debug, and document a large part of > this project. I am not claiming this is the best framework in the world, and > I am not claiming every number here was measured on your hardware. I am > describing what I built, why I built it, what I verified, and — just as > important — what I tried that did not work. The documentation site is large, > much of it written with AI assistance, and not everything in it is > independently verified. If you find a claim that seems wrong, it probably > is. Verify it, and open an issue. > > **What this article is:** a technical write-up. **What it is not:** marketing. --- ## 1. What JustAPI is JustAPI is a Python web framework where the web server, the router, the TLS termination, the request validation, the JSON serialization, and the database access all run in Rust. Your Python code handles the application logic. That is the entire premise, and it is the one sentence that explains every design decision in the project. ```python from justapi import JustAPIApp app = JustAPIApp() @app.get("/") def hello(): return {"Hello": "World"} app.run() # a real server, not a dev server ``` That is a complete program. It gives you HTTP/1.1 and HTTP/2, TLS, routing with path and query parameters, JSON serialization, automatic OpenAPI docs at `/docs`, and a server that does not need uvicorn or gunicorn. All of it runs in Rust. The Python process just runs your handler. The package is on PyPI (`pip install justapi`), it works on Linux, macOS, and Windows, and there are wheels for the free-threaded build of CPython 3.14t. --- ## 2. Why I built it (the story) The starting point was a simple observation that most Python web frameworks treat as a given: **the framework runs in Python.** FastAPI runs on Starlette, Starlette runs on uvicorn, and uvicorn is a Python event loop with a lot of asyncio machinery between the socket and your handler. Robyn and Granian moved the *server* to Rust, but the request still crosses into Python for routing, validation, and serialization. I asked a different question: what if almost nothing crossed into Python? What if the framework — the thing that does the same work on every request — lived entirely in Rust, and Python only ran the code that is different for each application? That question shaped a project with an unusual constraint, which I wrote down early and enforced throughout: **if a feature can be implemented in Rust, it must be implemented in Rust.** Not "can be implemented faster in Rust" — *can be implemented in Rust*. Python in the framework is reserved for the parts that have to be Python: the glue between Rust values and your handlers. I did not do this alone. I worked with agentic AI throughout — using it as an engineering guide. I made the architecture decisions; the AI helped me turn them into working code, find the bugs I could not see, write the tests, and keep the project honest when I wanted to skip the boring parts. There are parts of this codebase I understand completely, parts I understand well enough to maintain, and parts the AI wrote that I reviewed and tested but would be lying if I said I could reproduce from memory. I am not hiding that; it is part of how this project exists. The project then went through the standard engineering motions, in order: 1. A minimal server: tokio + hyper, a PyO3 boundary, one route. Measured 766k req/s on the hello-world fixture. 2. A native router (matchit radix trie, 51ns average lookup on 500 routes). 3. A memory pipeline (per-request arena, buffer pools). 4. Middleware in Rust: CORS, security headers, JWT, rate limiting. 5. Serialization in Rust (serde_json, optional simd-json). 6. TLS with rustls — no OpenSSL dependency. 7. A native API surface, replacing the ASGI shim. 8. Database access via sqlx: SQLite, PostgreSQL, MySQL, DuckDB. 9. WebSockets, SSE, background tasks, a scheduler, a plugin system. 10. Operational tooling: OpenTelemetry, Prometheus metrics, health checks, circuit breakers. None of this was fast in the sense of "one weekend." It was fast in the sense of "the numbers are in the repo, the tests pass, and the failures are documented." The release history tells part of the story on its own: | Version | What changed | |---|---| | 2.0.8 | Multi-threaded tokio server, free-threaded CPython support, async handler fix (14× async throughput) | | 2.0.9 | Native async DB awaits, Rust-native SSE, type stubs, tokenless CI publishing, first PyPI release | | 2.0.10 | The CLI shipped in the wheel (it was a stub before) | --- ## 3. The architecture The request path is a pipeline, and almost every stage is Rust: ``` Kernel (epoll/io_uring) → tokio connection manager (multi-threaded) → TLS (rustls) → HTTP parse (hyper) → Router (matchit, ~51ns lookup) → Middleware chain (auth, CORS, rate-limit, compression) → Python boundary (zero-copy PyO3, GIL pool) → Your Python handler → Rust serializer (serde_json / simd-json) → Response write → socket ``` The crate layout mirrors the pipeline: ``` justapi/ ├── crates/ │ ├── justapi-core/ # networking, routing, middleware, serialization, DB pool │ ├── justapi-py/ # PyO3 bindings + the Python package │ ├── justapi-cli/ # the `justapi-cli` binary (serve, create, check, profile) │ └── justapi-bench/ # benchmark harness ├── python/justapi/ # pip-installable package (maturin-built) ├── BENCHMARKS.md # append-only performance ledger ├── DECISIONS.md # ADR log (ADR-001 through ADR-093) └── PLAN.md # roadmap with an honesty status on every phase ``` The dependency graph is intentionally small: ``` justapi-cli → justapi-core justapi-py → justapi-core justapi-bench → justapi-core ``` ## 4. The numbers (verified, with the hardware caveat) All numbers below are from `BENCHMARKS.md`, measured on a single machine with 100 concurrent connections and 30-second runs. **Your machine will differ.** What matters is the *ratio* on the same hardware, not the absolute numbers. | Framework | Hello-world req/s | JSON echo req/s | p99 hello-world | RSS | |---|---|---|---|---| | JustAPI (native fast path) | 766k | 782k | 0.48 ms | 12 MB | | Granian (ASGI) | 314k | 145k | 0.74 ms | 37 MB | | Robyn | 39k | — | — | — | | FastAPI + Uvicorn | 36k | 33k | 24.63 ms | 29 MB | The "native fast path" needs two things: a route registered with `native=True` and a `Schema`. In that configuration, Rust validates the body and writes the response — Python never runs. Without a schema, you get the Python handler path, which is GIL-bound at roughly 60–120k req/s on this hardware, same as any other Python framework. Other verified numbers: - Route lookup: 51ns average on a 500-route table. - Native CRUD SELECT: 181k req/s — 125× FastAPI on the same SQLite fixture. - Native async DB awaits: 320 RPS vs 6 RPS for the blocking path on a slow query (a 2M-row recursive CTE) — 53×. - Multi-worker prefork (`justapi serve --workers 4`): 1.88× throughput (99.7k RPS vs 53k). - Free-threaded CPython 3.14t, CPU-bound Python handler: 12.4× vs GIL-locked — the GIL ceiling disappears. **What I do not claim:** there is no "beats every framework on every workload" claim here. Light async handlers (no I/O, just `asyncio.sleep`) sit at 4–12k req/s — the asyncio loop floor — and I measured that Granian's direct loop dispatch is faster on that specific shape. I do not hide it; it is in the benchmarks and in the article below. ## 5. The async story: what I tried, and what the measurements said This is the most important section in this article, because it is where I spent the most effort proving myself wrong. The initial async path was bad. An async handler doing `await asyncio.sleep(0.001)` served about **808 RPS** — a hard ceiling, not contention. The single GIL worker was blocking on each coroutine's full duration, serializing every async request. Fixing that (ADR-083) took async throughput from ~800 to **11,758 RPS** — 14× — by making completion callback-driven instead of blocking. Then I got ambitious. The plan was: "make the awaits Rust-native." If a Python coroutine's `await` could complete on tokio instead of on the asyncio loop, per-await overhead would drop, and I would beat Granian on async. I built four approaches and measured every one: | Approach | Per-await overhead | Verdict | |---|---|---| | `future_into_py` (Rust future wrapped as an asyncio.Future) | 2× slower than `asyncio.sleep` | The wrapper + cross-runtime wakeup costs more than the loop's own timer | | `into_future` (coroutine → Rust future) | tied at best | Requires a running asyncio loop for task-locals; does not decouple | | Hand-rolled driver, GIL attach per await | ~1125 µs/await | Thread-state setup dominates | | Hand-rolled driver, persistent thread | ~3.4 µs/await solo | **86× worse concurrent** (thread per coroutine) | | asyncio loop (status quo) | ~45 µs/await | The only mechanism that scales | The multiplexing driver — one persistent Rust thread stepping many coroutines, the design that should have worked — measured **16 µs/await vs asyncio's 0.56 µs/await on pure stepping** (ADR-091). The absolute floor, a bare `await noop()` in asyncio, is **0.039 µs**. The conclusion, written into the ADR log: *the Python coroutine `send()` stepping is the irreducible floor, and asyncio already runs it at the minimum possible rate. Any Rust wrapper around `send()` adds overhead; it cannot subtract it.* A multi-loop dispatch experiment (ADR-092) also came back neutral-to-worse: the GIL worker is the single dispatch point, so extra loops only added GIL contention. I stopped. That is the part of engineering nobody writes articles about: the work you delete. The async path stays on asyncio, which is the right answer, and I went back to making the *operations* native instead of the coroutine. ## 6. Native operations: where the real win is Since I cannot make Python coroutines faster, I made the framework operations they await faster — by taking Python out of them. **Native async DB awaits (`query_async`).** A normal async handler doing a database query would block the asyncio loop thread for the whole query. One slow Postgres query froze every other async handler on the server. `await app.db.query_async(...)` runs the SQL on the DB's own multi-threaded tokio runtime with the GIL released. The loop is never blocked. Measured: 53× faster than the blocking path on slow queries, and it is the only path that is *safe* for real databases with network latency. **Rust-native SSE (`sse_native`).** A stream of events is generated entirely in Rust — tokio timers, an mpsc channel, the HTTP layer drains it. Zero Python per event. 100k events stream instantly. **`@native_async`.** A marker that routes async handlers to the fastest dispatch path, and on free-threaded CPython enables true parallel dispatch across workers. The pattern is consistent: Python declares the operation, Rust executes it, and nothing in the middle is Python. ## 7. Bugs I found in my own framework (and fixed) The honest part of any framework article is the bug list. Some highlights: **Write-path collapse.** Concurrent Python-handler writes dropped to ~3 RPS at 11 connections (from ~150 at 10). The request-scoped auto-transaction was double-acquiring pool connections — 2N for N writes. Removed. (ADR-080) **GIL pool not fork-safe.** A forked child inherited the parent's initialized GIL pool whose worker threads did not exist, so every Python request hung and returned 504s. The pool now tracks its PID and rebuilds after fork. This was also the root cause of a long-standing flaky test. (ADR-081) **Pydantic models as `body_schema` were broken.** `validate_body` treated a Pydantic model class as a plain callable and invoked `BaseModel(body_dict)`, which raised `TypeError`. This broke the single most important FastAPI migration path. Fixed by validating through `model_json_schema()` in the Rust engine. It shipped fixed in 2.0.9. **`app.run()` required an address.** The README quickstart showed `app.run()` with no arguments, which crashed with a `TypeError`. Now defaults to `127.0.0.1:8000`. **The CLI in the wheel was a stub.** The PyPI package's `justapi` command printed a help message and did nothing else. It shipped fixed in 2.0.10 (serve, create, check, openapi — and it delegates to the Rust CLI when installed). **Unix-only APIs were not cfg-gated.** `UnixListener`-based functions failed to compile on Windows. Gated with `#[cfg(unix)]`. Each of these is in the changelog with the commit that fixed it. None of them was found by reading the code. They were found by running things, by benchmarking, and by trying to use the framework the way a user would. ## 8. What JustAPI ships that no other Python framework ships - **HTTP/3 (QUIC)** — feature-gated, serves Python handlers over QUIC through the full native pipeline. As far as I know, the only Python framework with a working HTTP/3 transport. - **Free-threaded CPython wheels** (3.14t) with auto-detected parallel dispatch. - **Rust-native SSE** where the stream never touches Python. - **Multi-worker prefork with auto-scaling** built into the CLI. - **OIDC trusted publishing** — the release pipeline uses zero tokens; a tag push builds 9 platform wheels and publishes them. ## 9. The honest caveats (read this before using it) 1. **The documentation site is large and much of it is AI-written.** I generated a lot of the docs with AI assistance. I verified the code and the benchmarks; I did not independently verify every sentence in every doc page. If you rely on a doc page, test the behavior yourself. Some doc pages were already found to describe APIs that did not exist, and I fixed them as I found them. There are probably more. 2. **The LLM/inference features are unverified.** Phases 41–52 of the roadmap (inference engine, KV cache, continuous batching, OpenAI-compatible server) are implemented but were never run with real GPU weights. The only honest status is "implemented, not verified." They are not part of the release story, and I do not make performance claims about them. (ADR-067) 3. **The absolute numbers are from one machine.** Ratios matter; absolutes depend on hardware, OS, and load generator. 4. **The roadmap contains 17 "implemented but unverified" phases.** I mark them 🟡 in PLAN.md. That is not a typo. It means: code exists, tests pass, and the real-world claim is not proven. 5. **Async light handlers are loop-bound.** If your handler is `await asyncio.sleep(0.001); return {}`, JustAPI is not faster than Granian. I measured it. Use the native operations for DB/SSE/IO work. 6. **There is no 1M RPS claim here.** The roadmap phase title once said "1M RPS tuning." I never measured 1M RPS. I changed the status to reflect that. (The phase overclaims; I say so in PLAN.md.) 7. **First impressions matter, and mine were rough.** The first published CLI was a stub. `app.run()` crashed without an argument. The docs had fabricated API references. All fixed, but if you are evaluating the project, the version history is honest about the rough edges. ## 10. How to actually use it ```bash pip install justapi==2.0.10 ``` ```python # main.py from justapi import JustAPIApp, native_async from pydantic import BaseModel app = JustAPIApp() app.set_database("sqlite://app.db") class Item(BaseModel): name: str @app.get("/") def root(): return {"Hello": "World"} @app.get("/items/{item_id}") async def get_item(item_id: int): return await app.db.query_async( "SELECT * FROM items WHERE id = ?", [item_id]) @app.post("/items", body_schema=Item) def create(request): data = request.json() return app.db.execute( "INSERT INTO items (name) VALUES (?)", [data["name"]]) # Rust-native SSE: no Python per event app.sse_native("/events", count=1000, interval_ms=0) app.run() # defaults to 127.0.0.1:8000 ``` Then: ```bash python main.py justapi check main.py # validate routes without serving justapi serve 0.0.0.0:8080 # or use the CLI ``` For the high-performance Rust CLI: ```bash cargo install justapi-cli # provides serve --workers N --reload, create, profile ``` ## 11. Where to verify everything in this article | Claim | Source | |---|---| | Benchmarks, methodology, hardware | `BENCHMARKS.md` in the repo | | Architecture decisions (all 93) | `DECISIONS.md` — ADR-001 through ADR-093 | | Roadmap status incl. unverified phases | `PLAN.md` (the honesty key is at the top) | | Async experiments and their failure | ADR-090, ADR-091, ADR-092 | | Native async DB awaits | ADR-093 | | Bug fixes | `CHANGELOG.md` (2.0.8 → 2.0.10) | | Code | https://github.com/swadhinbiswas/JustAPI | | Docs | https://justapi.pages.dev | --- ## 12. The thing I actually learned The takeaway of this project is not "Rust is faster than Python." Everyone knows that. The takeaway is more specific and more useful: **The performance of a Python web framework is decided by how much Python runs per request — and the parts you cannot remove, you should not try to make faster by rewriting them in Rust.** I tried to make asyncio faster by moving it to Rust. The measurements said no. I made the operations *around* asyncio native instead, and that worked: 53× on slow database queries, 125× on native CRUD, zero-Python SSE. The framework's job is to decide which parts of a request are yours and which are the framework's — and then to make the framework's parts not run Python at all. That, and the discipline to write down the failures, is what JustAPI is. There is a second lesson, specific to how I built this: **agentic AI is a force multiplier, not a substitute for judgment.** The AI guided me through Rust lifetimes, PyO3 FFI, and tokio internals I had never touched before. It also wrote things that were wrong, and I only caught them because I benchmarked, tested, and read the output. Use the tool; verify the work. --- *Written by Swadhin Biswas, maintainer of JustAPI, with agentic AI as a guide. Corrections welcome — open an issue at https://github.com/swadhinbiswas/JustAPI/issues. If a number here disagrees with your measurement, your measurement wins.* --- ## GDPR and the append-only log: a lakehouse that has to forget - URL: https://blog.swadhin.cv/blog/gdpr-and-the-append-only-log/ - Published: 2026-07-26T10:00:00.000Z - Updated: 2026-09-23T12:05:48.000Z - Author: Swadhin Biswas - Categories: Data Engineering, Backend, Architecture, Distributed Systems - Excerpt: Kafka and Parquet are append-only by design. Article 17 is not. This is a medallion lakehouse built around a six-layer deletion cascade. ### Content Most data infrastructure is built on one assumption: writes are append-only. Kafka appends events into partitions, and Iceberg, Delta and Hudi write immutable Parquet files. Under the GDPR that assumption runs into a legal obligation. Article 17 says a person can ask you to erase their data, and Article 12 puts a clock on the response. EuroStream is my attempt to build a lakehouse where erasure is a first-class operation instead of a support ticket. Repo: [swadhinbiswas/eurostream](https://github.com/swadhinbiswas/eurostream) · Lake: [Hugging Face](https://huggingface.co/datasets/swadhinbiswas/eustream) · [Architecture RFC](https://github.com/swadhinbiswas/eurostream/blob/master/docs/rfc/0001-platform-design.md) ![EuroStream end-to-end system architecture](https://cdn.jsdelivr.net/gh/swadhinbiswas/eurostream@master/assets/endtoendsystem.png) ## Where append-only breaks I mapped the problem into five failures that show up in production. A raw event log retains the original payload, and rewriting a partition or mutating consumer offsets to remove one person's data tends to corrupt downstream state. Materialized aggregates keep ghost records: delete a customer upstream and `gold.customer_360` still reports their lifetime spend and marketing flags. Stateful stream processors hold rolling window state in memory, so an erased customer can sit in a deque for hours and trigger false fraud alerts. Serverless and ephemeral containers wipe in-memory suppression caches on restart, which produces split-brain governance. And microservices keep adding PII columns nobody classified. ## The deletion cascade The core of the project is a synchronized six-step transaction: ``` Suppression -> Bronze mask -> Silver hard DELETE -> Gold hard DELETE -> Alert state purge -> Lake re-export ``` When Article 17 fires, raw Bronze columns are masked in place to `` so the ledger keeps its row ordering. Silver records are hard deleted, since PII there is already pseudonymized with a salted SHA-256 hash `H(s, x)`. Every affected Gold aggregate partition is recomputed, and the public Parquet lake is replaced atomically so a de-identified copy does not keep a ghost. A global suppression registry intercepts replayed or delayed events before they reach a consumer. The streaming side does the same thing in memory. Before a payment is scored for velocity, Z-score or geo-mismatch, `FraudScorer` checks `erasure.is_suppressed(cust_id)`. On deletion the customer's window deque and alert history are evicted immediately, so an erased identity cannot set off an alert later. ## Two engines, one watermark EuroStream pairs a local embedded DuckDB for microsecond analytics with a distributed Turso libSQL replica for durability. Every write, merge, watermark advance and erasure mutation is dual-written over HTTP v2. On a container restart the suppression sets and warehouse state come back automatically, which is what keeps a serverless deployment from drifting. The event bus has two implementations behind one interface: `SqliteBus` locally, in WAL mode with `BEGIN IMMEDIATE` for concurrency, and `KafkaBus` in production over Aiven with SASL_SSL and SCRAM-SHA-256. The speed path and the batch path share no state, which is what makes the erasure transaction safe to reason about. ## Governance in CI PII detection includes IBAN checksum verification (ISO 13616, ISO 7064 mod 97), and a contract baseline gate blocks any pull request that introduces an unclassified column or a breaking schema change. The medallion layers carry the policy directly: Bronze keeps PII internally and is never exported, Silver is pseudonymized, and Gold marketing analytics are gated on `bool_and(marketing_consent)` so a withdrawn consent removes a person from the aggregates. The project is pure Python, typed strictly with mypy and linted with ruff, with 59 tests across the streaming and batch paths. ## What I took from it Erasure is the hardest test of a data architecture, because it forces you to know where every copy of a record lives. If you cannot name each place a person's data sits, you cannot delete it. Building the cascade meant documenting the storage tiers first and designing for the delete path second, which is the reverse of how most pipelines get written. The repository, the RFC and the published lake are linked above. If you are building anything that falls under the GDPR, the deletion path is worth designing on day one rather than bolting on later. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## A European air-traffic lakehouse that runs on free tiers - URL: https://blog.swadhin.cv/blog/a-european-air-traffic-lakehouse-on-free-tiers/ - Published: 2026-07-12T10:00:00.000Z - Updated: 2026-09-23T12:05:43.000Z - Author: Swadhin Biswas - Categories: Data Engineering, Backend, DevOps, Architecture - Excerpt: Kafka on a small VPS, DuckDB and dbt in CI, and a read-only Turso copy for the browser. How I built a live European airspace pipeline without a cloud budget. ### Content I wanted to answer one question: what does European airspace actually look like right now. Then I wanted to be able to prove the numbers, which turns a dashboard into a pipeline. It has run for months on free tiers, and the code is archived on Zenodo. Repo: [swadhinbiswas/eu-air-traffic](https://github.com/swadhinbiswas/eu-air-traffic) · Live: [airtraffic-eu.pages.dev](https://airtraffic-eu.pages.dev) · Data lake: [Hugging Face](https://huggingface.co/datasets/swadhinbiswas/air-traffic) ## What it serves The live map shows around 2,000 aircraft with callsign, type, altitude, speed, vertical rate and route lines, plus weather stations and search by callsign, registration, type or airport. Alongside that sit delays, punctuality, cancellations, airport and airline leaderboards, route performance and weather impact. Eurostat's official monthly passenger numbers sit next to the movements this platform counted itself, so a wrong number has somewhere to show up. ## The shape of the pipeline A collector on a small VPS polls the upstream APIs and publishes to a five-topic Kafka cluster. Every fifteen minutes a scheduled job drains Kafka, builds the Bronze, Silver and DuckDB layers, runs dbt, then publishes to three places: Hugging Face for the dataset lake, MotherDuck for the full warehouse, and Turso for the copy the browser is allowed to read. ![EU air traffic pipeline: a VPS collector publishes to Kafka, a scheduled job builds bronze, silver and dbt marts, and Hugging Face, MotherDuck and Turso serve the dashboard.](https://cdn.jsdelivr.net/gh/swadhinbiswas/eu-air-traffic@main/images/repo-eu-air-traffic.webp) The sources are all public: OpenSky for movements, adsb.lol for live positions with airplanes.live and OpenSky as fallbacks, AirLabs for schedules and delays, aviationweather.gov for METAR and TAF, Open-Meteo for forecast, and Eurostat `avia_paoa` for the monthly passenger benchmark. Reference data from OurAirports, OpenFlights and ICAO 8643 is built once, and the OpenAP kinematic model is precomputed into a 37-type fuel lookup. ## Why there are two serving stores MotherDuck holds the full warehouse, but its user model cannot hand a scoped read-only token to a browser. Turso can, so the site reads a derived, bounded copy there instead: small enough to hold cheaply and safe to expose. Paging totals come from a precomputed `site_summary` row, so a browser poll never scans a fact table. Free-tier accounts carry their own read and write budgets, so the serving copy is spread across several Turso databases through `TURSO_TARGETS`. A table listed in more than one target is mirrored, each copy synced and versioned on its own. When one account runs out of quota or goes down, the publisher keeps going and the browser fails over to a healthy copy. No Turso replication is involved. Every target is an independent database. ## Working inside provider budgets The project is shaped as much by limits as by goals. | Limit | What I did | |---|---| | Kafka allows five topics per cluster | One topic per domain; weather and reference data multiplex with a `_kind` discriminator the sink splits back into datasets | | OpenSky meters credits per endpoint | `/flights/all` for both ends in one request, live departures for four hubs, a nightly arrivals backfill, around 2,700 of 4,000 daily credits | | AirLabs gives 1,000 calls a month at 50 rows each | Rotating hubs and a persisted monthly counter that stops at the budget; IATA to ICAO resolved from bundled data | | Turso meters reads and writes | Aggregates precomputed into one summary row, static tables uploaded only when a content hash changes, growing tables watermark-synced | | Object storage meters commits | Silver partitioned per source, only changed files pushed, unchanged files treated as no-ops | | The VPS has two cores | The box only collects; every transform runs in CI | The collector is deliberately the only long-running process. If it dies, the pipeline still drains whatever Kafka retained. ## What running unattended taught me Most of the work went into failure handling rather than the happy path, and each item below has a test behind it. A step once logged an error and exited 0, which meant a rejected upload looked like a success. Failures are loud now, and credentials that are set but empty raise instead of silently skipping. A failed lake pull could push a single window over the full Silver history, so pulls fail the job. Publishers now load static tables into a shadow table and swap, rather than wiping a serving table mid-run. OpenSky movements and AirLabs schedules describe the same flight with different ids, so marts dedupe on callsign, date and endpoint, and only average delays that are actually known. Casting a timestamp with a time zone to a plain timestamp shifted rows by the session offset and quietly re-read old data, which is the kind of bug that makes you distrust every date column you own. The repository ships an AWS serverless analytics plane as code (Lambda, S3, Glue, Athena, QuickSight) to show the scale path. It is not provisioned. What runs today is the free pipeline, every cycle, at zero cost. The full source, the 103 dbt models and the dataset are linked above. Air-traffic data is a good teacher because the upstream sources are messy in the same ways every real source is: rate limits, duplicate ids, and clocks that disagree. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## A browser media engine without FFmpeg WASM - URL: https://blog.swadhin.cv/blog/a-browser-media-engine-without-ffmpeg-wasm/ - Published: 2026-07-05T10:00:00.000Z - Updated: 2026-09-23T12:25:22.000Z - Author: Swadhin Biswas - Categories: Performance, Architecture, Programming - Excerpt: Most web players ship a 30 MB software decoder and hope the phone survives it. VidoLib decodes through WebCodecs instead, and ships every parser as its own plugin. ### Content Web media players tend to fail in one of two directions. The first is the monolithic player that bundles a 15 to 40 MB FFmpeg WASM binary so it can decode everything. It works on a fast machine and a good connection, and then it meets a mid-range Android phone on a train, where it adds seconds to startup, holds hundreds of megabytes of RAM for the life of the session, and drains the battery doing in software what the operating system would happily do in hardware. The second is the rigid player that hardcodes layout, networking, and UI into one package, so customizing anything means forking the whole thing. VidoLib takes a third position: use the browser's own media pipeline, and make every other piece a package you opt into. Repo: [swadhinbiswas/VidoLib](https://github.com/swadhinbiswas/VidoLib) ## The observation that started it Browsers spent a decade building a hardware media stack. WebCodecs exposes the platform decoders. WebAudio and AudioWorklet handle the audio path. WebGL and WebGPU render frames. Between them, a modern browser can play HLS, DASH, MP4, WebM, MKV, FLV, TS, and subtitles without a software decoder in sight. An app that ships FFmpeg WASM anyway is paying for capability it already has. The reason most players do it is portability and habit: a WASM decoder behaves the same everywhere, and the platform path has edges you have to learn. The cost is real and shows up exactly where it hurts, on the devices with the least memory. ## What the difference looks like in numbers The project keeps a comparison against the WASM approach, and the gaps are large enough to be the whole argument. | Metric | Native VidoLib | FFmpeg WASM players | |---|---|---| | Engine download | 3.4 KB to 30 KB | 15 MB to 40 MB | | Startup latency | under 110 ms | 1,500 ms to 4,000 ms | | Memory footprint | under 18 MB | 150 MB to 400 MB | | Battery | OS hardware decoders | CPU-bound WASM threads | | Mobile web | native decoder support | frequent out-of-memory crashes on iOS Safari | The last row is the one that ends most arguments. Under WebKit's tighter tab memory limits, a WASM player that works in testing can be evicted on a real iPhone at the worst moment. Hardware decoding sidesteps the failure mode instead of tuning around it. ## The architecture A load request moves through a predictable chain, and the layering is what makes the size claims honest. ```mermaid flowchart LR A[Stream layer
HTTP Range / Blob / WS / WebRTC] --> B[Container parser
MP4 / MKV / WebM / TS ...] B --> C[WebCodecs
hardware decoder] C --> D[Renderer
Canvas2D / WebGL / WebGPU] C --> E[WebAudio
AudioWorklet] F[ABR engine] -.-> A G[Clock / EventBus] -.-> D G -.-> E G -.-> F ``` The stream layer fetches bytes, the container parser demuxes them, the decoder produces frames and audio, and the render and audio sinks present them. A clock and event bus coordinate the pieces, and an adaptive bitrate engine feeds back into the stream layer. Every box in that diagram is a separate package. ```svg core 3.4 KB ``` ## Twenty-two packages and a small core The core is 3.44 KB gzipped and bundles no decoders. Everything else is its own package with its own size: the stream layer at 2.83 KB, containers at 14.11 KB, the HLS and DASH manifest parsers at 6.99 KB, the ABR engine at 1.75 KB, codecs at 4.63 KB, the transcoder at 1.50 KB, WebGL filters at 3.34 KB, the recorder at 1.62 KB, renderer backends at 5.36 KB, subtitles at 5.21 KB, a WCAG 2.1 AA UI at 5.49 KB, the worker pipeline at 2.73 KB, a zero-tracking telemetry package at 1.76 KB, a security package at 1.83 KB, and a plugin registry at 1.42 KB. That structure is the feature. A player that only needs HLS imports the stream layer, the manifest parser, the codecs negotiator, and a renderer, and lands under 15 KB gzipped. Nothing pulls in the MKV parser, the recorder, or the filter chain unless the app asks for them. Micro-frontend and bundler hygiene are usually an afterthought that gets fought later; here they set the package boundaries from the start. The capabilities are the FFmpeg operations web apps actually need, reimplemented natively. A `@vidolib/transcoder` package encodes frames to H.264 or VP9 through `VideoEncoder`. A `@vidolib/filters` package does chroma key, brightness, contrast, blur, and watermarking as GPU passes. A `@vidolib/recorder` package records canvas or a media stream to MP4 and WebM. A `@vidolib/containers` registry auto-demuxes across MP4, MKV, WebM, AVI, MOV, FLV, TS, PS, OGG, and ASF. The subtitle engine handles ASS, SRT, and VTT. ## Patent and licensing, handled deliberately Hardware decoding has a second benefit that is easy to miss. Licensing for codecs like H.264, HEVC, and AC-3 sits with the codec pool, and an application that decodes those in software can inherit that liability. By decoding exclusively through the operating system and browser hardware paths, VidoLib keeps the question at the platform layer. The project makes the boundary explicit: the MIT license covers the source and does not grant patent rights for any codec the deployment target does not already license. ## Testing a demuxer Media parsing is the kind of code that fails on the one file nobody tested. VidoLib runs 118 unit tests, spread across containers, manifest, codecs, subtitles, filters, worker, renderer, core, utils, and UI, plus a fuzz pass of 8,000 iterations across every demuxer. Fuzzing a container parser is not optional if the input comes from the network, because a malformed header is an attack surface as much as a bug. ## Where it is VidoLib is pre-release. The packages build from source with esbuild and are not published to npm yet, and the API can change before v1.0.0. The architecture and plugin-authoring docs are in the repository, and a custom plugin is meant to be under thirty lines. The broader lesson is one I keep meeting: before shipping a large dependency, check what the platform already does. The browser has a hardware media pipeline that most players ignore in favor of a WASM binary, and using what is already there is faster, smaller, and easier on the device. The hard part is not capability, it is trust in the platform, and the way to earn that trust is to test the edges properly. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Isolated instances of any CLI, rootless - URL: https://blog.swadhin.cv/blog/isolated-instances-of-any-cli-rootless/ - Published: 2026-06-21T10:00:00.000Z - Updated: 2026-09-23T12:25:20.000Z - Author: Swadhin Biswas - Categories: Backend, DevOps, Programming - Excerpt: Two GitHub accounts, two Discords, a stable and a beta of the same tool, all on one machine with no container, no daemon, and no sudo. The isolation model is three ideas and a path rewrite. ### Content The need shows up in the most ordinary way. You have a work GitHub account and a personal one, and the `gh` CLI stores its auth in one place. You want the stable release and the beta of the same tool installed side by side, and the second install overwrites the first. You have two Discord accounts, and the desktop app keeps exactly one login. Each of these is a five-minute annoyance that recurs forever, and the standard fix is to reach for a container, which means writing a Compose file and hand-wiring volumes to run what is fundamentally a single binary. Warren takes the position that most of what a container provides is overhead for this job, and that the isolation people actually need is a private home directory and a rewritten path. Repo: [swadhinbiswas/warren](https://github.com/swadhinbiswas/warren) ## Two accounts, one tool The everyday use is deliberately small. ```bash warren dig gh --as gh-work warren dig gh --as gh-personal gh-work # logs into your company GitHub gh-personal # logs into your personal GitHub ``` Both instances behave independently. They share the host kernel and nothing else. `warren ls` shows what is installed, and `warren inspect` shows where an instance actually lives on disk. The same idea covers old and new versions. You can install a tool into two aliases and upgrade one without touching the other, which turns "I want to try the beta without breaking my setup" from a virtual machine exercise into a command. ## Three levers, no namespaces The mechanism is worth explaining because it is simpler than the outcome suggests. There are no kernel namespaces and no OverlayFS. Isolation comes from three moves. The first is intelligent rewriting. When you install a tool through a shell script, Warren intercepts the script and scans it for hardcoded paths like `/usr/local/bin` or `~/.config`, then rewrites them to point inside the instance's private directory under `~/.warren/instances/`. A tool that thinks it is writing to your home directory is writing to its own world. The second is environment injection. Warren generates a small wrapper script in `~/.local/bin`. When you run the alias, the wrapper overrides `$HOME`, `$XDG_CONFIG_HOME`, `$XDG_DATA_HOME`, and `$TMPDIR`. Graphical instances additionally keep the host display and session bus, so `$DISPLAY`, `$WAYLAND_DISPLAY`, `$DBUS_SESSION_BUS_ADDRESS`, and the runtime dir still point at the real session. That last detail is what keeps a wrapped app from breaking Wayland, notifications, and audio. The third is execution. The target boots up believing its home directory is real, and the wrapper stays out of the way after the environment is set. For apps with no installer to rewrite, there is app wrapping. Warren resolves the host launch command once, whether that is `flatpak run` or a path under `/usr/bin`, and bakes it into the per-instance launcher. Same sandbox, zero copies of the binary. ```svg gh (shared) home/ config/ home/ config/ home/ config/ ``` ## GUI apps, wrapped instead of reinstalled The extension that made Warren more useful than I expected was wrapping apps you already have. Prefixes like `flatpak:`, `snap:`, `apt:`, `dnf:`, `pacman:`, `app:`, and `desktop:` resolve to an installed binary, and each alias gets a private sandbox plus its own `.desktop` entry. ```bash warren dig flatpak:com.discordapp.Discord --as discord-work warren dig flatpak:com.discordapp.Discord --as discord-home warren dig apt:firefox --as firefox-work warren dig app:mytool --as mytool-gui --gui ``` Each instance appears in the app grid, keeps the host audio and session working, and launches detached. Because the host binary is reused, a second instance costs almost no disk, which is the opposite of what you get from running another copy of an Electron app. `warren ls` reports whether an instance is a CLI or a GUI, and `warren rm` removes the desktop entry along with the data. There is a real limit here, and it is worth stating. Wrapping gives an app its own data and login. It does not give it its own kernel, and it is not a security boundary against hostile software. Warren is explicit that it is not a container runtime, not a VM, and not a privilege escalation tool, and it will refuse to run as root. That honesty is what lets the rest of it stay small. ## Sessions, because desktops crash The feature I did not plan and now use constantly is session snapshots. A reboot, a crash, or a closed window with twelve tabs is a small disaster, and Warren can capture the running desktop and bring it back. ```bash warren session save warren session restore warren session restore --dry-run warren session prune ``` Snapshots are tiny TOML files under `~/.warren/sessions/`, with a retention limit that defaults to keeping the last five and deletes older ones on save. The dry-run flag prints the relaunch plan before touching anything, which is the difference between a useful feature and a terrifying one. ## The shape it ended up in Warren is a single Rust binary, rootless, with no daemons and under fifty milliseconds of startup overhead. It detects Bash, Zsh, Fish, or Nushell and configures the path itself. Configuration lives in `~/.warren/config.toml`, covering things like keeping the last five session snapshots, and standard environment variables such as `NO_COLOR` are respected. Installation is a one-liner that downloads a prebuilt binary when one exists for your architecture and falls back to `cargo install` when it does not. The design lesson is that the heavier tool is not always the more isolated one. When the actual requirement is "this process should not see my other account's data", a private home directory, a path rewrite, and an environment override get you there without a kernel feature, a daemon, or a container runtime. The rest of the container is solving problems this case does not have. The install script and the full command reference are in the repository above. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## The Boring Rat reached 1M reported users, then we sold it - URL: https://blog.swadhin.cv/blog/we-had-1m-users-got-acquired-and-i-still-think-we-made-the-wrong-call/ - Published: 2026-06-12T10:57:36.729Z - Updated: 2026-09-25T10:52:15.000Z - Author: Swadhin Biswas - Categories: Architecture, News - Excerpt: The Boring Rat was an umbrella for open-source projects, sites, and communities. We sold the assets in November 2025. I no longer have the dashboards, so this is the story I can stand behind. ### Content I delayed this post for months. An NDA keeps the buyer's name and transaction terms out of it. The harder part is explaining a project that was not one site. The Boring Rat was the public name for a collection of open-source projects, web properties, and communities. We sold the assets in November 2025. I no longer have access to the old analytics, source infrastructure, or community accounts, so I cannot produce a fresh audit of the historical numbers. I can describe what I owned, what happened, and what I would do differently. ## What The Boring Rat was The work was aimed at developers who wanted practical tools and useful conversations. People used the projects to find collaborators, look for work, share advice, and learn from engineers who had shipped real things. The collection included several separate surfaces, including DevSpace, Data Science Factor, CV Builder, a Blogspot publishing property, and Discord and Telegram communities. Some were products, some were publishing or community spaces, and some were open-source projects. They shared the Boring Rat identity and some of the same infrastructure. They were not separate companies, and they were not one website with several pages. By the time of the sale, the properties were reported at a combined total of one million users. I cannot break that number down by property or independently verify it today. The old dashboards are gone from my access, so I am not going to invent per-site counts. ## The two-person team The Boring Rat had a public side and a technical side. Imran was the public face and community lead. He ran the Discord and Telegram servers, handled the public conversations, and connected interested people with opportunities to donate. He also helped turn those connections into paid projects outside the community. Those projects gave us a small income while we were still students. Imran handled the introductions, community communication, and coordination. I handled the technical side and the research work: public APIs, workers, Postgres, Redis, Kafka ingestion, the analytics warehouse, and the Airflow jobs around them. You can find Imran on [LinkedIn](https://www.linkedin.com/in/mdimraan/). The money went toward research, a college fund, food, and university costs. It helped pay for our studies and keep the project running, but it did not turn The Boring Rat into a normal company with a steady payroll. We were still a small team carrying the technical work, the community work, and the rest of university life at the same time. Backend problems did not wait for a convenient hour. I was responsible for debugging them, often at 2am. We kept the infrastructure small by using free tiers and managed services where they made sense. The detailed measurements I recorded before the sale are in [the infrastructure write-up](/blog/running-1m-users-on-50-dollars-a-month/). I cannot reopen the old billing or analytics systems now, so I am treating those figures as historical records rather than current measurements. This is a historical Cloudflare dashboard from before the sale. It is not a live analytics view, and I cannot verify the underlying dashboard from here. ![Historical Cloudflare traffic dashboard for The Boring Rat](/images/boringrats-traffic-peak.webp) ## When keeping it running became unsustainable During the final year of my B.Sc., a traffic spike broke a pipeline I had built six months earlier as a stopgap. I was balancing exams and research deadlines while backend alerts reached me at 2am. I was working on two research projects at the time. One was Aurora ART, which is about getting models to admit uncertainty instead of answering confidently and wrongly. The other was privacy-preserving API infrastructure using homomorphic encryption. Both needed sustained attention, and The Boring Rat kept interrupting that work. I was the backend on call while studying for exams and working on research. The dashboard could show that the system was holding. It could not answer the harder question: how long the two of us could keep operating it that way. ## The sale A company contacted us about a possible merger. During a few calls, the discussion changed to acquisition. We talked about what the collection could become with more resources behind it. The formal proposal arrived by email with an Asset Purchase and Transfer Agreement attached. It covered the domains, infrastructure, bots, source code, and related assets. It also included a confidentiality clause. The NDA is why this post has no buyer name or transaction price. ![The acquisition agreement email from the buyer, with identifying details redacted](/images/boringrats-acquisition-email.webp) We said yes and signed in November 2025. The Boring Rat stopped being ours after the deal. The sale transferred the properties and infrastructure away from us. We no longer have the old dashboards, hosting accounts, or community administration access. The sites and channels changed after the acquisition, and there was no clean way to move a community that had formed around several separate spaces. Relief came first. The pressure lifted, I could sleep, and I could return to my degree and research without guilt. Signing made sense under the pressure we were under. It also ended services that people had used. I can defend the decision, even though the ending still bothers me. ## What I would do differently Looking back, I focused on whether the systems could survive traffic. I had no good answer for how the two of us would fund and operate several properties over time. I should have put those questions in the same review. I also should have treated the six-month-old stopgap as something to remove. By the time it broke, I was working around exams and research, so I debugged it and kept going. The name also needs context. The Boring Rat was an umbrella identity, not a claim that every property had the same product, audience, or ownership structure. A clearer portfolio page would have made that easier to explain to users and to a potential buyer. ## What I'm doing now After the sale, I went back to my B.Sc. and research. At the time of writing, my degree was almost done and the Aurora ART paper was on the way. I was also working on privacy-preserving API infrastructure using homomorphic encryption. I want to keep working close to production systems: APIs, data pipelines, reliability, and the cost of running them. For now, I am looking for a backend or data engineering role in Germany, the Netherlands, or Austria. I may try something like The Boring Rat again, with funding and enough time to make the operating model work. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## keybinding - URL: https://blog.swadhin.cv/blog/introducing-gvx-the-runtime-layer-python-never-had/ - Published: 2026-06-05T10:00:00.000Z - Updated: 2026-06-09T06:55:31.000Z - Author: Swadhin Biswas - Categories: Backend, DevOps, Performance, Architecture ### Content ## 🔑 Modes ```text Esc Normal mode i Insert a Insert after cursor v Visual V Visual (line) Ctrl+v Visual (block) R Replace mode : Command mode ```` ## 🧭 Core Movement (Vim Defaults) ```text h j k l Left / Down / Up / Right w / b Next / previous word e End of word 0 / ^ Start of line $ End of line gg / G Top / bottom of file Ctrl+d/u Half page down / up Ctrl+f/b Page down / up % Matching bracket ``` ## ✍️ Editing ```text i / I Insert before cursor / line a / A Insert after cursor / line o / O New line below / above r Replace one character R Replace mode cw Change word cc Change line ci" Change inside quotes ci( Change inside parentheses ``` ## 🗑️ Delete (Cut) ```text x Delete character dw Delete word dd Delete line d$ / D Delete to end of line diw Delete inner word ``` ## 📋 Copy / Paste ```text yy Yank line yw Yank word p / P Paste after / before cursor "+y Yank to system clipboard "+p Paste from system clipboard ``` ## 🔁 Undo / Redo ```text u Undo Ctrl+r Redo ``` ## 🔍 Search ```text /text Search forward ?text Search backward n / N Next / previous result * Search word under cursor :noh Clear highlights ``` ## 🪟 Windows (Splits) ```text v Vertical split h Horizontal split Ctrl+w h/j/k/l Move between splits Ctrl+w c Close split Ctrl+w o Close others ``` ## 📑 Buffers (NVChad) ```text Tab Next buffer Shift+Tab Previous buffer x Close buffer ``` ## 📂 Tabs ```text :tabnew New tab gt / gT Next / previous tab :tabclose Close tab ``` --- ## 💾 Files ```text :w Save :q Quit :wq / ZZ Save & quit :q! Force quit ``` ## 📄 NVChad Cheat Sheet (Built-in) ```text ch Open NVChad cheatsheet ``` ## 🔍 Telescope ```text ff Find files fb Find buffers fg Live grep fh Help tags fo Old files fc Commands ``` ## 🌲 NvimTree ```text Ctrl+n Toggle file tree Enter Open file a Create file d Delete r Rename x Cut c Copy p Paste ``` ## 🧠 LSP (Built-in) ```text gd Go to definition gD Go to declaration gi Go to implementation gr References K Hover documentation rn Rename symbol ca Code action lf Format file ``` ## ✨ Autocomplete (nvim-cmp) ```text Ctrl+Space Trigger completion Ctrl+n / p Next / previous item Enter Confirm completion Tab Next item / snippet jump Shift+Tab Previous item ``` ## 🌱 GitSigns ```text ]c / [c Next / previous hunk hs Stage hunk hr Reset hunk hp Preview hunk hb Blame line ``` ## 🖥 Terminal (NVChad) ```text Alt+h Horizontal terminal Alt+v Vertical terminal Alt+i Floating terminal h Horizontal terminal v Vertical terminal ``` ## 📦 Lazy.nvim (Plugin Manager) ```text :Lazy Open plugin manager ``` ## ⚡ Power Tips (NVChad) ```text ; Enter command mode (NVChad default) . Repeat last command J Join lines >> / << Indent line ``` --- ## I Got Tired of GitHub Being Down, So I Built My Own Git Platform - URL: https://blog.swadhin.cv/blog/i-got-tired-of-github-being-down-so-i-built-my-own-git-platform/ - Published: 2026-05-22T09:02:22.444Z - Updated: 2026-06-05T16:07:08.000Z - Author: Swadhin Biswas - Categories: System Design, Backend, Architecture, Programming, Tutorials, News - Excerpt: OpenCodeHub is an open-source, self-hosted GitHub alternative built with Astro, TypeScript, and Drizzle ORM. Features SSH, stacked PRs, CI/CD pipelines, and AI code review — on your own server. ### Content > *"GitHub is down again."* > That one Slack message. At 2 AM. Right before a production deploy. > That was the last straw. --- ## The Incident That Started Everything It was a regular Wednesday night. I had a hotfix ready. CI was green locally. All I needed was to push, trigger the pipeline, and ship. Then GitHub decided it didn't exist anymore. No push. No pull. No Actions. Nothing. Just a sad little status page telling me "We're investigating an incident affecting Git operations." Cool. Super helpful. I'll just sit here and watch my deploy window close. I've been a GitHub user for years. I love it, genuinely. But that night, staring at that status page, I kept thinking — **why am I this dependent on a single platform I have zero control over?** So I did what any sleep-deprived developer does at 2 AM. I opened a new terminal and typed `mkdir OpencodeHub`. --- ## What Is OpenCodeHub? **OpenCodeHub** is a fully self-hosted Git platform I built from scratch. Think GitHub — but running on *your* server, under *your* control, with *your* rules. No more status pages. No more downtime surprises. No more "we're investigating." The tagline I eventually landed on: > *"A modern, self-hosted Git platform for teams that want speed, control, > and clean workflows."* But honestly? The real tagline is: *"I was angry and I had a weekend."* --- ## The Tech Stack (Because You're Going to Ask) I didn't want to reinvent every wheel. I wanted to build something I'd actually enjoy maintaining. So I made some deliberate choices: | Layer | Choice | |-------------|------------------------------------------------| | Framework | **Astro 4.x** (SSR, Node standalone) | | UI | **React 18** + Tailwind CSS + Radix UI | | Database | **Drizzle ORM** (PostgreSQL, SQLite, Turso) | | Auth | **JWT** + bcryptjs + TOTP + OAuth (arctic) | | Git | Native git CLI + simple-git + isomorphic-git | | SSH Server | **ssh2** library | | CI/CD | **Dockerode** (Docker API) | | Queue | **BullMQ** + Redis | | CLI | Commander.js + Inquirer | **Why Astro?** Because I wanted SSR without drowning in a React SPA for everything. Astro lets me drop React components exactly where I need them. It's been a genuinely pleasant choice — fast builds, clean routing. **Why Drizzle?** Because Prisma was too opinionated for what I needed and raw SQL makes me sad at 3 AM. Drizzle is just TypeScript all the way down. I can switch between PostgreSQL for production, SQLite for local dev, and Turso for edge deployments. That flexibility mattered. --- ## Features I Actually Shipped This wasn't a weekend toy that I abandoned. Here's what's actually working: ### Core Git Platform - **HTTP + SSH git push/pull** — yes, real SSH on port 2222, not just HTTPS - **Pull Requests** — comments, reviews, drafts, approvals, suggested changes - **Issues** — labels, milestones, project boards - **Wiki** — repository wiki with full revision history - **Organizations** — teams, collaborators, granular repository settings - **Branch Protection** — required reviews, status checks, push restrictions ### The Thing I'm Most Proud Of: Stacked PRs If you've ever used Graphite, you know the power of stacked PRs. Instead of one monolithic 3,000-line PR that nobody wants to review, you break your work into a clean stack of focused, reviewable pieces. I built this into OpenCodeHub natively — both in the web UI and the CLI. ```bash # Create a stack och stack create feature/auth-step-1 # Submit the whole stack for review och stack submit # Keep it in sync as you iterate och stack sync ``` This alone was worth building the whole thing. ### CI/CD Pipelines I made the pipelines **GitHub Actions-compatible**. Same YAML syntax. Same structure. The idea was: if you're migrating from GitHub, your workflows should just... work. No rewriting everything from scratch. The runner uses Docker via Dockerode under the hood. Each job gets its own container. Clean, isolated, reproducible. ### AI Code Review I added AI-powered code review that runs before human reviewers even see the PR. It catches the obvious stuff — security issues, logic bugs, style inconsistencies — so human review can focus on architecture and intent. ### The Merge Queue Stack-aware merge queue with speculative builds and priority lanes. If you have a stack of 5 PRs, the queue knows about their dependencies and builds them intelligently. No more merge conflicts from PRs stepping on each other. ### 140+ REST API Routes + GraphQL ```bash # Create a repo curl -X POST http://localhost:4321/api/repos \ -H "Authorization: Bearer " \ -d '{"name":"my-project","visibility":"public"}' # List pull requests curl http://localhost:4321/api/repos/alice/my-project/pulls \ -H "Authorization: Bearer " ``` There's also a full GraphQL endpoint and an auto-generated OpenAPI spec. Because I hate undocumented APIs as much as the next person. --- ## The Architecture ``` Clients (Browser / Git CLI / och CLI) │ ▼ OpenCodeHub Platform (Astro SSR + React) ├── Web UI ├── REST API (140+ routes) ├── GraphQL Endpoint ├── Git HTTP Server └── SSH Git Server (port 2222) │ ▼ Persistence Layer ├── PostgreSQL / SQLite / Turso (Drizzle ORM) ├── Redis (sessions, queues, caching) └── Pluggable Storage (S3, GCS, Azure, local…) ``` Four separate runtime processes keep things clean: | Process | Command | Purpose | |----------|--------------------------|-------------------------| | Main App | `npm run dev` | Web UI + API + Git HTTP | | SSH Git | `npm run git:start` | SSH git push/pull | | Worker | `npm run worker:start` | Background jobs | | Runner | `npm run runner:start` | CI/CD pipeline execution| --- ## Getting It Running (Seriously, 5 Minutes) ```bash # Clone it git clone https://github.com/swadhinbiswas/OpencodeHub.git cd OpencodeHub # Configure cp .env.example .env # Edit .env with your settings # Start everything docker-compose up -d # Create your admin user docker-compose exec app bun run scripts/seed-admin.ts # Open it open http://localhost:4321 ``` That's it. You now have your own Git platform running locally. For production you'll want PostgreSQL over SQLite, Redis, HTTPS via Nginx or Caddy, and external storage like S3 or MinIO. The deployment guide covers all of that, but the bones are solid out of the box. --- ## The CLI (`och`) I published the companion CLI as `opencodehub-cli` on npm: ```bash npm install -g opencodehub-cli # Authenticate against your instance och auth login --url http://your-server.com # The interactive cockpit — my personal favorite och focus ``` 20+ command groups covering stacks, merge queues, repos, issues, and more. Because clicking through a UI when you're deep in a terminal session is a crime. --- ## What I Learned Building This **1. SSH is not that scary.** I put off implementing SSH git for weeks because I thought it would be brutal. The `ssh2` library made it surprisingly manageable. The tricky part was git's internal protocol, not SSH itself. **2. Drizzle ORM is criminally underrated.** Type-safe queries, multiple database backends, migrations that don't feel like a punishment. I'm a convert. **3. BullMQ + Redis is the right answer for background jobs.** I tried doing things without a proper queue first. That was a mistake. BullMQ is robust and the developer experience is clean. **4. Spec compatibility matters more than I thought.** Making the CI pipelines GitHub Actions-compatible was extra work upfront, but it means people can actually migrate without a complete rewrite. That was the right call. **5. Storage adapters deserve abstraction from day one.** I built the abstract `StorageAdapter` pattern early and it's paid off. I support 8+ backends — S3, GCS, Azure, Google Drive, OneDrive, Dropbox, Rclone, and local — all behind the same interface. --- ## Is It Production Ready? Mostly. I have 271 commits, a proper test suite (Vitest + Playwright), load tests, a `PRODUCTION_READINESS.md` checklist, and a CircleCI pipeline. There are 67 open issues — mostly planned features and polish items, not fires. Would I run my team's code on it today? Yes, with proper backups and a reverse proxy in front. Would I run a Fortune 500's engineering department on it? Give me another six months. --- ## Why Not Just Use Gitea / Forgejo / GitLab? Fair question. I tried them. They're good. But they didn't have native stacked PRs, and the CI/CD story always felt bolted on. I also wanted to build something in a modern TypeScript stack end-to-end, using tools I actually enjoy. Sometimes you build a thing not just because it doesn't exist, but because *you* building it teaches you things no existing tool can. --- ## Try It / Contribute The repo is open source under MIT: **→ [github.com/swadhinbiswas/OpencodeHub](https://github.com/swadhinbiswas/OpencodeHub)** Docs live at **[docs.opencodehub.space](https://docs.opencodehub.space)** If you're tired of GitHub downtime, if you have data residency requirements, if you want stacked PRs without paying for Graphite, or if you just like running your own stuff — give it a spin. And if GitHub goes down while you're reading this... well. You know what to do. --- *Built with TypeScript, Astro, frustration, and an embarrassing amount of coffee. PRs welcome.* **— Swadhin** --- *Tags: `#selfhosted` `#git` `#opensource` `#devtools` `#typescript` `#astro` `#github-alternative` `#stacked-prs`* --- ## A local-first AI coding CLI - URL: https://blog.swadhin.cv/blog/a-local-first-ai-coding-cli/ - Published: 2026-05-09T10:00:00.000Z - Updated: 2026-09-23T12:25:18.000Z - Author: Swadhin Biswas - Categories: Machine Learning, Backend, Programming - Excerpt: Provider-independent, zero telemetry, and it writes your session to a local JSONL file. The constraints came first and the features followed. ### Content There is a pattern to AI coding assistants. You install one, log in, and over the first week you notice three things. The provider is fixed, so the model you actually want is not available. The telemetry is on, and turning it off is somewhere between a setting and a request. The commands you use most are implemented in a fork, which means they break on the next upstream merge. Each of those is a small tax, and together they add up to a tool that owns your workflow more than you do. Mervelas came from deciding that the constraints would be the design, not the marketing. Repo: [swadhinbiswas/Mervelas](https://github.com/swadhinbiswas/Mervelas) ## Provider independence is the first constraint The assistant supports OpenAI, OpenRouter, NVIDIA NIM, Qwen, DeepSeek, and locally hosted models out of the box, and switching is configuration rather than a migration. That list is not a feature checklist. It is a statement that the model you want changes every few weeks, and a tool that hardcodes a provider turns every model upgrade into work. For headless setups and CI, the same choice is expressible in the environment: ```bash MERVELAS_API_PROVIDER=openai OPENAI_API_KEY=your_key_here OPENAI_BASE_URL=https://api.openai.com/v1 ``` The `/login` and `/config` commands do the same thing interactively. What matters is that the provider is a value, not a fork. ## The commands belong to the event loop The commands people miss when they switch tools are the ones that feel native: a way to see the context window, a way to create a specialized agent, a way to reach an MCP server. Mervelas implements those directly against the local event loop instead of patching them in. `/context` shows exact token usage and the shape of the window, which turns a vague feeling of running out of room into a number. `/agents` creates and switches between local coding agents. `/mcp` wires in Model Context Protocol servers so the model can reach other tools. `/status` reports local development state and resource use, and `/config` manages providers and models. None of these are exotic. The point is that they are native, so they keep working. ## Lightweight is an architectural decision The CLI is compiled with Bun and rendered through a custom React Ink abstraction. That abstraction is enforced in the code review rules, and the reason is instructive: Mervelas does not import Ink directly from npm. Layout primitives route through a local `src/ink.ts`, so the rendering layer is something the project controls and can change without chasing a dependency. The rule that shaped the runtime most is about startup. Nothing is allowed to instantiate blocking state or read files at module load. Tools and execute loops use a delayed dynamic import, so the footprint stays idle until something is actually invoked. For an assistant that lives in a terminal all day, idle cost is not a rounding error. A background process peeking at the CPU between prompts is the difference between a tool you keep open and one you close. ```svg ``` ## Where the session lives Conversational history is written locally to `~/.mervelas/projects/`, one file per project, as JSONL. Nothing is uploaded as telemetry. That single decision changes how the tool can be used. You can point it at a private repository without wondering where the prompts end up, and the session files are ordinary text you can read, diff, grep, or delete. There is no server component that needs to stay available for your history to exist. Zero telemetry is easy to promise and easy to quietly break, so it is worth being concrete about what it means here. The session store is local, the provider calls go straight from your machine to the provider you configured, and there is no first-party backend in between that observes either. ## Agents, MCP, and the context window The commands that felt least like table stakes turned out to shape the architecture most. `/mcp` connects Model Context Protocol servers, which lets the assistant reach tools and data outside the terminal without baking those integrations into the CLI. That matters for a local-first tool, because the number of possible integrations is unbounded and the number the maintainer wants to own is not. MCP is the seam that keeps the tool small while leaving it extensible. `/agents` handles something different. A single assistant with one system prompt is asked to be a careful reviewer, a fast prototyper, and a documentation writer, and it does none of them especially well. Named local agents let the same CLI hold several configured personas, each with its own instructions, and switch between them without restart. It is a small amount of state and a large change in how the tool is used. `/context` is the one I open most. AI coding sessions fail at the boundary of the window, and a tool that will not tell you how close you are to it turns every long session into a guess. Seeing the token count and the shape of the remaining room changes the decision about when to start a fresh session, which is exactly the kind of quiet, unglamorous affordance a daily driver needs. ## The honest state of it Mervelas is in active development and not yet published to npm. Today you clone the repository and build it with Bun, which for now is the price of the privacy model. Type checking runs against strict ES2023 through `tsc --noEmit`, and the contribution rules exist to keep the architecture from regressing toward the thing it was built to avoid. There is a trade-off worth naming. Building your own assistant means you maintain it, and an established tool will always have more integrations. What a local-first tool gives back is that the constraints are yours. If the provider list is wrong for you, you change a value. If the session format is wrong, you change a file. That is a different kind of product from the one that treats your workflow as the integration surface. The build steps and the agent configuration are in the repository above. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## A grammar checker that never phones home - URL: https://blog.swadhin.cv/blog/a-grammar-checker-that-never-phones-home/ - Published: 2026-03-29T10:00:00.000Z - Updated: 2026-09-23T12:25:17.000Z - Author: Swadhin Biswas - Categories: Machine Learning, Backend, Programming - Excerpt: A 156,000-word dictionary that runs in the browser, a router that only reaches for a model when you bring your own key, and no database on the other side. ### Content The business model of a writing assistant requires reading what you write. That is not a bug in the design, it is the design. Your draft is the input, a model marks it up, and the value comes back. The consequence is that every email, every contract clause, and every half-finished thought passes through someone else's servers, and you accept it because the alternative is worse writing. OpenGrammar started from the observation that a large share of the useful checking does not need a model at all. Repo: [swadhinbiswas/opengrammar](https://github.com/swadhinbiswas/opengrammar) · Site: [opengrammer.eu.cc](https://opengrammer.eu.cc) ## Two engines, and knowing which one to use The heart of the project is a dual-engine design. A local engine runs a regular-expression rule set against a 156,000-word offline dictionary entirely in the browser. It catches misspellings, passive voice, and weak phrasing with no network call, no latency, and nothing to bill. A separate, optional engine routes to a language model for the things that genuinely need context: rewriting a sentence for tone, or fixing a subtle agreement error that depends on the whole paragraph. The interesting design decision is the seam between them. The AI is synchronized with the local checker, which means it never spends a token re-checking a typo the dictionary already caught. That sounds like a small optimization and it is actually the thing that makes the dual-engine approach feel coherent instead of like two products stapled together. Each engine gets the work it is best at. The dictionary handles the mechanical layer for free, and the model handles the layer where a generic rule cannot help. ```svg fixed ``` ## Privacy as a property of the architecture Most privacy claims are a policy about data the service already collected. OpenGrammar tries to make the claim structural instead. There is no database. The API key you paste for your own model stays in browser storage and never reaches the backend. Text that does go for AI correction passes through stateless edge functions and is not retained, because there is nowhere to retain it. The public edge deployments on Cloudflare, Vercel, and Netlify exist so you can use them without hosting anything, and the self-hosted path exists so you do not have to trust even those. Bring your own key is the piece that makes the economics work. You can point the router at OpenAI, Groq, Together, OpenRouter, or a local model through Ollama, and you pay only for what you use. The project is not trying to operate the model. It is trying to do the cheap layer itself and hand off the expensive layer without taking a cut. ## The shape of the backend The backend is a single service with a small REST surface, which is what lets it run almost anywhere. | Method | Endpoint | What it does | |---|---|---| | `GET` | `/` | status dashboard and engine version | | `GET` | `/health` | health check | | `POST` | `/analyze` | grammar analysis | | `POST` | `/autocomplete` | context-aware completion | | `GET` | `/providers` | which providers are configured | It listens on port 8787 by default, reads a `PORT` and provider keys from the environment, and ships as a multi-architecture Docker image. Because it runs on Node, it also runs where Node runs, which is how it ends up on an old laptop, a Raspberry Pi, or an Android phone through Termux. The extension points at a server URL, so switching from a public edge endpoint to one running on your desk is a settings change. ## The features that go past spellcheck Two features are worth calling out because they show where the product is aiming. Smart context awareness detects whether you are writing a casual post, a technical document, or a formal email and scales its strictness to match. A rule that should fire on a contract should not fire on a Slack message, and hardcoding one strictness level is what makes grammar tools annoying. Alongside it, a dynamic writing score rates text from 0 to 100 across correctness, readability, engagement, and sentence delivery, which turns a list of complaints into something closer to feedback. The extension injects into the editors people actually use: Gmail, Google Docs, Notion, and Reddit. That integration work is unglamorous and it is the difference between a demo and a tool someone leaves installed. ## The local engine is not a toy It would be easy to treat the offline checker as the consolation prize and the model as the real product. The rule set is what earns its keep. A 156,000-word dictionary catches the misspellings that make writing look careless, and the regular-expression rules catch the structural habits that a spellchecker ignores: passive constructions, hedging, weak verbs, sentences that say nothing. Each rule is a documented pattern in the repository rather than a black box, which means a contributor who knows grammar but not machine learning can improve the product by editing a file. That openness is the reason the local layer can be genuinely competitive rather than a fallback. If a rule is wrong, you can see why and fix it, and the fix does not require a training run or a release from someone else. For a project aimed at unseating a subscription product, the ability to accept a grammar fix from a language enthusiast is a feature, not a nice-to-have. ## What I took from it Grammar checking is a good test case for a broader argument. The default assumption now is that any language task needs a hosted model, and the privacy-preserving version is assumed to be worse. OpenGrammar makes the case that the layered version is often better, because the majority of the value is deterministic pattern matching that is faster, free, and private, and the model is the upgrade rather than the baseline. Getting the seam right between the two is the whole product. It is Apache 2.0 licensed, and the repository holds the engine, the server, and the extension. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Running 1M users on $50 a month: the infrastructure behind Boringrats - URL: https://blog.swadhin.cv/blog/running-1m-users-on-50-dollars-a-month/ - Published: 2026-03-15T10:00:00.000Z - Updated: 2026-09-23T11:32:23.000Z - Author: Swadhin Biswas - Categories: Data Engineering, Backend, DevOps, Performance, Architecture - Excerpt: Boringrats served a million users on donations, with a fifty-dollar monthly budget and a bill that landed near thirty-five. Here is the architecture, the numbers from the busiest day, and what it cost outside the invoice. ### Content People do not believe the fifty dollars. A million users sounds like a number that needs a platform team and a cloud bill in the thousands. Boringrats ran on donations. I set the infrastructure budget at $50 a month, and most months the bill came in closer to $35. Boringrats was a place for small open source developers to find collaborators, find work, and get advice from people who had actually shipped something. It reached a million users. At peak, around 200,000 people were active on a normal day. Two of us ran it. My co-founder handled community, fundraising, and the public face. I owned the backend and the data layer. After a year of it I could tell you where every request went and why the origin rarely had to care. This is the architecture that held a million users on a bill under fifty dollars, the numbers from the busiest day I measured, and the parts that nearly came apart. ## What the bill actually looked like The bill stayed small because most of what ran had a free tier or a usage-based price. A normal month looked roughly like this. | Line | What it was | Cost | | --- | --- | --- | | Origin VPS (Singapore) | one small box for the API and the workers | about $15 / month | | PostgreSQL | managed, Hobbyist plan | from $12 / month ($0.02 / hour) | | Redis | Upstash, pay as you go | about $3 / month ($0.20 per 100K commands) | | Kafka | Aiven free tier | $0 | | Cloudflare | subscription | $5 / month | | **Total** | | **about $35 / month** | Cloudflare did the expensive part: TLS, the WAF, and the cache that answered 78.36 percent of requests. The origin was one small Singapore VPS. Postgres, Redis, and Kafka were managed, so I was not the one patching a database at 2am. Airflow ran on the VPS and kicked off the scheduled jobs. Managed services cost more per unit than running the same software myself. I paid for them anyway because a two-person project has no on-call rotation, and automated backups on a managed database are cheaper than a week of downtime. The hours I saved went into the product and the pipelines. ## The edge does the work The most important number on the entire dashboard was the cache hit rate. Here is one 24-hour window from September 2025, during the busiest stretch we ever had: ![Cloudflare traffic overview for Boringrats showing 2.01M requests and 685.42K visits in 24 hours](/images/boringrats-traffic-peak.webp) 2.01 million requests and 685,420 visits in a single day, with 9.83 GB of bandwidth served. The busiest hour hit 102,341 requests at 21:45. The United States sent the most traffic at 428,300 requests, the homepage carried 30.4 percent of the total, and 46.3 percent of all requests were for HTML. 78.36 percent of those requests never reached the origin. Cloudflare answered them from cache close to the user, and the VPS only saw the remaining fifth. On the day Boringrats handled more traffic than it ever had, the origin was mostly idle. ```chart { "type": "doughnut", "data": { "labels": ["Served from Cloudflare cache", "Reached the origin"], "datasets": [{ "data": [78.36, 21.64], "backgroundColor": ["#89b4fa", "#45475a"], "borderWidth": 0 }] }, "options": { "responsive": true, "plugins": { "legend": { "position": "bottom" } } } } ``` Every percentage point of cache hit rate is an entire class of work the origin never has to do. Pushing that number higher was worth more than any instance upgrade I could have bought. ## The request path ```mermaid flowchart LR U[Visitors] -->|HTTPS| CF{Cloudflare edge} CF -->|cache hit 78.36 percent| U CF -->|cache miss| O[Origin VPS] O --> DB[(Postgres)] O --> R[(Redis hot keys)] O --> S[(Object storage)] ``` A request lands at Cloudflare first. DNS and TLS terminate there, the WAF drops the obvious junk, and the cache decides whether this response already exists. Most of the time it does, and the visitor gets bytes from a data center near them. When it does not, Cloudflare goes to the origin, the origin builds the response from Postgres or Redis, and the edge keeps a copy so the next thousand people do not repeat the work. ## The architecture ```svg REQUEST PATH Visitors 1M users Cloudflare edge DNS / TLS / WAF CDN cache 78.36 percent Origin VPS Docker: API + workers hit miss 21.64 percent Postgres Redis Object storage DATA PLANE Kafka Ingestion workers dedupe + rollups Warehouse Airflow ``` ## The rules that kept the bill flat **Cache before you scale.** When a page is slow, check whether the response should have already existed before you resize anything. Most content on a read-heavy site is identical for everyone, and identical work is waste. **Keep the origin replaceable.** Nothing important lived only on that VPS. The database, the object storage, and the repositories were elsewhere. If the box died I could rebuild it from a script, which meant I never paid for a second one "just in case". **Strip and compress.** HTML went out compressed, images were sized before they were uploaded, and the payloads that reached a phone were as small as I could make them. Smaller payloads kept the bandwidth line low and the pages fast. **Queue the writes.** A comment or a reaction did not have to finish inside the request. Push it to a queue, return quickly, let a worker do the slow part. The visitor waits for almost nothing, and the origin survives a spike. **Back up, then prove the backup.** Dumps and media went to object storage on a schedule, and I restored them into a scratch database often enough to trust them. **Watch the tail.** The average was always calm. The p95 told me when something was actually wrong, and it usually showed up before a user complained. ## What the bill did not cover The invoice was the small part. The rest was time and sleep, and it eventually ran out. A traffic spike broke a pipeline I had built six months earlier as a stopgap, and it broke during my final year, with research deadlines and exams already on the calendar. Both of us were unpaid. The platform was sold in November 2025 and shut down afterwards. I wrote about that separately in [the acquisition post](/blog/we-had-1m-users-got-acquired-and-i-still-think-we-made-the-wrong-call/), because the numbers here only tell half of it. ## What I would tell you If you are building something that people keep showing up to, the cheap architecture is usually the correct one. Cache at the edge, keep the stateful parts boring and backed up, and treat every service you add as a future page at 2am. The expensive resource on a project like this is attention, and the architecture should send it to the product instead of the plumbing. The budget was fifty dollars a month and the bill came in under it, mostly because the expensive work happened at the edge. I would keep most of that design even without the constraint. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## Versioned memory for AI agents, seven languages deep - URL: https://blog.swadhin.cv/blog/versioned-memory-for-ai-agents/ - Published: 2026-02-24T10:00:00.000Z - Updated: 2026-09-23T12:25:15.000Z - Author: Swadhin Biswas - Categories: Machine Learning, Data Engineering, Architecture, Programming - Excerpt: An agent that runs long enough will forget what it decided. I implemented the GCC framework, which treats agent memory like Git, in seven languages against one on-disk format. ### Content The failure mode of a long-running agent is not that it cannot reason. It is that it forgets why it reasoned the way it did. An hour of work fills the context window, the oldest tokens fall off the end, and the agent starts contradicting a decision it made earlier as if it had never happened. The usual answers are to stuff the whole history back in, to summarize it lossily, or to bolt on a vector store that retrieves fragments with no sense of order. Each one is expensive, incomplete, or both. A paper I found while working through this argues that the problem is not new, and that version control already solved it. The Git Context Controller, or GCC, applies Git's branching model to an agent's memory. Repo: [swadhinbiswas/contexa](https://github.com/swadhinbiswas/contexa) · Paper: [arXiv 2508.00031](https://arxiv.org/abs/2508.00031) The research and the benchmark results belong to that paper, by Wu and others. My contribution is Contexa, an implementation of the framework that runs in seven languages against a single on-disk format. That constraint, one format across seven runtimes, turned out to be most of the engineering. ## The idea in one diagram GCC treats an agent's working history the way Git treats a repository. ```svg main branch: experiment ``` Every step the agent takes is an Observation, Thought, Action record, which is the working directory. When a piece of work is done, it commits: a milestone summary that compresses the older OTA steps away. When it wants to try two approaches, it branches, so an experiment cannot corrupt the main line. When an experiment works, it merges. And when it needs to think again, it asks for context at a resolution of K commits. The API is small enough to hold in your head. ```python from contexa import GCCWorkspace ws = GCCWorkspace("/path/to/project") ws.init("Build a REST API with user auth") ws.log_ota("saw empty dir", "scaffold first", "create_files()") ws.log_ota("files created", "implement user model", "write_code('models.py')") ws.commit("Project scaffold and User model complete") ws.branch("auth-jwt", "Explore JWT authentication") ws.log_ota("JWT docs reviewed", "stateless, good for APIs", "implement_jwt()") ws.commit("JWT auth middleware implemented") ws.merge("auth-jwt") ctx = ws.context(k=1) ``` That `context(k=1)` call returns a formatted summary ready to inject into a prompt: the roadmap, the last commit, and the current OTA log. The paper's ablation is the counterintuitive part. K=1, the most recent commit only, outperforms giving the agent more history. Compression is not a compromise being forced by a small window. It is a better input. ## The part I actually built Implementing a single library is routine. Implementing the same library in Python, TypeScript, Rust, Go, Zig, Lua, and Elixir, all producing and reading the same `.GCC/` directory, is where the design pressure lives. ``` .GCC/ main.md # global roadmap branches/ main/ commit.md # milestone summaries log.md # fine-grained OTA traces metadata.yaml # intent, status, provenance experiment/ commit.md log.md metadata.yaml ``` The format is deliberately human-readable, Markdown and YAML on disk. You can open an agent's memory in your editor and read what it decided. That choice made cross-language parity possible, because the contract is text rather than a binary protocol, and it made debugging possible, because a wrong summary is a line you can point at. Holding seven implementations to one format is a discipline problem more than a technical one. Each language has its own idioms for files, time, and structured data, and every one of them will happily drift by a field or a timestamp format if you let it. The seven packages are independent, with their own build tooling and tests, and the only thing that truly binds them is that the directory one language writes is the directory another can extend. I added a place for the metadata for exactly this reason: intent, status, and provenance need to survive the trip, or the memory stops being portable. The models are small on purpose. An OTA record has a step, a timestamp, an observation, a thought, and an action. A commit record carries the branch, its purpose, the previous progress summary, and this commit's contribution. A branch has a name, a purpose, where it came from, and where it merged. Keeping the schema that small is what lets seven languages agree. ## Why the branching model matters The interesting claim from the paper is not that summarization helps. It is that structure helps. The ablation walks from 69.1 percent with the roadmap and commits, to 75.3 with logs and context, to 77.8 with metadata, and to 80.2 with branch and merge on SWE-Bench Verified using Claude 4 Sonnet. The paper also reports 83.4 percent on BrowseComp-Plus with GPT-5, against 26 existing open and commercial agent systems. To be precise about what those numbers are and are not: they come from the paper that defines GCC, not from a benchmark I ran on Contexa. What I can speak to is the implementation. The last column of that ablation is the one that stuck with me, because branch and merge is the part that maps least obviously to memory and most obviously to how engineers already work. When an agent tries two approaches, the useful record is not which one won. It is that there were two, what each assumed, and which one the main line adopted. There is a real cost to this approach. It adds tool calls and structure to an agent loop that was simpler before, and the paper notes that GCC agents spend more compute while ending up more cost-efficient. If you are building something that runs for a few turns, this is overhead. If you are building something that works on a task for an hour and needs to remember the first decision when it reaches the last, structured memory with a real branching model is worth the tokens. ## Where it lives Contexa is published across PyPI, npm, crates.io, pkg.go.dev, Hex, and LuaRocks, with the Zig package built from the repository. All seven read and write the same layout, so a workspace created by the Python package can be extended by the Rust one. The original research citation is in the repository, and the framework belongs to its authors. The lesson I keep taking from it is that memory is a data-modelling problem wearing an AI costume. The moment you stop treating context as a buffer to fill and start treating it as a structure to query, the design questions become ones that version control answered years ago. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). --- ## ART: a modular transformer that abstains instead of guessing - URL: https://blog.swadhin.cv/blog/art-a-modular-transformer-that-abstains-instead-of-guessing/ - Published: 2026-01-18T10:00:00.000Z - Updated: 2026-09-21T13:08:45.000Z - Author: Swadhin Biswas - Categories: AI, Machine Learning, Architecture - Excerpt: ART splits reasoning into six stages with explicit uncertainty and refuses when evidence runs out. GSM8K 55.6 percent at 0.29x cost in our runs. ### Content I started [github.com/swadhinbiswas/Aurora](https://github.com/swadhinbiswas/Aurora) on 14 January 2026 with Tuhin Sheikh and Md Shahriar Shakil at Daffodil International University in Dhaka. I had spent enough time watching language models answer in the same calm tone when right and when made up. For casual chat that habit is harmless. For medical, legal, or financial questions a confident wrong answer does more damage than no answer. I wanted a model that could not reach the user without passing a quality gate first. The repo holds `art-transformer` version 0.1.0, MIT licensed, Python package name `art-transformer`. It is a PyTorch library for language models that carry uncertainty as an explicit output. The paper draft lives in `paper/paper.md` and `paper/full_paper.tex`, full result tables live in `result/table1.json` through `result/table15.json`, and figures regenerate from `python -m art.benchmark.analysis --input result`. Everything below traces to those files. ## What we built ART splits a reasoning pass into six stages: ``` Perceive to Reason to Plan to Execute to Verify to Answer or abstain ``` The reasoning core reads the question and produces three separate signals: what it understands (R), what it wants to do next (C), and how unsure it is (U). A deterministic router turns those signals into an acyclic task graph, drops any sub-task whose uncertainty crosses a threshold, and dispatches the rest to stateless experts. Every expert result passes through a verification anchor before it counts. When too few results survive, the system says so explicitly. I keep coming back to a hospital analogy. I would not want my surgeon, pharmacist, and radiologist to share one brain. I want specialists, with someone checking the work before anything reaches the patient. ```mermaid flowchart TD BPL[Binary perception layer] --> CTC[Cognitive core R C U] CTC --> D3R[Dynamic DAG router] D3R --> EX[Stateless experts] EX --> CRA[Reality anchor accept reject abstain] CRA --> SYN[Synthesis head] CTC -. U channel .-> D3R CTC -. U channel .-> CRA SYN --> OUT[Answer] SYN --> ABS[Abstain] ``` ## Story of one forward pass A dense model reads a question and starts writing at once. Understanding, planning, computing, and checking tangle into one stream of hidden states. ART walks the question through stations, and nothing reaches the user until the last station signs off. The journey starts at the Binary Perception Layer in `art/modules/bpl.py`. Tokenisation happens offline. Text pre-compiles into fixed width 32-bit records that memory map at training time, so the runtime loop reads contiguous integer arrays instead of parsing strings. This removes the CPU bound data bottleneck that throttles accelerators. The trade is less vocabulary flexibility than byte level or unigram schemes, and the repo docs state that trade plainly. Next comes the Cognitive Transformer Core in `art/modules/ctc.py`. It has no decoder and no vocabulary softmax. Its final states project into three disjoint channels: reasoning representations R, control signals C, and a sigmoid bounded uncertainty channel U, trained jointly with a lightweight auxiliary correctness objective. Confidence is learned as a dedicated feature here. I did this because generation softmaxes miscalibrate under shift and quantization, and I did not trust them to say when to stop. Control passes to the Dynamic DAG Router in `art/modules/d3r.py`. Five control primitives select by deterministic argmax against projection vectors frozen after training: EXECUTE, COMPOSE, BRANCH, AGGREGATE, VERIFY. Routing carries no sampling variance. The router assembles acyclic graphs with hard caps on depth and width, and it suppresses any sub-task whose uncertainty exceeds threshold. Acyclicity is enforced on insertion, so the recursive runaway loops I have seen in agent frameworks cannot start here. Each surviving node dispatches through an ExpertRegistry in `art/modules/experts/` to stateless domain experts for math, code, retrieval, and passthrough. Experts share no memory and cannot call one another. They return structured results only, so cross talk between sub-tasks is impossible by construction. The math expert routes parseable expressions through SymPy for exact symbolic evaluation and falls back to a neural stand in otherwise. Before any result counts, the Context and Reality Anchor in `art/modules/cra.py` checks it against R and U and returns ACCEPT, REJECT, or ABSTAIN. Finally the Synthesis Head in `art/modules/syn.py` aggregates only accepted results through confidence weighted attention over verified candidates. It produces the final answer or an explicit abstention when too little survives. For higher stakes I run Multi-ART. It runs M independent instances over the same input and merges verified outputs through uncertainty weighted voting, without shared weights or joint training. Disagreement triggers abstention rather than forced consensus. Our configs use M equal to 3. Every call returns an `ARTOutput` dataclass with answer, abstained flag, calibrated confidence, pooled uncertainty, and graph diagnostics: ```python import torch from art import ART model = ART(vocab_size=50257, hidden_dim=768, num_layers=12, num_heads=12) out = model(input_ids=torch.randint(0, 50257, (2, 128))) print(out.abstained) # True when evidence was insufficient print(out.confidence) # calibrated confidence estimate print(out.num_tasks) # sub-tasks executed after uncertainty gating ``` Downstream code can act on refusals. It can escalate to a reviewer, retry with retrieval, or log for audit, instead of parsing prose for hesitation that was never there. ## What ships in the box Beyond the six modules, the repo has the full loop to train, evaluate, and serve: - Training pipeline in `art/training/`, driven by `configs/art_base.yaml`, `configs/art_full.yaml`, and `configs/multi_art.yaml`, with staged schedules that pre-train the core before freezing routing projections. - Benchmark harness in `art/benchmark/` covering GSM8K, MATH, MMLU, HumanEval, MedQA, and LegalBench, plus a failure injection framework and latency measurement. Results write as structured JSON so figures regenerate exactly. - NVFP4 utilities in `art/utils/quantization.py` with block scaled 4-bit simulation and bounded initialisation safeguards, alongside optional hardware paths for Blackwell GPUs. - Serving in `art/api/serve.py` as a FastAPI app with `/v1/infer`, `/v1/batch`, and health endpoints. - Checkpoint export that integrates with Hugging Face tooling. - Unit tests in `tests/test_modules.py` covering shape contracts, cycle rejection, depth and width bounds, uncertainty gating, verification outcomes, and abstention logic. The suite runs on CPU in seconds. The package metadata states Python 3.9 or newer in `pyproject.toml`, while the README asks for Python 3.10 or newer. I develop on 3.10 and above. Dependencies include `torch>=2.0.0`, `transformers>=4.30.0`, `datasets>=2.14.0`, `numpy>=1.24.0`, `pyyaml>=6.0`, `tqdm>=4.65.0`, `fastapi>=0.100.0`, `uvicorn>=0.23.0`, and `pydantic>=2.0.0`. Evaluate a trained model under simulated NVFP4 with ensemble consensus with one command: ```bash uv run python -m art.benchmark.run \ --checkpoint checkpoints/best.pt \ --nvfp4 --multi --limit 500 --output-dir result ``` ## Main results I report the NVFP4 numbers first because that is the point of the design. ART was built from scratch for aggressive 4-bit math, with bounded activations and no recursion. Quantization noise shows up as detectable uncertainty instead of silent hallucination. Dense models degrade sharply at the same precision. ART barely moves. | System | GSM8K | MATH | MMLU | HumanEval | |---|---|---|---|---| | Dense FP16 | 47.2 | 12.1 | 45.2 | 21.3 | | Dense NVFP4 | 40.5 | 9.8 | 38.6 | 17.4 | | ART FP16 | 56.4 | 18.2 | 49.3 | 25.4 | | ART NVFP4 | 55.6 | 17.5 | 48.6 | 24.8 | | Multi-ART NVFP4 | 57.9 | 19.1 | 50.4 | 26.5 | The table above is `result/table2.json`. GSM8K climbs from 47.2 percent dense FP16 to 55.6 percent ART NVFP4, and to 57.9 percent with three way consensus. MATH moves from 12.1 to 17.5, and to 19.1 with consensus. The same pattern holds on MMLU and HumanEval. ```chart { "type": "bar", "data": { "labels": ["Dense FP16", "Dense NVFP4", "ART FP16", "ART NVFP4", "Multi-ART NVFP4"], "datasets": [{ "label": "GSM8K accuracy percent", "data": [47.2, 40.5, 56.4, 55.6, 57.9] }] }, "options": { "responsive": true, "scales": { "y": { "beginAtZero": true, "title": { "display": true, "text": "percent" } } } } } ``` ### Confident errors and leakage I care more about confident error rate than raw accuracy. A wrong answer with high confidence is the failure that hurts users. | System | FP16 confident error percent | NVFP4 confident error percent | |---|---|---| | Dense text | 12.4 | 19.8 | | Dense binary | 10.1 | 14.5 | | ART binary | 2.1 | 2.9 | | Multi-ART M equal 3 | 1.4 | 1.8 | The table above is `result/table4.json`. Dense text at NVFP4 answers confidently and wrong 19.8 percent of the time. ART at NVFP4 does that 2.9 percent of the time. Three way consensus brings it to 1.8 percent. Error leakage tells a similar story. This is the share of errors that slip through verification, from `result/table5.json`: Dense text NVFP4 82 percent, Dense binary 67 percent, ART single 14 percent, Multi-ART 5 percent. I read that as the verification anchor doing its job. Most bad expert outputs never reach synthesis. Repeated runs stay tight. From `result/table3.json`, GSM8K with standard deviation: Dense text 48.5 plus minus 0.8 FP16 and 42.1 plus minus 1.4 NVFP4, Dense binary 49.7 plus minus 0.6 and 45.3 plus minus 1.1, ART binary 56.4 plus minus 0.4 and 55.6 plus minus 0.5, Multi-ART 58.7 plus minus 0.3 and 57.9 plus minus 0.3. ### Cost and memory | System | Relative cost | |---|---| | Dense FP16 text | 1.0 | | Dense NVFP4 text | 0.72 | | ART NVFP4 | 0.29 | | Multi-ART NVFP4 | 0.43 | The table above is `result/table6.json`. ART at NVFP4 runs at 0.29x relative inference cost. Even three parallel instances at 0.43x stay below half the dense FP16 baseline. Memory and latency come from `result/table13.json`: | Format | Accuracy percent | Confident error percent | Memory GB | Latency ms per query | |---|---|---|---|---| | FP16 baseline | 56.4 | 2.1 | 5.4 | 98 | | FP8 | 56.1 | 2.4 | 2.8 | 61 | | INT4 GPTQ | 52.1 | 4.8 | 1.8 | 47 | | NVFP4 ART | 55.6 | 2.9 | 1.6 | 38 | ART at NVFP4 needs 1.6 GB against 5.4 GB at FP16, and answers in 38 ms per query against 98 ms in our harness. INT4 GPTQ uses 1.8 GB and 47 ms but drops to 52.1 percent accuracy with 4.8 percent confident errors. I chose NVFP4 because it kept accuracy while cutting memory and latency together. ### Errors do not snowball In dense models small numerical errors compound layer after layer. In ART they stay flat. That property makes everything else possible. From `result/table14.json`, error magnitude by depth at NVFP4: Dense goes 0.18 at depth 4, 0.54 at depth 8, 1.41 at depth 12, 3.87 at depth 16. ART goes 0.12, 0.19, 0.23, 0.28 across the same depths. I plotted this in `result/figures/table14_chart.png`. The dense curve climbs. Ours stays level. ### Calibration When ART says 80 percent sure, it is right about 80 percent of the time. The reliability diagram in `result/figures/reliability_diagram.png` shows that alignment. The abstention curve in `result/figures/abstention_accuracy.png` climbs steeply as coverage shrinks, which is what I want from a system allowed to pass on hard questions. Numbers from `result/table11.json`: | System | ECE | Brier | AUROC | |---|---|---|---| | Dense FP16 text | 0.168 | 0.341 | 0.72 | | Dense NVFP4 text | 0.243 | 0.428 | 0.64 | | MoE FP16 calibrated | 0.112 | 0.295 | 0.78 | | ART NVFP4 binary | 0.024 | 0.142 | 0.94 | | Multi-ART NVFP4 M equal 3 | 0.018 | 0.118 | 0.97 | Lower ECE and Brier are better. Higher AUROC is better. Dense at NVFP4 degrades to 0.243 ECE. ART at NVFP4 sits at 0.024, and consensus at 0.018. ## Ablations I removed each piece in turn to see what breaks. From `result/table7.json`, confident error rate at ART binary plus NVFP4 starts at 2.9 percent with high stability. Without binary tokenization it rises to 6.9 percent with medium stability. Without the uncertainty channel it rises to 8.1 percent with low stability. Without D3R routing it rises to 10.4 percent with low stability. Without CRA verification it rises to 12.8 percent with poor stability. No single stage carries the result alone. Verification matters most in that table, which matches my experience debugging it. When I loosened the anchor, bad expert outputs reached synthesis and confidence numbers stopped meaning much. Router bounds show a clear sweet spot in `result/table8.json`. K max 4 and D max 2 gives 52.6 percent at 0.21 relative cost. K max 8 and D max 4 gives 55.6 percent at 0.29. K max 16 and D max 4 gives 55.8 percent at 0.38. K max 8 and D max 6 gives 55.5 percent at 0.34. K max 16 and D max 8 gives 55.3 percent at 0.52. I ship 8 and 4. Wider and deeper graphs cost more without helping accuracy. ## Tokenization and routing Offline binary records change the input path. From `result/table1.json`: text pipeline is CPU limited, high memory amplification, linear latency growth in batch size, high latency variance, poor accelerator utilization. BPL is bandwidth limited, minimal amplification near 1, sublinear latency growth, low variance, near saturation utilization. Accuracy follows the same split in `result/table9.json`: | Tokenization | Accuracy | Confident error | Prep cost | |---|---|---|---| | BPE text baseline | 47.9 | 12.4 | Runtime | | Byte level | 46.1 | 11.8 | Runtime | | Unigram SentencePiece | 48.3 | 11.2 | Runtime | | BPL binary offline | 55.6 | 2.9 | Offline | Routing comparison from `result/table10.json`: | Routing | Accuracy | Confident error | Failure pass | Deterministic | |---|---|---|---|---| | MoE learned gating | 46.5 | 10.2 | 58 | No | | Tool augmented | 48.2 | 9.4 | 45 | No | | D3R deterministic | 55.6 | 2.9 | 14 | Yes | Deterministic argmax against frozen projections removes sampling variance from routing. That choice cost some flexibility during training, and it repaid that cost in reproducibility. I can rerun a graph and get the same graph. ## Failure injection I injected retrieval noise, tool misuse, and multi step cascading failures to see which architecture holds up. From `result/table12.json`, accuracy under each stress: Dense text holds 41.3, 38.7, 34.2. Tool augmented holds 52.6, 43.1, 39.8. ART single holds 64.8, 66.2, 61.5. Multi-ART holds 69.1, 70.4, 67.3. The gap widens under stress. Stateless experts cannot call one another, so a poisoned retrieval result stays contained in its own node. The anchor rejects it, synthesis never sees it, and the answer either uses surviving evidence or abstains. ## High stakes suites MedQA and LegalBench matter to me because they proxy the domains where a wrong answer costs real money or health. From `result/table15.json`: Dense FP16 scores MedQA 41.2 accuracy with 18.4 confident error, LegalBench 44.5 with 16.1. Dense NVFP4 falls to 33.8 with 27.6, and 36.3 with 24.9. ART NVFP4 scores 44.8 with 3.6, and 47.1 with 3.3. Multi-ART reaches 46.2 with 2.4, and 48.6 with 2.1. Quantization hurts dense models most where I can afford it least. On MedQA dense confident errors climb from 18.4 to 27.6 percent when moving to NVFP4. ART stays at 3.6 percent at the same precision. ## Getting started You need Python 3.10 or newer per README, with `pyproject.toml` allowing 3.9 and above: ```bash git clone https://github.com/swadhinbiswas/Aurora cd Aurora pip install . ``` Or with uv: ```bash uv sync ``` Minimal forward pass: ```python import torch from art import ART model = ART(vocab_size=50257, hidden_dim=768, num_layers=12, num_heads=12) out = model(input_ids=torch.randint(0, 50257, (2, 128))) print(out.abstained) print(out.confidence) print(out.num_tasks) ``` Run the test suite, CPU only, finishes in seconds: ```bash pytest tests/ -v ``` Train from YAML: ```bash python scripts/train.py --config configs/art_full.yaml ``` Evaluate standard suites: ```bash python -m art.benchmark.run --checkpoint checkpoints/best.pt --nvfp4 --limit 500 ``` Regenerate figures from structured results: ```bash python -m art.benchmark.analysis --input result ``` ## Hardware note and reproduction Native NVFP4 acceleration needs NVIDIA Blackwell class GPUs, compute capability 10.x. On older GPUs and CPUs the library runs in faithful simulation mode with the same numerics and behavior, without the speed and memory wins. I did most early debugging in simulation and moved to Blackwell for timed runs. The full 8B configuration in `reproduce.sh` asks for an 8x Blackwell B200 cluster for native NVFP4 tensor cores and BPL DMA bypass. The training corpus is 198 GB of proprietary expert reasoning and coding text that I cannot redistribute, so `reproduce.sh` skips raw dataset preparation by design. Tracked `checkpoints/export/` entries are placeholders to replace with a locally trained checkpoint from `python scripts/train.py --config configs/art_base.yaml`. `reproduce.sh` runs four steps: prepare dataset and offline tokenization, distributed training from `configs/art_base.yaml`, full evaluation across GSM8K, MATH, MMLU, HumanEval, MedQA, and LegalBench with `--limit 200` to `checkpoints/art-8b-nvfp4-instruct.pt`, and figure generation to `result/`. When training exits non zero on non Blackwell hardware, the script falls back to the pre trained 8B checkpoint path. The README warns that paper `--checkpoint` commands assume a checkpoint exists at `checkpoints/`, otherwise the harness re-plots committed results without evaluating a model. Point it at a real checkpoint before claiming a fresh number. About pretrained weights: an 8B instruction tuned checkpoint with GGUF, MLX, and PyTorch exports was trained on that proprietary expert corpus. Those weight files are not in the repo. Architecture, training pipeline, tokenizers, benchmark harness, and evaluation logs are all there. Train your own model with the provided configs, or wire heavier expert backends through the registry interface. ## Honest limitations ART is a research testbed. The bundled experts are lightweight neural stand ins behind a stable interface. Only the math expert dispatches to a real symbolic backend today. Users bring heavier tools for code, retrieval, and domain work. Because the architecture refuses to guess, it abstains more often than dense baselines. That behavior helps in a clinic or a law office and annoys in a chatbot. I consider that trade the point of the project, but I track abstention rate alongside accuracy so the cost stays visible. The repo history showed 10 commits on main and 3 stars when I pulled these numbers, language Python, license MIT. Citation metadata is version 0.1.0, released 23 August 2026, DOI `10.5281/zenodo.22067754`: ```text @software{biswas2026art, title = {ART: AURORA-Transformer, a modular transformer library for uncertainty-aware language reasoning}, author = {Biswas, Swadhin and Sheikh, Tuhin and Shakil, Md Shahriar}, year = {2026}, doi = {10.5281/zenodo.22067754}, url = {https://github.com/swadhinbiswas/Aurora} } ``` Authors are Swadhin Biswas with ORCID `0009-0005-2980-6651`, Tuhin Sheikh, and Md Shahriar Shakil, Department of Computer Science and Engineering, Daffodil International University, Dhaka, Bangladesh. Contact is `swadhinbiswas.cse@gmail.com`. If you work on calibration, routing, or low precision training, the repo gives you a place to swap one stage and measure the effect in isolation. Start with `configs/art_base.yaml`, run the CPU tests, then try a single ablation from the table above and see whether your change moves confident error rate or just accuracy. --- ## Self-hosting the whole Git workflow - URL: https://blog.swadhin.cv/blog/self-hosting-the-whole-git-workflow/ - Published: 2026-01-11T10:00:00.000Z - Updated: 2026-09-23T12:25:13.000Z - Author: Swadhin Biswas - Categories: Backend, DevOps, Architecture, Programming - Excerpt: A self-hosted forge with stacked pull requests, a speculative merge queue, Actions-compatible CI, and AI review. The reasoning behind a modular monolith, and the parts that were hard. ### Content Most developers can self-host almost everything they depend on. Databases, queues, object storage, monitoring, all of it has a credible open-source path. The forge is the exception. The place where every commit, review, and release passes through is usually someone else's server with a per-seat price attached, and the workflow features that make it pleasant are treated as the moat that keeps you there. OpenCodeHub started as a question about that moat. If the pleasant parts are mostly workflow features, stacked diffs and merge queues and CI, then they are software, not magic, and software can be written. What I did not expect was how much of the work would go into the boring parts: making one codebase serve a browser, a Git client over HTTP and SSH, a GraphQL consumer, and a pipeline runner without splitting into eleven services. Repo: [swadhinbiswas/OpencodeHub](https://github.com/swadhinbiswas/OpencodeHub) · Docs: [docs.opencodehub.space](https://docs.opencodehub.space) ## The shape of the thing The whole platform is one application with clear internal seams, which is what makes a single container possible and a small team able to run it. ```mermaid flowchart TB C[Browser + Git CLI + och CLI] --> W[Web UI] C --> R[REST API - 175+ routes] C --> G[GraphQL endpoint] C --> GS[Git server - HTTP RPC] C --> SS[SSH server] W --> DB[(Postgres / SQLite / Turso)] R --> DB G --> DB GS --> DB R --> Q[(Redis queues)] Q --> WK[Worker - webhooks and automation] WK --> RUN[Runner - Docker executors] DB --> S3[(Pluggable S3 storage)] ``` Three container images ship: the platform (web UI, REST and GraphQL API, Git over HTTP and SSH), a worker for queues and webhooks and automation, and a runner that executes pipelines in Docker. The images are around 251 MB, which is small enough that pulling the stack on a small server is not a project of its own. The persistence layer is deliberately swappable. Postgres for a real deployment, SQLite for a laptop, Turso when you want the database to live somewhere managed. That choice costs some care in the data layer, because the three engines do not agree on every detail, but it removes the "you need a database before you can try this" wall that keeps people from evaluating a self-hosted tool at all. ## Stacked pull requests The feature I reach for first on anything larger than a bug fix is the stack. A feature that touches the schema, the API, and the UI is three coherent changes pretending to be one, and as a single pull request it becomes a thousand-line review that nobody reads carefully. `och stack create` builds a chain of dependent branches. Each layer is a pull request against the one below it, so a reviewer can approve the schema change while the API on top of it is still moving. `och stack submit` pushes every branch and opens the linked pull requests. `och stack sync` rebases the whole stack when `main` moves, and `och stack log` draws the topology in the terminal so you can see what depends on what. The reason this belongs in the forge rather than a separate CLI is the review state. A stack has relationships between pull requests, and those relationships need to be first-class: which one is approved, which one is blocked, which one merged and left its children pointing at a gone parent. A third-party tool can only infer that from the API. ## A merge queue that does not serialize everything The second feature is the one that protects `main` without making everyone wait. If you validate pull requests one at a time against `main`, a queue of ten becomes a queue of ten builds, and the last author waits for work that has nothing to do with them. The alternative is speculative builds: when several pull requests are ready, each one is tested against the result of the ones ahead of it in the queue, so a build that passes proves the combination, not just the branch. ```svg PR 1 PR 2 PR 3 main ``` Speculative builds make the hard parts elsewhere. A failed build in the middle invalidates everything behind it, so the queue has to rebuild the tail, and the queue has to stay ordered while several lanes run in parallel. Priority lanes solve the other half of the problem: an urgent fix should not sit behind a long automatic queue, and a human needs a way to say "this one first" that the scheduler respects. The queue is also where the CLI earns its keep. `och queue add 42`, `och queue status 42`, and `och queue list` are what a developer actually types, and `och focus` opens a terminal cockpit that shows the lanes and the speculative build states live, so you can watch a queue without switching to a browser. ## CI without asking for a rewrite Pipelines run in isolated Docker executors and accept GitHub Actions YAML. That compatibility is a deliberate constraint, not a shortcut. A team evaluating a forge already has a repository full of workflows, and asking them to rewrite automation is the fastest way to lose them. Running what they already have is the difference between a migration that takes an afternoon and one that never happens. The runner image exists because pipeline execution is the one part of the system that should not share a process with the API. It runs Docker-in-Docker, which is heavy and occasionally hostile, and keeping it separate means a runaway build cannot take the platform down with it. ## AI review, provider-agnostic Automated review runs through GPT-4, Claude 3.5, Gemini 1.5, Groq, and a local Ollama model behind one interface. The value is a first pass before a human spends time: an obvious bug, a missing test, a naming inconsistency, the sort of thing that is easier to catch when something else reads the diff first. The provider abstraction is the point. Model quality changes every few weeks, and a review system wired to one vendor turns a model upgrade into a code change. Behind one interface, swapping providers is configuration. ## Storage and federation Storage is pluggable across the local filesystem and any S3-compatible bucket: AWS, MinIO, Cloudflare R2, Backblaze B2, or Ceph. A homelab deployment keeps everything local, and the same code points at object storage when the repositories and build artifacts outgrow the disk. Federation came from a real annoyance. Two teams running separate instances still share libraries, and without federation the only options are a shared account on one instance or a mirror that drifts. With it, one instance can fork from another, push branches, and open a pull request across the boundary. It is the feature that makes self-hosting a network instead of a set of islands. ## What the work actually was The impressive-sounding part, Git over HTTP and SSH and a pipeline runner in one binary, was mostly plumbing that had to be correct. The hard part was keeping one codebase coherent while it served very different clients, and the thing that made it tractable was refusing to split it into services before there was a reason. A modular monolith gets called a stepping stone, but for a team of one it is the difference between a system you can operate and a distributed system you cannot debug. The test suite is 679 unit, integration, and contract tests, which is partly about correctness and partly about being able to change the storage engine and the queue without fear. The deployment is Docker Compose, an admin seed script, and a browser at port 4321. There is a real trade-off in a project like this. A self-hosted forge will never have the ecosystem of a hosted one, and pretending otherwise would be dishonest. What it can have is ownership, no per-seat fee, and the workflow features that matter, in a form you can read and change. The repository and the API reference are linked above. Reach me at swadhinbiswas.cse@gmail.com or on [GitHub](https://github.com/swadhinbiswas) and [LinkedIn](https://www.linkedin.com/in/swadhinbiswas/). ---