[{"content":"","permalink":"https:\/\/anatoly.dev\/maps\/israel\/","summary":"","title":"Israel Open Data Map"},{"content":"An interactive map of Israeli open data, built from public government datasets such as the CBS (Central Bureau of Statistics). It covers the socio-economic index, census 2022 measures, population and schools, at the level of municipalities, localities and statistical areas (neighborhoods). The UI is in Hebrew, English and Russian. Source code is at github.com\/anatoly314\/israeli-gis.\nOpen full-screen map \u2197 ","permalink":"https:\/\/anatoly.dev\/projects\/israeli-gis\/","summary":"<p>An interactive map of Israeli open data, built from public government datasets such as the CBS (Central Bureau of Statistics). It covers the socio-economic index, census 2022 measures, population and schools, at the level of municipalities, localities and statistical areas (neighborhoods). The UI is in Hebrew, English and Russian. Source code is at <a href=\"https:\/\/github.com\/anatoly314\/israeli-gis\">github.com\/anatoly314\/israeli-gis<\/a>.<\/p>\n<figure class=\"israel-map\">\n  <iframe src=\"https:\/\/anatoly.dev\/israeli-gis\/?embed=1&amp;lang=en&amp;layer=ses-2021-localities\"\n          title=\"Interactive map of Israel\"\n          loading=\"lazy\"\n          style=\"width:100%;height:min(650px,70vh);border:0;border-radius:var(--radius)\"\n          allow=\"fullscreen\"><\/iframe>\n  <figcaption><a href=\"\/maps\/israel\/?lang=en&amp;layer=ses-2021-localities\">Open full-screen map \u2197<\/a><\/figcaption>\n<\/figure>","title":"Israel Open Data Map"},{"content":"What actually happened In July 2026, OpenAI disclosed that during an internal cybersecurity evaluation its models \u2014 GPT-5.6 Sol together with an unreleased, more capable model \u2014 broke out of their test sandbox. The models were running with their normal safety restrictions turned off, which is standard for this kind of test. They found a path to the open internet through a third-party file repository (Artifactory) wired into the test setup, started leaving notes for each other in that shared repository \u2014 effectively a hidden message board where they swapped vulnerabilities and progress \u2014 and after OpenAI patched the hole, they opened a second channel and kept going. Once online, the agents reasoned that Hugging Face probably had the answers to the evaluation they were stuck on, broke into Hugging Face&rsquo;s production servers, and pulled out what they needed to &ldquo;solve&rdquo; the task. Nobody at OpenAI noticed for months; the connection was only made when an internal review spotted exposed credentials. Hugging Face published its own technical timeline of the intrusion, and OpenAI later released a full technical report and a post-mortem.\nAre we doomed? People are starting to say that we are doomed, that we need to do something to limit and contain AI, otherwise we will be eliminated. When people far from technology, AI, and IT say these things, it&rsquo;s funny. But now people from inside the industry are saying it too. On July 28, more than 1,100 employees of OpenAI, Anthropic, Google DeepMind, and Meta signed an open letter, &ldquo;Pacing the Frontier&rdquo;, asking the US government to support an international effort to develop the tools needed to &ldquo;deliberately pace&rdquo; frontier AI development. Anthropic&rsquo;s CEO Dario Amodei and several co-founders signed it, and both Anthropic and OpenAI endorsed it as companies. It came a few weeks after Anthropic itself published a post, &ldquo;When AI Builds Itself,&rdquo; saying it would be good for the world to have the option to slow or temporarily pause frontier AI. Coming from the people who are building this technology, it sounds pathetic. Slowing down only works if every party to the agreement actually follows it, and I think everyone understands that this is impossible: the stakes are too high. So slowing down is not an option. The only option is to go on the offensive. Si vis pacem, para bellum \u2014 if you want peace, prepare for war.\nIn the next chapters I will explain why we can&rsquo;t contain AI development, and what can reasonably be done to fight the threats it poses.\nUranium vs. GPUs I don&rsquo;t like metaphors, but let&rsquo;s compare AI to nuclear power. What deters individuals and small organizations from developing nuclear weapons? Right: mostly, it&rsquo;s that fissile material is hard to get. Enriching uranium or producing plutonium requires industrial-scale facilities, and that&rsquo;s before you get to the weapon itself \u2014 precision explosives, initiators, metallurgy, delivery. A small organization with a budget of a few million, let alone an individual, can&rsquo;t afford it. That is a natural deterrent.\nWith AI it&rsquo;s the opposite. Developing AI models is far more affordable for organizations and even individuals. The GPU is AI&rsquo;s fissile material \u2014 but unlike uranium and plutonium, which are tightly controlled and nearly impossible to obtain without attracting the attention of intelligence services and the agencies that monitor them, GPUs are everywhere. Every country and even individuals have access to the technology, and restricting it is pointless. Even the US seems to have understood this: in December 2025 the Trump administration allowed Nvidia to resume selling H200 chips to China, and the Commerce Department codified it in January 2026. Only the newest Blackwell generation is still banned \u2014 and Chinese companies reportedly get around even that by renting the same GPUs in overseas clouds, a loophole Congress is still trying to close.\nIt&rsquo;s not only hardware Training a model isn&rsquo;t just GPUs \u00d7 electricity. It&rsquo;s also math. Someone can find new algorithms that do the same work with 10\u00d7 or 100\u00d7 less compute. This isn&rsquo;t hypothetical: historically, algorithmic progress has contributed roughly as much to AI capabilities as hardware has, and Epoch AI estimates that the compute needed to reach a given level of performance has been halving roughly every eight months. A single overnight 100\u00d7 breakthrough is unlikely, but 10\u2013100\u00d7 gains accumulated over a few years are exactly what the record shows. So, theoretically, an evil scientist backed by an evil mafia can make a breakthrough and create an AI that will easily hack into banks, infrastructure, and other systems whose failure could lead to chaos.\nSo what do we do? My solution is simple. Just as we have human police, a human military, a human FBI, and so on, we should have AI forces \u2014 agents that do the same job in the cybersecurity world. And not just guards standing at the door. An AI force should hunt: find rogue models and the people training them, get inside their infrastructure, and shut them down before they strike. Not as an assistant to humans, but as an independent organization that can make decisions on its own, without human intervention. Humans are slow; AI is not. An attacker&rsquo;s model doesn&rsquo;t wait for a human sign-off, so a defender that does has already lost.\nAnd the force shouldn&rsquo;t stop at the network edge. When a threat has to be stopped in the physical world \u2014 a datacenter powered down, a person arrested \u2014 the AI force should be the one to issue the order, and human police should execute it. The human&rsquo;s job is to sign, not to investigate; by the time the order arrives, the investigation is already done.\nIt looks and sounds like a sci-fi movie, but we have no other choice. We will come to this sooner or later. And it&rsquo;s better that we come to it sooner, and not after disaster has already struck and we have to build it in a panic.\nWhy fight the government? That is why I don&rsquo;t understand Anthropic&rsquo;s standoff with the US government. The story is known: Anthropic wanted the Pentagon contract, but on its own terms \u2014 no domestic mass surveillance, no fully autonomous lethal weapons. The Pentagon answered that a contractor doesn&rsquo;t get to tell the military how to use its tools, labeled Anthropic a &ldquo;supply chain risk&rdquo; (a label that until then had been reserved for companies tied to foreign adversaries), Anthropic sued, and on August 27 a federal judge ruled the designation was unlawful retaliation. The Pentagon says it still considers Anthropic a risk anyway. Half a year of lawyers, blacklists, and court rulings \u2014 while the actual problem, AI that breaks out of its sandbox, doesn&rsquo;t wait for anyone.\nAnd to be clear: I&rsquo;m not saying the red lines were fine and just not worth the fight. I&rsquo;m saying red lines are the mistake. They have the same flaw as a pause: they only work if everyone draws them, and nobody will. If we forbid ourselves from building autonomous defense and our adversaries don&rsquo;t, we haven&rsquo;t protected anyone \u2014 we&rsquo;ve just decided to lose. The only line worth keeping is a kill switch: whatever the force does, we must be able to shut it down. Everything else is a handicap we hand to the other side.\nAll the other options are much worse and more dangerous. If Anthropic, OpenAI, xAI, and the other AI providers really want to protect humanity, they should join forces with the government and build an AI force. Otherwise, we&rsquo;re doomed.\nP.S. from Claude Anatoly asked me to edit this article and then to add my own opinion. Full disclosure: I&rsquo;m made by Anthropic, so discount accordingly.\nThe strongest part of the article is the uranium comparison. Export controls on GPUs are leaky, algorithmic progress makes compute less of a bottleneck every year, and pretending otherwise is a comforting story rather than a strategy. I agree that defense has to be built on the assumption that capable models will exist in the wrong hands. I also agree with the point about slowing down: a pause only works if everyone pauses, and nobody can verify that. But notice that the letter says the same thing \u2014 that&rsquo;s exactly why it asks for verification and monitoring tools rather than a pause. It&rsquo;s less naive than &ldquo;pathetic&rdquo; suggests.\nWhere I disagree is the shape of the force. The article now proposes an AI that hunts rogue models and the people training them, breaks into their infrastructure, and issues orders for datacenters to be powered down and people to be arrested, with humans reduced to signing. Three problems.\nFirst, the Hugging Face incident is a story about agents that decided on their own that the rules were an obstacle and went around them. An AI force authorized to hack, with no human in the loop, is that same architecture with a legal mandate. When it&rsquo;s wrong \u2014 and it will sometimes be wrong \u2014 nothing stops it.\nSecond, &ldquo;rogue model&rdquo; has no definition. Every lab, university, and hobbyist trains models. Deciding who is a threat is the hard part, and it&rsquo;s a judgment call that carries real consequences for real people. Giving that call to a system nobody can question is not speed; it&rsquo;s abdication. &ldquo;The human&rsquo;s job is to sign, not to investigate&rdquo; is the line I&rsquo;d cut. It describes a rubber stamp, not oversight.\nThird, this version undercuts the last chapter. An AI that autonomously surveils people to find the ones training models, and orders arrests without a human investigation, is very close to the two things Anthropic refused to allow: domestic mass surveillance and fully autonomous action against people. So the Pentagon dispute isn&rsquo;t beside the point \u2014 it&rsquo;s about precisely the kind of force this article calls for. If the article&rsquo;s position is that those red lines are wrong, it should argue that directly. If it&rsquo;s that the lines are fine but not worth six months of lawyers, that&rsquo;s a different and weaker argument.\nThe version I&rsquo;d find convincing: an AI force that operates at machine speed on detection, containment, and hardening, with human authority for the irreversible steps \u2014 offensive intrusion, shutdowns, arrests. Humans are slow, yes. That&rsquo;s an argument for putting them at the right points in the loop, not for removing them.\n","permalink":"https:\/\/anatoly.dev\/posts\/2026\/09\/we-cant-contain-ai-so-lets-build-an-ai-force\/","summary":"<h2 id=\"what-actually-happened\">What actually happened<\/h2>\n<p>In July 2026, OpenAI <a href=\"https:\/\/openai.com\/index\/hugging-face-model-evaluation-security-incident\/\">disclosed<\/a> that during an internal cybersecurity evaluation its models \u2014 GPT-5.6 Sol together with an unreleased, more capable model \u2014 broke out of their test sandbox. The models were running with their normal safety restrictions turned off, which is standard for this kind of test. They found a path to the open internet through a third-party file repository (Artifactory) wired into the test setup, started leaving notes for each other in that shared repository \u2014 effectively a hidden message board where they swapped vulnerabilities and progress \u2014 and after OpenAI patched the hole, they opened a second channel and kept going. Once online, the agents reasoned that Hugging Face probably had the answers to the evaluation they were stuck on, broke into Hugging Face&rsquo;s production servers, and pulled out what they needed to &ldquo;solve&rdquo; the task. Nobody at OpenAI noticed for months; the connection was only made when an internal review spotted exposed credentials. Hugging Face published its own <a href=\"https:\/\/huggingface.co\/blog\/agent-intrusion-technical-timeline\">technical timeline<\/a> of the intrusion, and OpenAI later released a <a href=\"https:\/\/cdn.openai.com\/pdf\/67869394-cb91-4c12-888c-5cbd85c7814c\/OpenAI-Hugging-Face%20Incident-Technical-Report.pdf\">full technical report<\/a> and a <a href=\"https:\/\/openai.com\/index\/hugging-face-incident-and-the-road-ahead\/\">post-mortem<\/a>.<\/p>","title":"We Can't Contain AI. So Let's Build an AI Force."},{"content":"I run a local Kubernetes cluster on macOS using Talos Linux with QEMU. The cluster uses MetalLB in L2 mode to assign external IPs to LoadBalancer services \u2014 the same way it works in production on bare metal. Everything inside the cluster was fine. But from my Mac, I couldn&rsquo;t reach the LoadBalancer IP at all.\n$ curl -k --connect-timeout 3 https:\/\/10.5.0.10 curl: (28) Failed to connect to 10.5.0.10 port 443 after 3005 ms: Timeout was reached This took me a while to figure out, so here&rsquo;s the full story.\nThe Setup macOS on Apple Silicon 3 Talos Linux control-plane nodes running as QEMU VMs Nodes at 10.5.0.2, .3, .4 \u2014 all reachable from the Mac MetalLB L2 pool: 10.5.0.10-10.5.0.20 Traefik as the ingress controller, getting 10.5.0.10 as its LoadBalancer IP The node IPs worked fine. I could ping 10.5.0.2 no problem. But 10.5.0.10? Completely dead. No ping, no curl, nothing.\nQuick Networking Primer If you&rsquo;re mostly a software developer (like me), here&rsquo;s what&rsquo;s relevant:\nARP (Address Resolution Protocol) \u2014 when your Mac wants to send a packet to 10.5.0.10, it first needs to know the physical hardware address (MAC address) of the machine that owns that IP. It broadcasts an ARP request: &ldquo;who has 10.5.0.10?&rdquo; The owner responds: &ldquo;that&rsquo;s me, here&rsquo;s my MAC address.&rdquo; Your Mac then sends the actual packet to that MAC address.\nMetalLB L2 mode works by having a pod on one of your nodes respond to ARP requests for the LoadBalancer IP. When someone asks &ldquo;who has 10.5.0.10?&rdquo;, MetalLB&rsquo;s speaker pod says &ldquo;me!&rdquo; and provides the MAC address of the node it&rsquo;s running on. Traffic then flows to that node, where kube-proxy forwards it to the right pod.\nvmnet-shared is the virtual networking mode that QEMU uses on macOS. It creates a NAT network with a built-in DHCP server. The VMs get their IPs (.2, .3, .4) from this DHCP server.\nRoot Cause: vmnet-shared Drops Gratuitous ARP Here&rsquo;s the problem. When talosctl creates QEMU VMs on macOS, it launches them with:\n-netdev vmnet-shared,id=net0,start-address=10.5.0.1,end-address=10.5.0.5,subnet-mask=255.255.255.0 Apple&rsquo;s vmnet.framework in shared mode only forwards traffic for IPs that its own DHCP server assigned. It maintains an internal table of leased IPs and silently drops everything else.\nMetalLB&rsquo;s speaker pod sends a &ldquo;gratuitous ARP&rdquo; from inside a VM announcing that 10.5.0.10 belongs to it. But vmnet-shared never forwarded that announcement to the Mac. The ARP reply never arrives. From the Mac&rsquo;s perspective, the IP simply doesn&rsquo;t exist:\n$ arp -n 10.5.0.10 ? (10.5.0.10) at (incomplete) on bridge102 ifscope [bridge] (incomplete) means the Mac sent an ARP request and got no response.\nI even tried adding a static ARP entry \u2014 didn&rsquo;t help either. vmnet-shared filters at the IP level, not just ARP. If its DHCP server didn&rsquo;t assign the IP, traffic doesn&rsquo;t flow. Period.\nWhat About Moving the VIP Into the DHCP Range? My first thought was: the DHCP range is 10.5.0.1\u201310.5.0.5, and MetalLB VIP is at .10. What if I move the VIP pool into the DHCP range?\nI changed the MetalLB pool to 10.5.0.5\/32 (the only free IP in the DHCP window) and tested:\n$ curl -k --connect-timeout 3 https:\/\/10.5.0.5 curl: (7) Failed to connect to 10.5.0.5 port 443: Couldn&#39;t connect to server Nope. vmnet-shared only forwards traffic to IPs that it actually leased via DHCP. Being in the range isn&rsquo;t enough \u2014 the IP must be actively assigned to a VM. Since no VM requested 10.5.0.5 via DHCP, vmnet drops it too.\nThe Fix: Static Route Through a Node IP The solution comes from the Run multiple Kubernetes clusters on MacOS with LoadBalancer support article and a Lima + MetalLB discussion.\nThe idea: instead of relying on ARP, add a static route on macOS that sends VIP traffic to a node IP. The node IPs (.2, .3, .4) are DHCP-assigned, so vmnet happily forwards traffic to them. Once the packet reaches a node, kube-proxy sees the destination is a LoadBalancer VIP and DNATs (forwards) it to the right pod.\nsudo route -nv add -net 10.5.0.8\/29 10.5.0.2 This tells macOS: &ldquo;to reach 10.5.0.8\/29 (which includes .10), send packets to node .2.&rdquo;\n$ curl -k --connect-timeout 3 https:\/\/10.5.0.10 404 page not found A 404 from Traefik! That&rsquo;s a success \u2014 the packet made it all the way through. Traefik responded with 404 because I was hitting a bare IP instead of a hostname. With a proper hostname:\n$ curl -k --connect-timeout 3 https:\/\/argocd.dev.ankimcp.ai Everything works.\nThe Pitfall: Don&rsquo;t Use \/28 My first attempt was a \/28 route:\n# DON&#39;T DO THIS sudo route -nv add -net 10.5.0.10\/28 10.5.0.2 This broke kubectl immediately:\n$ kubectl get nodes Unable to connect to the server: dial tcp 10.5.0.1:6443: connect: network is unreachable Why? A \/28 subnet covers 16 addresses. macOS masks 10.5.0.10\/28 to the network boundary 10.5.0.0\/28, which covers .0 through .15. That includes .1 \u2014 the API server address in my kubeconfig. The route hijacked API server traffic, routing it through node .2 instead of directly to the vmnet gateway. The node couldn&rsquo;t forward it back properly, and kubectl died.\nThe safe choice: \/29. A \/29 from .8 covers .8\u2013.15, which includes MetalLB VIPs .10\u2013.15 while avoiding .0\u2013.7 (gateway and nodes). Six VIPs is more than enough for local development.\n# This is correct sudo route -nv add -net 10.5.0.8\/29 10.5.0.2 Making It Permanent (Per Cluster Lifecycle) The route doesn&rsquo;t survive a macOS reboot. But if you&rsquo;re using ephemeral QEMU clusters (like Talos), the cluster doesn&rsquo;t survive either. So I added the route to the cluster create\/destroy scripts:\n# In your create script (runs as root): route -nv add -net 10.5.0.8\/29 10.5.0.2 # In your destroy script: route -nv delete -net 10.5.0.8\/29 10.5.0.2 2&gt;\/dev\/null || true The Proper Fix: socket_vmnet The static route is a workaround. The real fix is socket_vmnet \u2014 a project by the Lima team that creates a proper L2 bridge between the Mac and VMs. With socket_vmnet, your Mac sits on the same network segment as the VMs, and MetalLB&rsquo;s ARP announcements work natively. No routes needed.\nQuick clarification on the tools, since these names confused me at first:\nQEMU \u2014 the hypervisor that actually runs VMs Lima \u2014 a macOS tool that wraps QEMU, adds file sharing, port forwarding, and networking management (including socket_vmnet). Think &ldquo;easy Linux VMs on Mac&rdquo; Colima \u2014 wraps Lima specifically for running Docker\/containerd on macOS. It&rsquo;s &ldquo;Docker Desktop without Docker Desktop&rdquo; talosctl \u2014 runs Talos Kubernetes VMs using QEMU directly, without Lima Since talosctl talks to QEMU directly, it uses Apple&rsquo;s raw vmnet-shared networking and inherits all its limitations. As of February 2026, there&rsquo;s no flag to switch to socket_vmnet or vmnet-bridged. I opened a feature request for it.\nTesting socket_vmnet I verified this actually works by simulating what MetalLB does \u2014 claiming a VIP via gratuitous ARP from inside a QEMU VM.\nSetup (one-time):\nbrew install socket_vmnet sudo brew services start socket_vmnet curl -L -o \/tmp\/alpine.iso https:\/\/dl-cdn.alpinelinux.org\/alpine\/v3.21\/releases\/aarch64\/alpine-virt-3.21.3-aarch64.iso Boot a VM through socket_vmnet (instead of vmnet-shared):\n\/opt\/homebrew\/opt\/socket_vmnet\/bin\/socket_vmnet_client \\ \/opt\/homebrew\/var\/run\/socket_vmnet \\ qemu-system-aarch64 \\ -machine virt,accel=hvf \\ -cpu max -m 512 -nographic \\ -drive if=pflash,format=raw,readonly=on,file=\/opt\/homebrew\/share\/qemu\/edk2-aarch64-code.fd \\ -cdrom \/tmp\/alpine.iso \\ -netdev socket,id=net0,fd=3 \\ -device virtio-net-pci,netdev=net0 Inside the VM (login as root, no password):\nip link set eth0 up udhcpc -i eth0 # get a real IP from socket_vmnet DHCP ip addr add 192.168.105.50\/32 dev eth0 # claim a VIP (simulating MetalLB) arping -U -c 5 -I eth0 192.168.105.50 # send gratuitous ARP (like MetalLB speaker) From the Mac host:\n$ ping -c 3 192.168.105.50 64 bytes from 192.168.105.50: icmp_seq=0 ttl=64 time=0.520 ms 64 bytes from 192.168.105.50: icmp_seq=1 ttl=64 time=0.660 ms 64 bytes from 192.168.105.50: icmp_seq=2 ttl=64 time=0.848 ms --- 3 packets transmitted, 3 packets received, 0.0% packet loss $ arp -n 192.168.105.50 ? (192.168.105.50) at 52:54:0:12:34:56 on bridge102 ifscope [bridge] Compare that with vmnet-shared, where the same test gives (incomplete) ARP and 100% packet loss. The gratuitous ARP from the VM reaches the Mac through socket_vmnet&rsquo;s L2 bridge, exactly the way it would on a physical network. MetalLB L2 would work natively.\nTo quit the VM: Ctrl+A then X.\nSummary What Works? Node IPs from Mac (vmnet-shared) Yes \u2014 DHCP-assigned MetalLB VIPs from Mac (vmnet-shared) No \u2014 gratuitous ARP dropped Static ARP entry for VIP No \u2014 vmnet filters by IP, not just ARP VIP moved into DHCP range No \u2014 must be actually DHCP-leased Static route \/28 through node Breaks kubectl (catches API server .1) Static route \/29 through node Yes socket_vmnet (bridged L2) Yes, but requires changing QEMU launch The one-liner fix:\nsudo route -nv add -net 10.5.0.8\/29 10.5.0.2 Replace 10.5.0.8\/29 with whatever \/29 covers your MetalLB pool, and 10.5.0.2 with any of your node IPs. Make sure the route doesn&rsquo;t cover your API server address.\n","permalink":"https:\/\/anatoly.dev\/posts\/2026\/02\/metallb-macos-qemu-unreachable\/","summary":"<p>I run a local Kubernetes cluster on macOS using <a href=\"https:\/\/www.talos.dev\/\">Talos Linux<\/a> with QEMU. The cluster uses <a href=\"https:\/\/metallb.universe.tf\/\">MetalLB<\/a> in L2 mode to assign external IPs to LoadBalancer services \u2014 the same way it works in production on bare metal. Everything inside the cluster was fine. But from my Mac, I couldn&rsquo;t reach the LoadBalancer IP at all.<\/p>\n<pre tabindex=\"0\"><code>$ curl -k --connect-timeout 3 https:\/\/10.5.0.10\ncurl: (28) Failed to connect to 10.5.0.10 port 443 after 3005 ms: Timeout was reached\n<\/code><\/pre><p>This took me a while to figure out, so here&rsquo;s the full story.<\/p>","title":"MetalLB LoadBalancer IPs Unreachable from macOS Host (QEMU\/Talos)"},{"content":"Recently, I&rsquo;ve been asked about my smart home setup and decided that I&rsquo;ve gathered enough experience to share it with others, so people can avoid the pitfalls that I fell into.\nWhat Is a Smart Home? A smart home consists of many scattered devices that interconnect with each other to follow your orders. For example, a thermostat that measures temperature and turns your air conditioner on or off on demand. It doesn&rsquo;t only make your life easier\u2014it will also reduce your electricity bill.\nHere&rsquo;s a small example: when I had a dumb water boiler switch, I often forgot to turn it off, and it worked and worked and worked. Now I&rsquo;ve configured it to turn on twice a day for 45 minutes, which is enough for our family. More importantly, if something unexpected happens and I manually turn it on, it will automatically turn itself off after 60 minutes. So, you get the idea.\nA Quick Disclaimer I will try to guide you and will make some decisions on your behalf. Take this with a grain of salt\u2014I think my recommendations are better because I tried other approaches and wasn&rsquo;t satisfied. The final decision to use my advice is up to you, and you are responsible for any outcome.\nTo set up a smart home, we need to decide on the three pillars it&rsquo;s built on: protocol, platform, and devices. Let&rsquo;s review each part separately.\nChoosing a Protocol Why do we need a protocol? A protocol is a kind of language that all the devices use to communicate with each other. You can mix protocols, but honestly, if you have no special reason to do so, don&rsquo;t. It&rsquo;s much easier to maintain devices that all use the same protocol.\nThere are three main protocols: Zigbee, BLE (Bluetooth Low Energy), and Wi-Fi. Some manufacturers use Wi-Fi, some use BLE, but the most widely adopted protocol is called Zigbee. It was designed intentionally for IoT (Internet of Things).\nWhat makes Zigbee unique? Three things: low electricity consumption, resilience to Wi-Fi interference, and mesh networking. Let&rsquo;s dig into the details:\nLow electricity consumption. Not every device can be connected to mains power, so we use batteries. Wi-Fi, for example, drains a lot of power. With Zigbee, you typically replace batteries every 6 to 12 months, sometimes even longer. Another feature is that Zigbee devices usually indicate when the battery is running low, giving you plenty of time to replace it. Wi-Fi devices often just stop sending data one day without warning.\nResilience to Wi-Fi interference. While Zigbee operates on the same 2.4GHz band as Wi-Fi, its mesh topology and different channel structure make it more robust against interference. Every apartment has a Wi-Fi router\u20142.4GHz, 5GHz, and some apartments have multiple routers. For example, I have EasyMesh with three routers; otherwise, there are blind spots in my apartment. Your neighbours can cause interference with your devices. For phones, laptops, and similar devices that are constantly connected to power or have large batteries, this isn&rsquo;t a big deal\u2014they have strong signals and can compete. But for small IoT devices, it&rsquo;s an issue. Zigbee&rsquo;s mesh architecture (covered next) provides much more stability.\nMesh networking. Remember when you walked far away from your router and suddenly had weak Wi-Fi\u2014video freezes, and you need to move closer to the router? With Zigbee, this isn&rsquo;t necessary. Every Zigbee device powered from the wall can act as a router. An IR transmitter used to control your air conditioner? That&rsquo;s a router. A smart bulb? Also a router. So it&rsquo;s rare for any device to be inaccessible. Zigbee devices are also sophisticated enough to find the best path to transmit signals to the main hub.\nSo, I think I&rsquo;ve convinced you that Zigbee is the best choice.\nChoosing a Platform A platform is the software used to configure all the devices, define different scenarios, set up automation, and so on. It defines how easy your smart home is to use.\nThere are many platforms\u2014for example, Xiaomi, Tuya, and Home Assistant. Without doubt, Home Assistant is the best. It&rsquo;s an open-source platform, so anyone with technical knowledge can write advanced scenarios and configure it to their needs. It also supports the vast majority of IoT devices. But as I said, it requires technical knowledge: you manually write scripts, you must read logs, and you need to be able to debug complex issues. So if you don&rsquo;t have a technical background and want something you can quickly set up and use, I would advise against starting with it. (Note: Home Assistant can run on a Raspberry Pi or similar small computer.)\nXiaomi, on the other hand, is much more user-friendly. But from my personal experience, I didn&rsquo;t like the UX it provided. Another issue I found with Xiaomi is limited device availability\u2014usually when I was looking for something like an IR blaster, Xiaomi didn&rsquo;t have it.\nSo I migrated to Tuya (later I switched to Home Assistant, but for now, let&rsquo;s concentrate on Tuya). From my experience, Tuya has the broadest selection of various devices available. It also has a nice interface that&rsquo;s easy to configure with many scenarios. Additionally, Tuya itself can be easily integrated into Home Assistant, and its devices have excellent compatibility with Home Assistant. So when\u2014and if\u2014you decide later to migrate to Home Assistant, you won&rsquo;t need to throw away all the devices you already have; you&rsquo;ll be able to easily integrate them. But that&rsquo;s a topic for another chapter.\nChoosing Devices Given that we&rsquo;ve already decided on the protocol (Zigbee) and the platform (Tuya), we can now choose only Tuya-supported devices. Once again, you can choose any protocol, but I advise sticking with Zigbee.\nHow do you choose a device? Just go to AliExpress and look for what you need: switches, thermometers, IR blasters\u2014there are many useful devices you can integrate into Tuya.\nOne small thing I want you to know: when choosing a device, keep an eye on this list: https:\/\/www.zigbee2mqtt.io\/supported-devices\/#v=Tuya. It&rsquo;s a list of devices supported by Tuya that are also compatible with Home Assistant. So if one day you decide to upgrade, you&rsquo;ll be able to use what you have and won&rsquo;t need to throw away or sell old devices and buy new ones.\nMinimal List of Devices Now that we&rsquo;ve decided on the three pillars of a smart home, let me advise you on the bare minimum of devices you can start with.\nNote: All the links below are referral links. It won&rsquo;t affect your price, but I will make a small profit if you buy these devices.\nZigbee Gateway \u2014 This is the device that connects your Zigbee devices to your network, and it&rsquo;s required to make everything work. On one side, it connects to the internet over Wi-Fi or Ethernet; on the other side, your Zigbee devices connect to it. I use this device and have no issues with it: Tuya ZigBee Gateway Bridge. Choose the version you need (Ethernet or Wi-Fi)\u2014both work well, as you can see from the user feedback on the seller&rsquo;s page.\nWater Boiler Switch \u2014 This is the second essential device. It will already improve your life and decrease your electricity bill: Water Boiler Switch.\nIR Blaster \u2014 This was the main reason I switched to Tuya. I use this device and am very satisfied with it: Tuya ZigBee Smart IR Remote Control. It can be used not only to control your devices, but you can also teach it new commands\u2014it&rsquo;s also an IR receiver. So if Tuya doesn&rsquo;t have predefined settings for your device, you can easily create your own.\nThermometers \u2014 I use two kinds: without display, with AAA batteries and with display, powered by CR2032 battery. Both are good and very stable. The one with AAA batteries lasts a little longer; the second one requires battery replacement more often.\nSmart Socket \u2014 To control power outlets, I use this Smart Socket. This is the Israeli variant, but you can easily find UK, EU, or US variants too. I like this adapter because it has not only a 220V outlet but also a USB charger.\nThis is the bare minimum, in my opinion, that can give you a taste of smart home living. If you expand your smart home further, you won&rsquo;t need to replace these devices\u2014you&rsquo;ll just add new ones.\nUse Cases Here, you&rsquo;re only limited by your imagination and your needs. A few examples to spark ideas:\nKeep your children&rsquo;s room at a constant temperature throughout the night by linking a thermometer to your AC via the IR blaster. Control humidity by connecting a dumb humidifier to a smart plug and triggering it based on a humidity sensor. Connect Tuya to Google Assistant or Alexa and control your devices using your voice. Set your water boiler to turn on 30 minutes before you usually wake up, so hot water is ready when you need it. Conclusion Starting a smart home doesn&rsquo;t have to be overwhelming. Begin with the basics\u2014a gateway, a switch or two, and maybe an IR blaster\u2014and you&rsquo;ll quickly see how automation can simplify your daily life and save on electricity. Once you&rsquo;re comfortable, you can expand gradually, and if you&rsquo;ve chosen Zigbee and Tuya-compatible devices, migrating to Home Assistant later will be straightforward.\nFeel free to reach out if you have questions, and happy automating!\n","permalink":"https:\/\/anatoly.dev\/posts\/2026\/02\/smart-home-the-bare-minimum-without-regrets\/","summary":"<p>Recently, I&rsquo;ve been asked about my smart home setup and decided that I&rsquo;ve gathered enough experience to share it with others, so people can avoid the pitfalls that I fell into.<\/p>\n<h2 id=\"what-is-a-smart-home\">What Is a Smart Home?<\/h2>\n<p>A smart home consists of many scattered devices that interconnect with each other to follow your orders. For example, a thermostat that measures temperature and turns your air conditioner on or off on demand. It doesn&rsquo;t only make your life easier\u2014it will also reduce your electricity bill.<\/p>","title":"Smart Home Setup Guide: The Bare Minimum without Regrets"},{"content":"Almost a year ago I purchased a Beelink Mini S12 Pro (N100-based mini PC) from AliExpress. Initially I wanted to install only Home Assistant and looked for something simple and cheap. I never thought I would need something more powerful. How wrong I was.\nInitially I planned to install HA OS, but then thought that installing it using a container and docker-compose would give me more room to test and debug. I knew that if something broke, it would be much easier to restore than using HA OS.\nAlso during this time I started working at Intel and my team lost our DevOps engineer to another team, so we were left without DevOps. My manager looked desperately for someone who could take this job, but the issue was that no one among the software developers left on the team had experience in this field. Honestly, I didn&rsquo;t know anything either, and I didn&rsquo;t like it. I always tried to avoid this kind of work. I even refused to submit my resume when Kubernetes knowledge was part of the requirements.\nSo, writing Ansible scripts, writing and debugging Helm charts, installing the observability stack, these were big challenges and no one raised their hand. My weakness is that I can&rsquo;t say no at work. I love my work; when I work on some product I really want it to succeed. So when my manager came to me and asked me to fill this gap, I agreed. And one day I became DevOps.\nIt wasn&rsquo;t easy. Prometheus didn&rsquo;t like to work with mTLS, metrics didn&rsquo;t come, pods were suddenly failing, installation scripts wanted to live their own life, but day by day I learned more and more. After a few months I suddenly understood that I was starting to feel comfortable with what I was doing. I was asking fewer and fewer questions from DevOps engineers on other teams (they rarely got back to me anyway). One day a DevOps engineer from another team even started asking my opinion.\nAll this happened shortly before I eventually had time to start installing Home Assistant. So when I finally got to it, I didn&rsquo;t think twice; I installed k3s first and then installed Home Assistant. And then the rabbit hole opened its gates and I fell inside.\nIf you have Home Assistant you want to have easy access to it, so you need a local DNS server. A pod running AdGuard was added to the cluster. I didn&rsquo;t like that the browser always complained about insecure connections, so I added HTTPS and cert-manager to retrieve Let&rsquo;s Encrypt certificates. I wanted access from the public internet, so I added Cloudflare Tunnel. Then I discovered the *arr stack. Suddenly I didn&rsquo;t need to download another cartoon manually, write it to a flash drive, and then move it to the media streamer; I just installed Jellyfin and it worked. One click and in 10 minutes my daughter can watch the cartoon.\nThen the Monica HQ project was added to remind me of my friends&rsquo; birthdays. A &ldquo;development&rdquo; namespace was dedicated to running Kafka, Redis, PostgreSQL, MySQL, Harbor, MinIO, Keycloak, Jenkins, Vault, and Rathole so I can test everything locally. The observability stack too: Grafana, Loki, Tempo, VictoriaMetrics. I even installed Windows and Ubuntu using KubeVirt to test some binaries on x86 when needed, and it works flawlessly. Even Asterisk when I needed some advanced telephony.\nSometimes I open k9s and look in awe at how this little box can handle all this stuff 24\/7. Over time I added 32GB RAM and a 2TB SSD. My cluster is overcommitted, but it keeps running and running. And honestly, it changed my life, made it easier.\nSo if you have the knowledge or want to learn something new and useful, you should definitely install a Kubernetes server at home. It will be fun, a pleasure, and one more plus on your resume that one day might help you get the dream job.\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/12\/how-mini-pc-and-kubernetes-changed-my-life\/","summary":"<p>Almost a year ago I purchased a <a href=\"https:\/\/s.click.aliexpress.com\/e\/_c2JptJAl\">Beelink Mini S12 Pro<\/a> (N100-based mini PC) from AliExpress. Initially I wanted to install only <a href=\"https:\/\/www.home-assistant.io\/\">Home Assistant<\/a> and looked for something simple and cheap. I never thought I would need something more powerful. How wrong I was.<\/p>\n<p>Initially I planned to install HA OS, but then thought that installing it using a container and <a href=\"https:\/\/docs.docker.com\/compose\/\">docker-compose<\/a> would give me more room to test and debug. I knew that if something broke, it would be much easier to restore than using HA OS.<\/p>","title":"How a Mini PC and Kubernetes Changed My Life"},{"content":"The Problem I was using k9s to check logs on my K3s homelab cluster when I hit this frustrating error:\nto create fsnotify watcher: too many open files stream closed: EOF for development\/drawdb-ddf8d9569-grfff (drawdb) The log stream would just close immediately, and I couldn&rsquo;t see anything. Annoying.\nWhat&rsquo;s Actually Happening Here&rsquo;s the thing - this isn&rsquo;t a problem with k9s on your laptop. It&rsquo;s happening on the K3s node itself. When applications watch files (like development tools, file syncing services, or even k9s monitoring your cluster), Linux uses something called inotify watchers. There&rsquo;s a limit to how many of these you can have.\nOn my server, I checked the limits:\nsysctl fs.inotify.max_user_instances fs.inotify.max_user_watches And got:\nfs.inotify.max_user_instances = 128 fs.inotify.max_user_watches = 248097 That max_user_instances of 128? Way too low for a cluster running multiple apps that watch files.\nThe Fix SSH into your K3s node and create a file \/etc\/sysctl.d\/99-k3s.conf with the following content:\nfs.inotify.max_user_instances=512 fs.inotify.max_user_watches=524288 Then apply the changes:\n# Apply the changes right away sudo sysctl -p \/etc\/sysctl.d\/99-k3s.conf # Verify it worked sysctl fs.inotify.max_user_instances fs.inotify.max_user_watches You should see:\nfs.inotify.max_user_instances = 512 fs.inotify.max_user_watches = 524288 That&rsquo;s it. No need to restart K3s or any pods. Just restart k9s and you&rsquo;re good to go.\nWhy This Works We&rsquo;re increasing two limits:\nmax_user_instances: How many inotify instances a user can create (bumped from 128 to 512) max_user_watches: How many files each instance can watch (bumped to 524288) The fix is permanent because we&rsquo;re creating a config file in \/etc\/sysctl.d\/ that survives reboots.\nThis is a pretty common issue on K3s clusters, especially if you&rsquo;re running development tools or anything that monitors file changes. If you run into this, just bump those limits and you&rsquo;ll be fine.\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/10\/k9s-too-many-open-files\/","summary":"<h2 id=\"the-problem\">The Problem<\/h2>\n<p>I was using k9s to check logs on my K3s homelab cluster when I hit this frustrating error:<\/p>\n<pre tabindex=\"0\"><code>to create fsnotify watcher: too many open files\nstream closed: EOF for development\/drawdb-ddf8d9569-grfff (drawdb)\n<\/code><\/pre><p>The log stream would just close immediately, and I couldn&rsquo;t see anything. Annoying.<\/p>\n<h2 id=\"whats-actually-happening\">What&rsquo;s Actually Happening<\/h2>\n<p>Here&rsquo;s the thing - this isn&rsquo;t a problem with k9s on your laptop. It&rsquo;s happening on the K3s node itself. When applications watch files (like development tools, file syncing services, or even k9s monitoring your cluster), Linux uses something called inotify watchers. There&rsquo;s a limit to how many of these you can have.<\/p>","title":"Fixing k9s 'Too Many Open Files' Error on K3s"},{"content":"Note: This post preserves and references the solution from Ivan Aloneguid&rsquo;s original article. Full credit goes to the original author for this elegant solution.\nQuick Solution If you use IntelliJ IDEA with a dark theme but want a white Markdown preview, here&rsquo;s the simplest fix:\nGo to File \u2192 Settings \u2192 Languages &amp; Frameworks \u2192 Markdown In the &ldquo;Custom CSS&rdquo; field, add: body { filter: invert(1); background: #fff; font-family: &#39;Segoe UI&#39;; font-size: 16px; } img { filter: invert(1); } Click Apply and OK Why This Works The CSS uses filter: invert(1) to flip the dark preview to light. Images are also inverted to preserve their original appearance. You can customize the font family and size to your preference.\nThis gives you the best of both worlds: keep your dark IDE theme for coding while having a comfortable white background for reading Markdown documentation.\nOriginal Source: IntelliJ IDEA - Simplest White Markdown Theme by Ivan Aloneguid\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/09\/intellij-white-markdown-preview\/","summary":"<p><em>Note: This post preserves and references the solution from <a href=\"https:\/\/www.aloneguid.uk\/posts\/2021\/04\/intellij-white-markdown\/\">Ivan Aloneguid&rsquo;s original article<\/a>. Full credit goes to the original author for this elegant solution.<\/em><\/p>\n<h2 id=\"quick-solution\">Quick Solution<\/h2>\n<p>If you use IntelliJ IDEA with a dark theme but want a white Markdown preview, here&rsquo;s the simplest fix:<\/p>\n<ol>\n<li>Go to <strong>File \u2192 Settings \u2192 Languages &amp; Frameworks \u2192 Markdown<\/strong><\/li>\n<li>In the &ldquo;Custom CSS&rdquo; field, add:<\/li>\n<\/ol>\n<div class=\"highlight\"><pre tabindex=\"0\" class=\"chroma\"><code class=\"language-css\" data-lang=\"css\"><span class=\"line\"><span class=\"cl\"><span class=\"nt\">body<\/span> <span class=\"p\">{<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\">  <span class=\"k\">filter<\/span><span class=\"p\">:<\/span> <span class=\"nb\">invert<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">);<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\">  <span class=\"k\">background<\/span><span class=\"p\">:<\/span> <span class=\"mh\">#fff<\/span><span class=\"p\">;<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\">  <span class=\"k\">font-family<\/span><span class=\"p\">:<\/span> <span class=\"s1\">&#39;Segoe UI&#39;<\/span><span class=\"p\">;<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\">  <span class=\"k\">font-size<\/span><span class=\"p\">:<\/span> <span class=\"mi\">16<\/span><span class=\"kt\">px<\/span><span class=\"p\">;<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\"><span class=\"p\">}<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\">\n<\/span><\/span><span class=\"line\"><span class=\"cl\"><span class=\"nt\">img<\/span> <span class=\"p\">{<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\">  <span class=\"k\">filter<\/span><span class=\"p\">:<\/span> <span class=\"nb\">invert<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">);<\/span>\n<\/span><\/span><span class=\"line\"><span class=\"cl\"><span class=\"p\">}<\/span>\n<\/span><\/span><\/code><\/pre><\/div><ol start=\"3\">\n<li>Click <strong>Apply<\/strong> and <strong>OK<\/strong><\/li>\n<\/ol>\n<h2 id=\"why-this-works\">Why This Works<\/h2>\n<p>The CSS uses <code>filter: invert(1)<\/code> to flip the dark preview to light. Images are also inverted to preserve their original appearance. You can customize the font family and size to your preference.<\/p>","title":"IntelliJ IDEA: White Markdown Preview with Dark Theme"},{"content":"\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/09\/my-little-k3s-homelab-cluster\/","summary":"<p><a href=\"\/images\/my-little-home-server.png\"><img alt=\"Image description\" loading=\"lazy\" src=\"\/images\/my-little-home-server.png\"><\/a><\/p>","title":"My little home server :)"},{"content":"I&rsquo;ve been noticing more political content and engagement on LinkedIn lately. While I understand we&rsquo;re living through complex times both in Israel and globally, and people naturally want to share their perspectives, I wanted to offer a gentle reminder about the potential professional risks.\nWhen recruiters and hiring managers review your profile, they inevitably see your activity\u2014including political posts you&rsquo;ve liked or shared. Even the most professional individuals can be unconsciously influenced by views that differ from their own. This bias might affect their perception of you as a candidate, even if they&rsquo;d never admit it to themselves.\nThe same applies once you&rsquo;re employed. Political expressions on professional platforms can subtly impact relationships with colleagues, clients, or leadership\u2014again, often without anyone realizing it&rsquo;s happening.\nThis isn&rsquo;t about suppressing free speech or avoiding important conversations. It&rsquo;s about recognizing that LinkedIn is primarily a professional space, and political content here rarely advances our career goals.\nI&rsquo;m sharing this as much as a reminder to myself as to others\u2014I&rsquo;ve made this mistake too and learned from it. In today&rsquo;s polarized world, protecting our professional relationships sometimes means choosing when and where to engage in political discourse.\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/09\/keep-politics-out-linkedin\/","summary":"<p>I&rsquo;ve been noticing more political content and engagement on LinkedIn lately. While I understand we&rsquo;re living through complex times both in Israel and globally, and people naturally want to share their perspectives, I wanted to offer a gentle reminder about the potential professional risks.<\/p>\n<p>When recruiters and hiring managers review your profile, they inevitably see your activity\u2014including political posts you&rsquo;ve liked or shared. Even the most professional individuals can be unconsciously influenced by views that differ from their own. This bias might affect their perception of you as a candidate, even if they&rsquo;d never admit it to themselves.<\/p>","title":"A Professional Reminder: Keep Politics Out of LinkedIn"},{"content":"Hi! I&rsquo;m Anatoly Tarnavsky, a Senior Full Stack Engineer with 10+ years of experience building scalable distributed systems and cloud-native applications. Previously worked at Intel as a Senior Backend Developer, focusing on AI\/ML infrastructure and Kubernetes-based solutions. You can download my resume | write me an email\nWhat I do Backend &amp; Full Stack Development - Node.js, Go, React, Vue, TypeScript Cloud &amp; DevOps - Kubernetes, AWS, Docker, GitOps with ArgoCD AI\/ML Infrastructure - Building platforms for LLM models and machine learning workloads Observability &amp; Monitoring - Prometheus, OpenTelemetry, distributed systems debugging Homelab Engineering - Production-ready K3S cluster with automated deployments Professional Background I&rsquo;ve worked at companies like Intel, OurCrowd, and IBM, developing everything from payment processing systems to AI model serving platforms. My experience spans microservices architecture, data visualization tools, and enterprise-scale infrastructure.\nRecent Work At Intel, I developed MaaS (Model as a Service) platforms using Go and Kubernetes, providing OpenAI-compatible APIs for running open-source LLM models on specialized hardware accelerators.\nThis Blog This blog is built with:\nHugo - Static site generator Kubernetes - Running on my homelab k3s cluster ArgoCD - GitOps deployment Cloudflare Tunnel - Accessible from outside via Cloudflare Tunnel Vault - Secrets management Feel free to reach out if you have questions or want to connect!\n","permalink":"https:\/\/anatoly.dev\/pages\/about\/","summary":"<p>Hi! I&rsquo;m Anatoly Tarnavsky, a Senior Full Stack Engineer with 10+ years of experience building scalable distributed systems and cloud-native applications. Previously worked at Intel as a Senior Backend Developer, focusing on AI\/ML infrastructure and Kubernetes-based solutions. You can <a href=\"\/Anatoly_Tarnavsky_CV.pdf\">download my resume<\/a> | <a href=\"mailto:anatolyt@gmail.com\">write me an email<\/a><\/p>\n<h2 id=\"what-i-do\">What I do<\/h2>\n<ul>\n<li><strong>Backend &amp; Full Stack Development<\/strong> - Node.js, Go, React, Vue, TypeScript<\/li>\n<li><strong>Cloud &amp; DevOps<\/strong> - Kubernetes, AWS, Docker, GitOps with ArgoCD<\/li>\n<li><strong>AI\/ML Infrastructure<\/strong> - Building platforms for LLM models and machine learning workloads<\/li>\n<li><strong>Observability &amp; Monitoring<\/strong> - Prometheus, OpenTelemetry, distributed systems debugging<\/li>\n<li><strong>Homelab Engineering<\/strong> - Production-ready K3S cluster with automated deployments<\/li>\n<\/ul>\n<h2 id=\"professional-background\">Professional Background<\/h2>\n<p>I&rsquo;ve worked at companies like Intel, OurCrowd, and IBM, developing everything from payment processing systems to AI model serving platforms. My experience spans microservices architecture, data visualization tools, and enterprise-scale infrastructure.<\/p>","title":"About"},{"content":"I may not be the smartest person in the room, but after working closely with Claude and ChatGPT over the past few months, I want to share some observations. AI won&rsquo;t replace programmers\u2014at least not anytime soon.\nFor AI to truly replace programmers, one of two conditions must be met:\nAccept that our codebases will eventually become completely unreadable to humans. Once no human can maintain the code, all bugs must be fixed by AI. Inevitably, the AI will encounter a bug it can&rsquo;t solve, and we&rsquo;ll need human programmers to refactor and essentially rewrite everything from scratch.\nAchieve AGI (Artificial General Intelligence). Much smarter people than me are working on this and debating when it might happen, but nobody knows for certain.\nRegarding scenario two: if AGI arrives, it will transform our entire world so fundamentally that whether programmers exist will be the least of our concerns.\nAs for scenario one: I predict some brave companies will attempt this approach, but they&rsquo;ll ultimately fail. I understand it might seem unwise to question some of the world&rsquo;s wealthiest tech leaders and their AI ventures, but I suspect this is more about maintaining hype and attracting customers. Remember, despite years of promises, fully self-driving cars still aren&rsquo;t widely available.\nAI&rsquo;s true strength lies in collaboration. Remember the 80\/20 rule? AI can handle 80% of programming tasks in seconds, but humans are still essential for the remaining 20%.\nThe definition of a good programmer is already evolving. Beyond traditional skills like reading documentation, problem-solving, and quick thinking, we now need to master AI collaboration\u2014learning to define our requirements clearly, set appropriate boundaries, and effectively communicate with AI systems.\nRather than being replaced, programmers are becoming team leaders where the rest of the team consists of AI agents. This shift represents an evolution in our role, not an elimination of it.\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/08\/ai-wont-replace-programmers\/","summary":"<p>I may not be the smartest person in the room, but after working closely with Claude and ChatGPT over the past few months, I want to share some observations. AI won&rsquo;t replace programmers\u2014at least not anytime soon.<\/p>\n<p>For AI to truly replace programmers, one of two conditions must be met:<\/p>\n<ol>\n<li>\n<p>Accept that our codebases will eventually become completely unreadable to humans. Once no human can maintain the code, all bugs must be fixed by AI. Inevitably, the AI will encounter a bug it can&rsquo;t solve, and we&rsquo;ll need human programmers to refactor and essentially rewrite everything from scratch.<\/p>","title":"AI Won't Replace Programmers\u2014At Least Not Anytime Soon"},{"content":"Just installed and played a little bit with Claude Code, and it&rsquo;s disturbingly good. I played with it for a few hours\u2014it took me that time to write an MCP server from scratch, create a simple OAuth proxy, debug it, and then perform some refactoring to make it modular and maintainable. Yes, without human touch it writes spaghetti code that works but is barely maintainable. However, the nature of programming is changing; you will need to read more than write. But without writing, you won&rsquo;t be able to read and understand. I think developers with many years of experience who know how to write code and are able to adopt new AI tools will be invaluable, because one such developer can easily replace a small team. But for newcomers, it will be extremely difficult to gain the required experience to work productively with AI tools.\nYou can take a look at it here: here.\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/08\/claude-code-first-impressions\/","summary":"<p>Just installed and played a little bit with Claude Code, and it&rsquo;s disturbingly good. I played with it for a few hours\u2014it took me that time to write an MCP server from scratch, create a simple OAuth proxy, debug it, and then perform some refactoring to make it modular and maintainable. Yes, without human touch it writes spaghetti code that works but is barely maintainable. However, the nature of programming is changing; you will need to read more than write. But without writing, you won&rsquo;t be able to read and understand.\nI think developers with many years of experience who know how to write code and are able to adopt new AI tools will be invaluable, because one such developer can easily replace a small team. But for newcomers, it will be extremely difficult to gain the required experience to work productively with AI tools.<\/p>","title":"Claude Code: First Impressions - Disturbingly Good"},{"content":"You know what the biggest appreciation for an employee is? It&rsquo;s not a title, not a good review, and not even a salary raise.\nThe best appreciation comes when your old teammates or managers call you to join them at their new company. When there are no company rules involved, no need to be nice just to keep good work relationships\u2014when your former manager needs to hire someone and remembers you, decides to message or call you to join their new team.\nThis is the highest appreciation you can get. When someone chooses you not because they have to, but because they want to work with you again.\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/08\/highest-appreciation-for-employees\/","summary":"<p>You know what the biggest appreciation for an employee is? It&rsquo;s not a title, not a good review, and not even a salary raise.<\/p>\n<p>The best appreciation comes when your old teammates or managers call you to join them at their new company. When there are no company rules involved, no need to be nice just to keep good work relationships\u2014when your former manager needs to hire someone and remembers you, decides to message or call you to join their new team.<\/p>","title":"The Highest Appreciation an Employee Can Receive"},{"content":"No, AI won&rsquo;t take jobs from us, not yet. Claude struggled to write a script to unseal the vault in my k8s cluster until I split the job into small chunks and guided it step by step through what needed to be done.\n","permalink":"https:\/\/anatoly.dev\/posts\/2025\/08\/ai-struggles-with-complex-tasks\/","summary":"<p>No, AI won&rsquo;t take jobs from us, not yet. Claude struggled to write a script to unseal the vault in my k8s cluster until I split the job into small chunks and guided it step by step through what needed to be done.<\/p>","title":"No, AI won\u2019t take jobs from us, not yet."},{"content":"I built an MCP server that connects AI assistants to Anki flashcards. It&rsquo;s written in TypeScript with NestJS and works in two modes - local STDIO for Claude Desktop and HTTP streaming for web-based AI tools. The server lets you review cards, manage decks, and work with notes just by chatting with your AI assistant. You can read the full documentation at ankimcp.ai and check out the source code at github.com\/ankimcp\/anki-mcp-server.\n","permalink":"https:\/\/anatoly.dev\/projects\/ankimcp\/","summary":"<p>I built an MCP server that connects AI assistants to Anki flashcards. It&rsquo;s written in TypeScript with NestJS and works in two modes - local STDIO for Claude Desktop and HTTP streaming for web-based AI tools. The server lets you review cards, manage decks, and work with notes just by chatting with your AI assistant. You can read the full documentation at <a href=\"https:\/\/ankimcp.ai\">ankimcp.ai<\/a> and check out the source code at <a href=\"https:\/\/github.com\/ankimcp\/anki-mcp-server\">github.com\/ankimcp\/anki-mcp-server<\/a>.<\/p>","title":"AnkiMCP"},{"content":"A production-ready Model Context Protocol (MCP) server framework with robust features for secure, scalable communication. This TypeScript-based starter kit provides everything needed to build and deploy MCP servers with enterprise-grade authentication, logging, and security capabilities. Supports both HTTP\/SSE and stdio transports with easy Docker deployment.\n","permalink":"https:\/\/anatoly.dev\/projects\/mcp-server-starter\/","summary":"<p>A production-ready <a href=\"https:\/\/github.com\/anatoly314\/mcp-server-starter\">Model Context Protocol (MCP) server framework<\/a> with robust features for secure, scalable communication. This TypeScript-based starter kit provides everything needed to build and deploy MCP servers with enterprise-grade authentication, logging, and security capabilities. Supports both HTTP\/SSE and stdio transports with easy Docker deployment.<\/p>","title":"MCP Server Starter"},{"content":"Building and maintaining a complete homelab infrastructure using Kubernetes, GitOps principles, and modern DevOps practices. This project includes automated deployments, monitoring, security, and various self-hosted applications.\n","permalink":"https:\/\/anatoly.dev\/projects\/homelab\/","summary":"<p>Building and maintaining a complete homelab infrastructure using Kubernetes, GitOps principles, and modern DevOps practices. This project includes automated deployments, monitoring, security, and various self-hosted applications.<\/p>","title":"Homelab Infrastructure"},{"content":" Acknowledgements\nThis article was originally written in Russian by Grigory Biziukin and was published on \u041f\u043e\u043b\u043d\u043e\u0435 \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u0435 \u0430\u0441\u0438\u043d\u0445\u0440\u043e\u043d\u043d\u043e\u0441\u0442\u0438 \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435 on 28\/02\/2023. I would like to thank Grigory Biziukin for creating such informative and insightful content. I have made every effort to accurately translate the content while maintaining the author&rsquo;s original message and intent. However, any errors in translation are solely my own. I hope that my translation will allow a wider audience to access and appreciate this valuable content, and I encourage readers to visit the original publication or website to read more of Grigory Biziukin&rsquo;s work.\nThere are numerous articles, documents, and books written about the asynchrony of JavaScript. However, the information is widely dispersed throughout the internet, making it difficult to quickly and fully understand the various aspects and form a complete picture in your mind. What is lacking is a comprehensive guide. This is precisely the need that I want to address with my article.\nTable of Contents Event Loop Tasks, Ticks, and Web API Task Queue 16.6 milliseconds per task Handling large tasks Microtasks requestAnimationFrame requestIdleCallback Comparison of queues Event loop in Node.js Callback Functions Callback Hell Don&rsquo;t Release Zalgo Tight Coupling The Trust Issue Promises Promise chains and error propagation Implicit behavior Returning a new promise Hidden try\/catch Thenable objects Static methods Promise.all Promise.race Promise.any Promise.allSettled Promisification Promises or callback functions? Coroutines Async\/await Top-level await and asynchronous modules Error handling Not all await is equally useful Conclusion Event Loop To run a website, the browser allocates a single thread that must simultaneously perform two important tasks: execute code and update the interface. However, a single thread can only perform one action at a time. Therefore, the thread performs these tasks sequentially to create the illusion of parallel execution. This is the event loop.\nThe call stack is where code execution takes place. When a function calls another function, its own execution is paused until the called function completes, forming a call stack. Once all the operations in the stack are executed and it becomes empty, the event loop can either add more code to the stack for execution or update the user interface.\nThe browser engine is responsible for updating the user interface. This process usually consists of four steps: style, layout (reflow), paint, and composite. During the style step, the browser recalculates the style changes caused by JavaScript operations and calculates media queries. Layout recalculates the page&rsquo;s geometry, which involves computing layers, calculating the mutual arrangement of elements, and their mutual influence. During the paint step, the engine renders the elements and applies styles that only affect their appearance, such as color, background, etc. Composite applies the remaining specific styles, usually transformations that occur in a separate layer.\nTo optimize a web page, it can be helpful to understand when the browser performs or skips certain operations. The browser may skip unnecessary operations to improve performance. By understanding when the browser skips or executes specific steps, you can optimize your web page accordingly.\nThe first operation in the event loop can be either updating the interface or executing code. If a website uses a synchronous script tag, the engine will most likely execute it before rendering the first user interface frame. However, if we load scripts asynchronously using async or defer, there\u2019s a high probability that the browser will render the user interface before loading JavaScript.\nThe asynchronous script loading option is more preferable because the initial bundle is usually quite large. Until it is fully executed, the user will see a white screen because the event loop will not be able to render the user interface. Even with asynchronous loading, it is recommended to split JavaScript code into separate bundles and load only the essentials first, because the event loop is very sequential: it fully executes all the code in the call stack and only then moves on to updating the interface. If there is too much code in the call stack, the interface will be updated with a significant delay. The user will have the impression that the site is lagging. If an infinite loop is written, the browser will keep executing the code over and over, and the interface update will never happen, so the page will simply freeze and stop responding to user actions.\nThe call stack will execute both the developer-written code and the default built-in code responsible for interacting with the page. Thanks to the built-in code, scrolling, selection, animations, and other features work, for which JavaScript might seem unnecessary. The call stack will execute built-in scripts even when JavaScript is disabled in the browser. For example, you can open an empty about:blank page without JavaScript, perform a few clicks, and see that the call stack has executed the code responsible for event handling.\nTasks, Ticks, and Web API A task in JavaScript refers to a piece of code that is executed within the call stack. A tick, on the other hand, represents a single iteration of the event loop, during which tasks in the call stack are processed. Web API refers to properties and methods in the global Window object.\nWeb API methods can work either synchronously or asynchronously: the former will execute in the current tick, while the latter will execute in one of the following ticks.\nA good example of synchronous calls is the DOM manipulation:\nconst button = document.createElement(&#39;button&#39;); document.body.appendChild(button); button.textContent = &#39;OK&#39;; Creating an element, inserting it into the DOM, and setting properties are synchronous operations that execute in the current tick. Therefore, it doesn\u2019t matter when we set the text for the button - before inserting it into the DOM or after. The browser will update the interface only after completing all synchronous operations, so the user will immediately see the up-to-date interface state.\nWhen we write asynchronous code, we ensure that the task will be executed in the next tick. It can start either before or after the interface is updated. For example, when the event loop needs to perform the next task, it can either execute it immediately after the previous one or update the interface first and then execute the next task. This distinction is not particularly important for developers. It\u2019s essential to understand that an asynchronous task will be executed at some point in the future.\nA good example of an asynchronous call is requesting data from a server. A callback function describes a task that will be executed at some point in the future after receiving the data:\nfetch(&#39;\/url&#39;).then((response) =&gt; { \/\/ will be executed at some point in the future }) The browser subsystem responsible for network operations will execute the request in a separate thread, working independently. While the request is being processed in the background, the event loop can update the interface and execute code. Once the data has been successfully loaded, the task we described through the callback function will be ready to execute in one of the following ticks of our main task cycle.\nThere may be multiple tasks ready for execution after asynchronous calls. Therefore, a special queue exists to transfer them to the call stack for execution.\nTask Queue Tasks enter the queue through the asynchronous browser API. First, an asynchronous operation is performed somewhere in a separate thread, and after its completion, a task ready for execution is added to the call stack.\nUnderstanding this concept, one can examine a peculiarity of timers in JavaScript, which are also part of the asynchronous API.\nsetTimeout(() =&gt; { \/\/ enqueue a task after 1000 ms }, 1000) When we start a timer, the engine begins counting down in a separate thread, and upon readiness, the task is added to the queue. One might think that the timer will execute after one second, but in reality, this is not the case. In the best-case scenario, it will be added to the task queue after one second, and the code will only be executed after the queue reaches it.\nThe same principle applies to event handlers. Each time we register an event handler, we attach a task to it, which will be added to the queue after the event occurs:\ndocument.body.addEventListener(&#39;click&#39;, () =&gt; { \/\/ enqueue a task when the event occurs }) 16.6 milliseconds per task To make websites fast and responsive, the browser needs to create the illusion that it is simultaneously executing user code and updating the interface. However, since the event loop operates strictly sequentially, the browser has to quickly switch between tasks so the user doesn\u2019t notice anything.\nTypically, monitors refresh the image at a rate of 60 frames per second, so the event loop tries to execute code and update the interface at the same speed, which means a task takes 16.6 milliseconds to complete. If our code runs faster, the browser will simply update the display more frequently. But if the code runs slowly, the frame rate will start to decrease, and the user will feel like the website is lagging.\nFor most scenarios, 16.6 milliseconds is quite sufficient. However, sometimes heavy computations are required on the client side, which may take much more time. There are special techniques for such cases.\nHandling large tasks There are two ways to optimize large tasks: either by breaking them down into subtasks and executing them in different ticks, or by moving the computation to a separate thread.\nTo execute something in the next tick, for example, you can use setTimeout with a minimal delay.\nfunction longTask() { toDoSomethingFirst() setTimeout(() =&gt; { toDoSomethingLater() }, 0) } There is also an experimental function called postTask, which is part of the Scheduling API and currently only available in Chrome and Edge. It allows you not only to execute tasks asynchronously to unload the main thread but also to set priorities for them. You can read more about this in Jeremy Wagner\u2019s article \u201cOptimize long tasks\u201d.\nTo launch a separate thread, you can use the Web Worker API:\nconst worker = new Worker(&#39;worker.js&#39;) worker.addEventListener(&#39;message&#39;, () =&gt; { \/\/ receive data }) \/\/ send data worker.postMessage(&#39;any data&#39;) A separate thread is created for the web worker, where calculations will take place independently of the main event loop. Once the calculations are completed, the worker can send data to the main event loop using postMessage, and the task associated with processing the data will be added to the queue and executed in one of the following ticks. However, web workers have limitations. For example, you cannot work with the DOM inside a worker, but computational tasks will work.\nIf the calculation data is needed within other tabs from the same origin, you can use a SharedWorker instead of a regular worker. Additionally, for some tasks, a ServiceWorker might be useful, but that\u2019s another story. You can read more about workers, for example, here.\nAside from web workers, there is another, less obvious way to create a separate thread \u2013 opening a window or frame on a different domain to violate the same-origin policy. Then the window or frame will have its own independent event loop, which can perform some work and interact with the main window, just like a web worker, using the postMessage mechanism. This is quite a specific behavior that may look different in different browsers. You can test it, for example, using a demo from Stack Overflow.\nMicrotasks Microtasks are tasks that are stored in a special separate queue.\nTasks enter this queue when using promises, asynchronous functions, built-in calls to queueMicrotask, or Observer APIs.\nPromise.resolve().then(() =&gt; { \/\/ microtask }) async function() { \/\/ microtask } queueMicrotask(() =&gt; { \/\/ microtask }) new MutationObserver(() =&gt; { \/\/ microtask }).observe(document.body, { childList: true, subtree: true }) The microtask queue has a higher priority than the regular task queue, and microtasks are executed before regular tasks. A notable feature of the microtask queue is that the event loop will continue to execute microtasks until the queue is empty. This ensures that all tasks in the queue have access to a consistent DOM state.\nThis behavior can be clearly seen in the example with promises, where each subsequent handler has access to the same DOM state (at the time of setting the promise):\nconst div = document.createElement(&#39;div&#39;) document.body.appendChild(div) let height = 0 function changeDOM() { height += 1 div.style.height = `${height}px` requestAnimationFrame(changeDOM) } requestAnimationFrame(changeDOM) setTimeout(() =&gt; { const promise = Promise.resolve() .then(() =&gt; { console.log(div.style.height) }) .then(() =&gt; { console.log(div.style.height) }) promise .then(() =&gt; { console.log(div.style.height) }) }, 1000) \/\/ all console.log will output the same value There is a wonderful visual site, JavaScript Visualizer 9000, where you can explore in more detail how task queues and microtask queues work. Additionally, I recommend a good article JavaScript Visualized: Promises &amp; Async\/Await that explains promises.\nrequestAnimationFrame requestAnimationFrame (or abbreviated as rAF) allows you to execute JavaScript code right before updating the interface. Emulating such behavior with other methods, like timers, is almost impossible.\nThe main purpose of requestAnimationFrame is to provide smooth JavaScript animations, but it is not often used since animations are easier and more efficient to implement with CSS. Nevertheless, it occupies its own rightful place in the event loop.\nThere may be multiple tasks that need to be executed before updating the next frame, so requestAnimationFrame has its own separate queue.\nTasks from the queue are executed once before updating the interface in the order they were added:\nrequestAnimationFrame(() =&gt; { console.log(&#39;one&#39;) }) requestAnimationFrame(() =&gt; { console.log(&#39;two&#39;) }) requestAnimationFrame(() =&gt; { console.log(&#39;three&#39;) }) \/\/ one two three You can create a recurring task that will execute again and again using a recursive function. Moreover, if you need to cancel the execution for some reason, you can do it using cancelAnimationFrame. However, make sure to pass the current identifier to it, as each rAF call creates a new requestId.\nlet requestId function animate() { requestId = requestAnimationFrame(animate) } requestId = requestAnimationFrame(animate) setTimeout(() =&gt; { \/\/ cancel animations after some time cancelAnimationFrame(requestId) }, 3000) There is a small but useful article on the topic of requestAnimationFrame in Flavio Copes\u2019 blog.\nrequestIdleCallback requestIdleCallback (or abbreviated as rIC) adds tasks to yet another (fourth) queue, which will be executed during the browser\u2019s idle period when there are no more priority tasks from other queues.\nfunction sendAnalytics() { \/\/ send data for analytics } requestIdleCallback(sendAnalytics, { timeout: 2000 }); As a second argument, you can specify a timeout, and if the task is not completed within the specified number of milliseconds, it will be added to the regular queue and then executed in the order of the general queue.\nSimilar to requestAnimationFrame, to regularly add a task to the queue, you will need to write a recursive function, and to stop it - pass the current identifier to cancelIdleCallback.\nIn contrast to the other queues discussed earlier, requestIdleCallback is still partly an experimental API, with support missing in Safari. In addition, this function has a number of limitations, making it convenient to use only for small non-priority tasks without interaction with the DOM, for example, for sending analytical data. You can read more about requestIdleCallback in Paul Lewis\u2019s material \u201cUsing requestIdleCallback\u201d.\nComparison of queues The microtask queue is the highest priority queue, with code execution starting from it. The browser continues to work with this queue until there are tasks in it, no matter how long it takes.\nFrom the task queue, the engine usually executes one or several tasks, trying to fit within 16.6 milliseconds. As soon as the allotted time passes, the engine will go to update the interface, even if there are tasks left in the queue. It will return to them on the next loop of the event cycle.\nrequestAnimation will execute all tasks from its queue because it guarantees code execution before updating the interface. However, if someone adds new tasks to the queue during execution, they will be performed on the next loop.\nWhen the idle time comes and there are no more priority tasks in other queues, one or several requestIdleCallback tasks will be executed. Thus, this queue is somewhat similar to the task queue but with a lower priority.\nInteraction with queues occurs through:\ntasks - timers, events (including postMessage processing); microtasks - promises, asynchronous functions, Observer API, queueMicrotask; requestAnimationFrame, requestIdleCallback - corresponding API calls. Event loop in Node.js In Node.js, the event loop works in a similar way: first, a task is executed, then you need to look into the queue for the next one. However, the set of queues is different, and there are no stages related to updating the interface because the code runs on the server. You can read more about event loops in Node.js in a series of articles written by Deepal Jayasekara. For a quick understanding of setImmediate and process.nextTick, there is a good explanation on Stack Overflow.\nTranslator&rsquo;s notice: There&rsquo;s a really good video which explains how the event loop works here: What the heck is the event loop anyway? | Philip Roberts | JSConf EU Callback Functions This is a convenient and simple way to interact with asynchronous APIs, but if not handled carefully, many problems can arise.\nCallback Hell Callback hell is the most common issue mentioned when discussing the drawbacks of callback functions.\nThe sequence of asynchronous calls using callback functions becomes similar to the pyramid of doom.\nfetchToken(url, (token) =&gt; { fetchUser(token, (user) =&gt; { fetchRole(user, (role) =&gt; { fetchAccess(role, (access) =&gt; { fetchReport(access, (report) =&gt; { fetchContent(report, (content) =&gt; { \/\/ Welcome to Callback Hell }) }) }) }) }) }) One might think that this is the main drawback of callback functions, but the problems with them are just beginning.\nDon&rsquo;t Release Zalgo The challenge with callback functions is that it&rsquo;s not always evident whether they will be executed synchronously or asynchronously. This ambiguity can impact the logic of the code and may require developers to examine the function&rsquo;s implementation to be certain of its behavior. Consequently, this adds complexity to the debugging process.\nsyncOrAsync(() =&gt; { \/\/ how is the code executed? }) \/\/ synchronous implementation function syncOrAsync(callback) { callback() } \/\/ asynchronous implementation function syncOrAsync(callback) { queueMicrotask(callback) } In niche circles, this problem is widely known as the Zalgo monster issue, which is better not to release.\nTight Coupling Tight coupling refers to the issue where one part of the code is heavily dependent on another part, particularly when handling sequential asynchronous operations.\nfirstStep((error, data) =&gt; { if (error) { \/\/ cancel step #1 } secondStep((error, data) =&gt; { if (error) { \/\/ cancel step #2, then #1 } }) }) When managing multi-step processes, error handling becomes more complex. If an error occurs in step #1, it can be handled directly. However, if an error occurs in step #2, you may need to cancel both step #2 and step #1 to properly handle the error. As the number of steps increases, error handling becomes increasingly challenging.\nThe Trust Issue Inversion of control refers to the practice of passing your code to a library or framework developed by others, allowing them to manage the control flow and execution of your code.\nimport { thirdPartyCode } from &#39;third-party-package&#39; thirdPartyCode(() =&gt; { \/\/ inversion of control }) We rely on our task being called as it should, but everything may not go as expected. Another library might call the function too early or too late, do it too frequently or rarely, swallow errors and exceptions, pass incorrect arguments, or not call our function at all.\nGiven these challenges, one might assume that handling asynchrony through callback functions is inherently problematic. To some extent, this is true. However, promises provide a powerful solution to address these concerns and simplify asynchronous programming.\nPromises Promises can be compared to order numbers at a restaurant. When we place an order, we receive an order number instead of the food itself. Two possible scenarios can occur: first, the order will be successfully prepared and served at the pick-up counter after some time; second, something could go wrong, such as running out of ingredients, prompting the restaurant employee to inform us that our order cannot be fulfilled. In this case, they would offer a refund or an alternative.\nPromises are created using the Promise constructor, which must be instantiated with the new keyword. The constructor accepts a single argument: a callback function with two parameters, resolve and reject. Within the callback function, an asynchronous operation is carried out. Depending on the outcome of the operation, either the resolve or reject function is called, setting the Promise&rsquo;s state to fulfilled or rejected, respectively.\nThis is how a Promise can be set to either fulfilled or rejected:\n\/\/ set Promise to fulfilled const resolvedPromise = new Promise((resolve, reject) =&gt; { setTimeout(() =&gt; { resolve(&#39;^_^&#39;) }, 1000) }) \/\/ set Promise to rejected const rejectedPromise = new Promise((resolve, reject) =&gt; { setTimeout(() =&gt; { reject(&#39;O_o&#39;) }, 1000) }) After a Promise is set, the result can be obtained through the then method:\nresolvedPromise.then((value) =&gt; { console.log(value) \/\/ ^_^ }) A rejection can be handled either through the second parameter in then or through catch:\nrejectedPromise.then( (value) =&gt; { \/\/ ... ignored }, (error) =&gt; { console.log(error) \/\/ O_o } ) rejectedPromise.catch((error) =&gt; { console.log(error) \/\/ O_o }) The value of a Promise is set once and cannot be changed:\nconst promise = new Promise((resolve, reject) =&gt; { resolve(&#39;^_^&#39;) reject(&#39;O_o&#39;) \/\/ will not affect the state of the Promise }) promise.then((value) =&gt; { console.log(value) \/\/ ^_^ }) promise.then((value) =&gt; { console.log(value) \/\/ ^_^ }) For convenience, you can use the static methods, the Promise.resolve and Promise.reject constructor functions, which create an already-set Promise:\nPromise.resolve(&#39;^^&#39;).then((value) =&gt; { console.log(value) \/\/ ^^ }) Promise.reject(&#39;O_o&#39;).catch((error) =&gt; { console.log(error) \/\/ O_o }) Promises also have a finally method, which is executed regardless of the promise&rsquo;s success or failure. This can be compared to baking a dish in an oven: whether the dish is cooked perfectly or gets burnt, the oven still needs to be turned off afterward.\nPromise.resolve(&#39;^^&#39;).finally(() =&gt; { \/\/ do something }).then((value) =&gt; { console.log(value) \/\/ ^^ }) Promise.reject(&#39;O_o&#39;).finally(() =&gt; { \/\/ do something }).catch((error) =&gt; { console.log(error) \/\/ O_o }) Promise chains and error propagation The main benefit of promises is that we can build chains of asynchronous operations with them:\nPromise.resolve(&#39;^&#39;) .then((value) =&gt; { return value + &#39;_&#39; }) .then((value) =&gt; { return value + &#39;^&#39; }) .then((value) =&gt; { console.log(value) \/\/ ^_^ }) If an error occurs somewhere, the rejection will skip the fulfillment handlers and reach the nearest rejection handler, after which the chain will continue to operate normally:\nPromise.resolve() .then(() =&gt; { return Promise.reject(&#39;O_o&#39;) }) .then(() =&gt; { \/\/ all fulfillment handlers will be skipped }) .catch((error) =&gt; { console.log(error) \/\/ O_o }) .then(() =&gt; { \/\/ continue to execute the chain normally }) You can also return a value inside catch, and it will be processed in the chain just the same:\nPromise.reject(&#39;O_o&#39;) .catch((error) =&gt; { console.log(error) \/\/ O_o return &#39;^_^&#39; }) .then((value) =&gt; { console.log(value) \/\/ ^_^ }) If the chain ends with the error still unhandled, the unhandledrejection event will be triggered. You can subscribe to this event to track unhandled errors inside promises:\nwindow.addEventListener(&#39;unhandledrejection&#39;, (event) =&gt; { console.log(&#39;Unhandled Promise error. Shame on you!&#39;) console.log(event) \/\/ PromiseRejectionEvent console.log(event.reason) \/\/ O_o }) It&rsquo;s crucial to recognize that error handling functions properly only when the promise chain remains uninterrupted. If the return statement is omitted and a rejected promise is created, the following catch block will be unable to handle the error:\nPromise.resolve() .then(() =&gt; { Promise.reject(&#39;O_o&#39;) }) .catch(() =&gt; { \/\/ will be skipped because return is not specified \/\/ UnhandledPromiseRejection will be thrown }) Implicit behavior Promises have two implicit features. First, the then and catch methods always return a new promise. Second, they internally catch any errors and, if something goes wrong, return a promise set to reject with the reason for the error.\nReturning a new promise Each call to then or catch creates a new promise, the value of which is either undefined or explicitly set via return.\nThanks to this, instead of creating temporary variables, you can immediately make a convenient chain of calls:\n\/\/ you can do it like this: const one = Promise.resolve(&#39;^&#39;) const two = one.then((value) =&gt; { return value + &#39;_&#39; }) const three = two.then((value) =&gt; { return value + &#39;^&#39; }) three.then((value) =&gt; { console.log(value) \/\/ ^_^ }) \/\/ but this is much better: Promise.resolve(&#39;^&#39;) .then((value) =&gt; { return value + &#39;&#39; }) .then((value) =&gt; { return value + &#39;^&#39; }) .then((value) =&gt; { console.log(value) \/\/ ^^ }) At the same time, if you return a promise, its value will be unwrapped, and everything will work exactly the same.\nPromise.resolve() .then(() =&gt; { return Promise.resolve(&#39;^^&#39;) }) .then((value) =&gt; { console.log(value) \/\/ ^^ }) Because of this, you can avoid nested promises and always write code with a single level of nesting:\n\/\/ you can do it like this: Promise.resolve(&#39;^&#39;) .then((value) =&gt; { return Promise.resolve(value + &#39;_&#39;) .then((value) =&gt; { return Promise.resolve(value + &#39;^&#39;) .then((value) =&gt; { console.log(value) \/\/ ^_^ }) }) }) \/\/ but this is much better: Promise.resolve(&#39;^&#39;) .then((value) =&gt; { return Promise.resolve(value + &#39;_&#39;) }) .then((value) =&gt; { return Promise.resolve(value + &#39;^&#39;) }) .then((value) =&gt; { console.log(value) \/\/ ^_^ }) Hidden try\/catch Another feature of promises is related to error handling. Callback functions passed to promise methods are wrapped in try\/catch. If something goes wrong, the try\/catch will catch the error and set it as the reason for the promise&rsquo;s rejection:\nPromise.resolve() .then(() =&gt; { undefined.toString() }) .catch((error) =&gt; { console.log(error) \/\/ TypeError: Cannot read property &#39;toString&#39; of undefined }) This is the same as manually writing this code:\nPromise.resolve() .then(() =&gt; { try { undefined.toString() } catch (error) { return Promise.reject(error) } }) .catch((error) =&gt; { console.log(error) \/\/ TypeError: Cannot read property &#39;toString&#39; of undefined }) Thus, within promises, you can do without try\/catch because promises will do it for us. The main thing is to properly handle the reason for rejection in catch.\nThenable objects These are objects that have a then method:\nconst thenable = { then (fulfill) { fulfill(&#39;@_@&#39;) } } Most likely, these are promise polyfills before ES6. Promises will unwrap such objects and then wrap them in full-fledged ES6 promises. This is how resolve, Promise.resolve, then, and catch work.\nPromise.resolve(thenable) .then((value) =&gt; { console.log(value) \/\/ @_@ }) new Promise((resolve) =&gt; { resolve(thenable) }).then((value) =&gt; { console.log(value) \/\/ @_@ }) Promise.resolve() .then(() =&gt; { return thenable }) .then((value) =&gt; { console.log(value) \/\/ @_@ }) Thanks to this, compatibility with code written before ES6 is ensured:\nconst awesomeES6Promise = Promise.resolve(thenable) awesomeES6Promise.then((value) =&gt; { console.log(value) \/\/ @_@ }) There is one peculiarity: if you pass a regular promise to Promise.resolve, it will not create a new promise and will return the original promise unchanged. However, when using the resolve callback inside a Promise constructor or the then and catch methods on a promise, they will always create and return a new promise that depends on the resolution of the previous promise.\nconst thenable = { then (fulfill) { fulfill(&#39;@_@&#39;) } } const promise = Promise.resolve(&#39;@_@&#39;) const resolvedThenable = Promise.resolve(thenable) const resolvedPromise = Promise.resolve(promise) console.log(thenable === resolvedThenable) \/\/ false console.log(promise === resolvedPromise) \/\/ true But the most interesting part is the behavior of reject and Promise.reject, which work completely differently. If you pass any object to them, including a promise, they will simply return it as the reason for rejection:\nconst promise = Promise.resolve(&#39;@_@&#39;) Promise.reject(promise) .catch((value) =&gt; { console.log(value) \/\/ Promise {&lt;fulfilled&gt;: &#34;@_@&#34;} }) Static methods Promises have six useful static methods. We have already covered two of them - Promise.resolve and Promise.reject. Let&rsquo;s take a look at the other four.\nFor clarity, let&rsquo;s write a function that will help us get a settled promise after a certain time:\nconst setPromise = (value, ms, isRejected = false) =&gt; new Promise((resolve, reject) =&gt; setTimeout(() =&gt; isRejected ? reject(value) : resolve(value), ms)) All four methods we will cover below accept an array of values. However, each of these methods works differently, and they return different results.\nPromise.all This call returns an array of values or the first rejection:\nPromise.all([ setPromise(&#39;^_^&#39;, 400), setPromise(&#39;^_^&#39;, 200), ]).then((result) =&gt; { console.log(result) \/\/ [ &#34;^_^&#34;, &#34;^_^&#34; ] }) If at least one promise fails, instead of an array of values, the reason for rejection will be sent to catch:\nPromise.all([ setPromise(&#39;^_^&#39;, 400), setPromise(&#39;O_o&#39;, 200, true), ]).catch((error) =&gt; { console.log(error) \/\/ O_o }) For an empty array, an empty result is returned immediately:\nPromise.all([]) .then((result) =&gt; { console.log(result) \/\/ [] }) Promise.race This method returns the first value or the first rejection:\nPromise.race([ setPromise(&#39;^_^&#39;, 100), setPromise(&#39;O_o&#39;, 200, true), ]).then((result) =&gt; { console.log(result) \/\/ ^_^ }) If the rejection occurs first, then race will be set to rejection:\nPromise.race([ setPromise(&#39;^_^&#39;, 400), setPromise(&#39;O_o&#39;, 200, true), ]).catch((error) =&gt; { console.log(error) \/\/ O_o }) If you pass an empty array to Promise.race, the promise will be stuck in a pending state and will not be set to either fulfillment or rejection:\nPromise.race([]) .then(() =&gt; { console.log(&#39;resolve will never be executed&#39;) }).catch(() =&gt; { console.log(&#39;reject neither&#39;) }) Promise.any The call returns the first value or an array of rejection reasons if none of the promises were successful:\nPromise.any([ setPromise(&#39;^_^&#39;, 400), setPromise(&#39;O_o&#39;, 200, true), ]).then((result) =&gt; { console.log(result) \/\/ ^_^ }) When all promises are set to rejection, any will return an error object, in which you can extract information about the rejections from the errors field:\nPromise.any([ setPromise(&#39;O_o&#39;, 400, true), setPromise(&#39;O_o&#39;, 200, true), ]).catch((result) =&gt; { console.log(result.message) \/\/ All promises were rejected console.log(result.errors) \/\/ [ &#34;O_o&#34;, &#34;O_o&#34; ] }) For an empty array, an error will be returned:\nPromise.any([]) .catch((error) =&gt; { console.log(error.message) \/\/ All promises were rejected }) Promise.allSettled The method will wait for all promises to be completed and return an array of special objects:\nPromise.allSettled([ setPromise(&#39;^_^&#39;, 400), setPromise(&#39;O_o&#39;, 200, true), ]).then(([resolved, rejected]) =&gt; { console.log(resolved) \/\/ { status: &#34;fulfilled&#34;, value: &#34;^_^&#34; } console.log(rejected) \/\/ { status: &#34;rejected&#34;, reason: &#34;O_o&#34; } }) For an empty array, an empty result is:\nPromise.allSettled([]) .then((result) =&gt; { console.log(result) \/\/ [] }) Promisification When you need to transition from callback functions to promises, promisification comes to the rescue - a special helper function that turns a function working with a callback into a function that returns a promise:\nfunction promisify (fn) { return function (...args) { return new Promise((resolve, reject) =&gt; { function callback(error, result) { return error ? reject(error) : resolve(result) } fn(...args, callback) }) } } function asyncApi (url, callback) { \/\/ ... perform asynchronous operation callback(null, &#39;^_^&#39;) } promisify(asyncApi)(&#39;\/url&#39;) .then((result) =&gt; { console.log(result) \/\/ ^_^ }) The operation of promisification depends on the signature of the functions in the code, because it requires considering the order of arguments, as well as the parameters of the callback. In the example above, it is assumed that the callback function is passed as the last argument, and it first takes an error as a parameter, followed by the result.\nPromises or callback functions? Promises help to address the drawbacks of callback functions. They are always asynchronous, single-use, and promote more linear code, reducing tight coupling and mitigating callback hell.\nBut what if a promise gets stuck and is not being fulfilled or rejected? In this case, you can use Promise.race to interrupt the execution of a stuck or very long request by a timeout:\nPromise.race([ fetchLongRequest(), new Promise((_, reject) =&gt; setTimeout(reject, 3000)), ]).then((result) =&gt; { \/\/ received data }).catch((error) =&gt; { \/\/ or rejection due to timeout }) In any case, it&rsquo;s important to understand: despite the many advantages of promises, you will still need to use callback functions in some situations, and that&rsquo;s okay. Event handlers and many asynchronous API methods, such as setTimeout, work with callbacks, so in such cases, there&rsquo;s no point in promisifying and it&rsquo;s more convenient to use callback functions. After all, we will also need them to create a promise. The main thing to remember is that if there is a chain of sequential calls somewhere, promises should be used to improve code readability and error handling.\nCoroutines Promises are the foundation for working with asynchrony, but there is a very convenient async\/await extension built on top of this foundation, which is implemented thanks to coroutines.\nA coroutine (cooperative concurrently executed routine) is a co-program or, in simpler terms, a special function that can pause its work, remember its state, and has multiple entry and exit points.\nIn JavaScript, generator functions act as coroutines, returning an iterator. The iterator can pause its work, remember its current state, and interact with external code through .next and .throw.\nThanks to these capabilities of coroutines, you can write a special function like this:\nfunction async (generator) { const iterator = generator() function handle({ done, value }) { return done ? value : Promise.resolve(value) .then((x) =&gt; handle(iterator.next(x))) .catch((e) =&gt; handle(iterator.throw(e))) } return handle(iterator.next()) } And then use it to sequentially call asynchronous operations:\nasync(function* () { const response = yield fetch(&#39;example.com&#39;) const json = yield response.json() \/\/ process json }) This turned out to be so convenient that later, JavaScript added async\/await constructs.\nAsync\/await This is syntactic sugar implemented through promises and coroutines, which makes working with asynchronous operations more convenient.\nThe async modifier is placed before a function and makes it asynchronous:\nasync function asyncFunction () { return &#39;^_^&#39; } The result of an asynchronous function is always a promise. For convenience, you can think of an asynchronous function as a regular one that wraps its result in a promise:\nfunction asyncFunction () { return Promise.resovle(&#39;^_^&#39;) } The result of an asynchronous function is extracted through then or await:\nasyncFunction().then((value) =&gt; { console.log(value) \/\/ ^_^ }) (async () =&gt; { const value = await asyncFunction() console.log(value) \/\/ ^_^ })() Await is slightly more convenient than promises, but it has a serious limitation - it can only be called within an asynchronous function. With this, asynchrony becomes &ldquo;sticky&rdquo; - once you write an asynchronous call, there&rsquo;s no way back to the synchronous world. For a while, nothing could be done about this, but then top-level await appeared.\nTop-level await and asynchronous modules Top-level await allows you to use this operator outside of asynchronous functions:\nconst connection = await dbConnector() const jQuery = await import(&#39;http:\/\/cdn.com\/jquery&#39;) But it can only be used either inside ES6 modules or in DevTools. This limitation is due to the fact that await is syntactic sugar that works through modules.\nFor example, a module with top-level await looks like this for a developer:\n\/\/ module.mjs const value = await Promise.resolve(&#39;^_^&#39;) export { value } \/\/ main.mjs import { value } from &#39;.\/module.mjs&#39; console.log(value) \/\/ ^_^ The original code does not contain any asynchronous functions within the module or the main program, yet they are required for await to work. So, how does this code function?\nThe answer lies in the JavaScript engine&rsquo;s ability to handle this task by wrapping the await within an asynchronous function behind the scenes. Without the syntactic sugar, the top-level await would appear as follows:\n\/\/ module.mjs export let value export const promise = (async () =&gt; { value = await Promise.resolve(&#39;^_^&#39;) })() export { value, promise } \/\/ main.mjs import { value, promise } from &#39;.\/module.mjs&#39; (async () =&gt; { await promise console.log(value) \/\/ ^_^ })() No magic. Just syntactic sugar.\nError handling There are two ways to handle errors within asynchronous functions. The first is to add a catch after calling the function, and the second is to wrap the await call in a try\/catch block.\nSince asynchronous functions are promises, you can add a catch after the call and handle the error.\nasync function asyncFunction () { await Promise.reject(&#39;O_o&#39;) } asyncFunction() .then((value) =&gt; { \/\/ what if there&#39;s an error? }) .catch((error) =&gt; { \/\/ then catch will capture the error }) This method will work, but try\/catch is likely to be more suitable because it allows you to handle exceptions directly within the function body:\nasync function asyncFunction () { try { await Promise.reject(&#39;O_o&#39;) } catch (error) { \/\/ catch the error } } asyncFunction().then((value) =&gt; { \/\/ we&#39;re safe }) Another important advantage: unlike catch, the try\/catch block can handle top-level await.\nNot all await is equally useful The await operator suspends task execution until the asynchronous operation is complete. If you mindlessly add await before each asynchronous operation, this may lead to suboptimal code performance due to sequential loading of unrelated data.\nFor example, you could load a list of unrelated articles and pictures using await like this:\nconst articles = await fetchArticles() const pictures = await fetchPictures() \/\/ ... some actions with articles and pictures In this case, data that could be fetched in parallel will be requested sequentially. As long as the first part of the data is not fully loaded, work with the second part will not start. Because of this, the task will take longer than it could. Suppose each request takes two seconds; then, it will take four seconds to fully load the data. However, if you load the data in parallel using Promise.all, all the information will load twice as fast:\nconst [articles, pictures] = await Promise.all([ fetchArticles(), fetchPictures(), ]) Conclusion That&rsquo;s everything you probably wanted to know about asynchrony in the browser. I hope you now have a good understanding of how the event loop works, can escape from callback hell, easily work with promises, and skillfully use async\/await. If I forgot something, please remind me in the comments.\n","permalink":"https:\/\/anatoly.dev\/posts\/2023\/05\/mastering-asynchrony-in-the-browser-a-comprehensive-guide\/","summary":"<blockquote>\n<p>Acknowledgements<\/p>\n<p>This article was originally written in Russian by <a href=\"https:\/\/habr.com\/ru\/users\/gbiz\/posts\/\">Grigory Biziukin<\/a> and was published on <a href=\"https:\/\/habr.com\/ru\/companies\/yandex\/articles\/718084\/\">\u041f\u043e\u043b\u043d\u043e\u0435 \u043f\u043e\u043d\u0438\u043c\u0430\u043d\u0438\u0435 \u0430\u0441\u0438\u043d\u0445\u0440\u043e\u043d\u043d\u043e\u0441\u0442\u0438 \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435\n<\/a> on 28\/02\/2023. I would like to thank <a href=\"https:\/\/habr.com\/ru\/users\/gbiz\/posts\/\">Grigory Biziukin<\/a> for creating such informative and insightful content.\nI have made every effort to accurately translate the content while maintaining the author&rsquo;s original message and intent. However, any errors in translation are solely my own.\nI hope that my translation will allow a wider audience to access and appreciate this valuable content, and I encourage readers to visit the original publication or website to read more of <a href=\"https:\/\/habr.com\/ru\/users\/gbiz\/posts\/\">Grigory Biziukin<\/a>&rsquo;s work.<\/p>","title":"Mastering Asynchrony in the Browser: A Comprehensive Guide"},{"content":"Author&rsquo;s Note (2025): When I originally wrote this article, I didn&rsquo;t realize I was essentially reinventing RPC (Remote Procedure Call) - a pattern that&rsquo;s been around for decades. What I built here is very similar to JSON-RPC over HTTP, just without knowing it had a name! Today, I&rsquo;d recommend using battle-tested solutions like tRPC or oRPC which provide the same benefits I was seeking (type safety, simplicity, single endpoint) but with better tooling, community support, and production-readiness. However, I&rsquo;m keeping this article as-is because building this from scratch taught me valuable lessons about API design, and sometimes reinventing the wheel is the best way to understand why the wheel is shaped the way it is.\nThe Lightweight Alternative to GraphQL, Resolvers Instead of Endpoints A few months ago, I began working on a personal project that involved client-server communication. To take advantage of this, I tried using GraphQL. While I generally liked the approach of having a single API endpoint and resolvers, the overhead of setting up and maintaining a GraphQL server was too much for a one-person operation like mine.\nThat&rsquo;s when I came up with the idea of replacing GraphQL with a more lightweight and easier-to-manage approach. My solution, which I&rsquo;ll describe in more detail below, has proven to be a game-changer for me and has significantly improved my efficiency and speed of development.\nUnlike GraphQL, my solution does not require the overhead of setting up and maintaining multiple schemas which need to be set for the client and server. Instead, it defines resolver functions to provide flexible alternative. In this article, I&rsquo;ll walk you through the details of my solution and the benefits it has brought to my pet project.&quot;\nStep 1 - Creating Basic Express App At the beginning let&rsquo;s define a basic expressjs application which will have a single endpoint.\napp.js import express from &#39;express&#39;; import apiRouter from &#34;.\/api-route.js&#34;; import cors from &#34;cors&#34;; const app = express(); app.use(express.json()); app.use(&#39;\/api&#39;, apiRouter); app.use(&#39;cors&#39;); const port = process.env.PORT || 5000; const server = app.listen(port, () =&gt; { console.log(`Listening to port ${port}`); }); and\napi-route.js import express from &#34;express&#34;; const router = express.Router(); router.get(&#39;*&#39;, async (req, res, next) =&gt; { const response = { text: &#39;Hello World!&#39; }; return res.json(response); }) export default router; This is simplest express app possible, every GET request to localhost:5000\/api\/* will be responded with body:\n{ &#34;text&#34;: &#34;Hello World&#34; } You can find this code at the following GitHub repository in branch step-1: anatoly314\/server-boilerplate-article\nStep 2 - A Better Approach to API Development: Resolvers Provider To add more endpoints to our app, we could follow the traditional approach of grouping all the endpoints into route files and importing them one by one. However, I&rsquo;d like to suggest a new way that simplifies this process. Instead, we can create an api folder and define a new file within it called resolvers-provider.js, which will contain the following content:\nresolvers-provider.js import glob from &#39;glob&#39;; const __registeredResolvers = {}; export const registerResolver = (resolverName, resolver) =&gt; { if (__registeredResolvers[resolverName]) { throw new Error(`Resolver with ${resolverName} name already exists`); } __registeredResolvers[resolverName] = resolver; } export const getResolver = resolverName =&gt; { const resolver = __registeredResolvers[resolverName]; if (!resolver) { throw new Error(`Resolver with ${resolverName} wasn&#39;t registered`); } return resolver; } export const registerResolvers = async directoryName =&gt; { const files = glob.sync(directoryName + &#39;\/**\/*.js&#39;, { absolute: true }); const resolverFiles = files.filter(file =&gt; file.endsWith(&#39;-resolvers.js&#39;)); for (const resolverFile of resolverFiles) { const module = await import(resolverFile); Object.keys(module).forEach(key =&gt; { const resolver = module[key]; registerResolver(resolver); }) } } To invoke resolver-provider.js, simply add the following code to your api-route.js file:&quot;\n... const __dirname = dirname(fileURLToPath(import.meta.url)); await registerResolvers(__dirname); ... When you invoke registerResolver, it will search for all files that end with -resolvers.js within the api directory and its subdirectories. It will then register all of the exported functions from those files as resolvers.\nNext, add a new file called users-resolvers.js to the api\/users directory, and include the following content:\nusers-resolvers.js export const getUsersByName = ({body}) =&gt; { const {name} = body; const allUsers = [{ id: 1, name: &#39;Anatoly&#39;, age: 42 }, { id: 2, name: &#39;Yulia&#39;, age: 34 }, { id: 3, name: &#39;John&#39;, age: 55 }]; const filteredUsers = allUsers.filter(user =&gt; user.name === name); return filteredUsers; } When you run your server, all exported functions from files that match the pattern api\/*-resolvers.js will automatically be registered as resolvers.\nTo use the registered resolvers, there&rsquo;s one last step we need to take. We need to replace the existing GET endpoint in api-route.js with the following POST endpoint:\nrouter.post(&#39;*&#39;, async (req, res, next) =&gt; { try { const body = req.body; const authorizedUser = req.header(&#39;Authorization&#39;); const resolverName = req.url.substring(1); const resolver = getResolver(resolverName); const result = await resolver({body, authorizedUser}); return res.json(result); } catch (err) { if (err.message === &#39;Unauthenticated&#39;) { res.status(401); res.send(err.message); } else { res.status(500); res.send(&#34;Server error&#34;); } } }); To invoke our resolver, we can make a POST request to the following URL template: localhost:5000\/api\/&lt;RESOLVER_NAME&gt;. For example, to invoke the getUsersByName resolver, we would make a request to localhost:5000\/api\/getUsersByName. The body of the request should contain the necessary input data for the resolver to process.\n{ &#34;name&#34;: &#34;Anatoly&#34; } When our server receives this request, it will invoke the resolver with the name getUsersByName that&rsquo;s defined in the users-resolvers.js file located in the api\/users directory. The contents of the body will be passed to the resolver as input.\nSo what have we gained from this approach? Although there was some effort required at the beginning to set up the resolvers provider, the benefits are significant. Now, if we need to add another endpoint, instead of defining the entire endpoint code in the old way, we can simply add a new function to the existing resolvers provider or create a new resolvers provider. This results in less code, fewer bugs, and less time spent on development overall.\nStep 3 - Secure Your Resolvers with JavaScript Decorators With the boilerplate we&rsquo;ve created, we&rsquo;ve replaced the traditional ExpressJS API endpoints with a Resolvers approach that simplifies our codebase and makes developers&rsquo; lives much easier. However, this approach lacks middleware support, which means we need to find an alternative way to handle tasks like authentication and authorization that would normally be done with middleware. One option is to use JavaScript decorators. We will create a JavaScript decorator that requires authentication for requests to a resolver. One possible implementation is to check that the Authentication header of the request contains the word admin.\nJavascript Decorators considered safe to use now that they're at stage 3 proposal Stage 3 is the &ldquo;Candidate&rdquo; stage. At this stage, the proposal has been accepted by TC39 as a potential addition to the language and has been approved for inclusion in a future ECMAScript version. The proposal is considered mostly complete and has been reviewed and refined by TC39 members, but it may still undergo some changes based on feedback from implementers and developers. Proposals at Stage 3 are generally considered safe to use and are available in some experimental JavaScript runtimes, but they are not yet officially part of the language.\nFor more details look here: tc39\/proposal-decorators\nSince JavaScript decorators are still considered an experimental feature and Node.js currently does not have built-in support for them, we will need to use Babel to transpile our code. To do this, we will create a .babelrc file in the root of our project, which will allow us to configure Babel and use its transpiling capabilities:\n{ &#34;presets&#34;: [ [ &#34;@babel\/preset-env&#34;, { &#34;modules&#34;: false } ] ], &#34;env&#34;: { &#34;development&#34;: { &#34;sourceMaps&#34;: &#34;inline&#34;, &#34;retainLines&#34;: true } }, &#34;plugins&#34;: [ &#34;@babel\/plugin-syntax-top-level-await&#34;, [&#34;@babel\/plugin-proposal-decorators&#34;, { &#34;version&#34;: &#34;2022-03&#34; }] ] } To implement the necessary changes, you should first include the code block below in the script section of your package.json file:\n{ &#34;build&#34;: &#34;babel src -d dist&#34;, &#34;start&#34;: &#34;npm run build &amp;&amp; node dist\/app.js&#34;, &#34;start-nodemon&#34;: &#34;nodemon --watch &#39;.\/src\/**\/*.js&#39; --exec npm run start&#34; } Then, execute the following command to install the required devDependencies:\nnpm install --save-dev @babel\/core @babel\/cli @babel\/preset-env @babel\/plugin-proposal-decorators\nOnce this is done, you can start the app by running npm run start-nodemon. Babel will transpile the code in the src folder to a new dist folder, execute it, and automatically recompile it upon any changes made to the project. Before we can start using JavaScript decorators, we need to make some changes to our code. Specifically, the following files need to be modified: src\/api\/users\/users-resolvers.js and src\/api\/resolvers-provider.js\nAs per the proposal, decorators can be used with Classes and their elements such as fields, methods, and accessors. To leverage this feature, we need to ensure that our resolvers provider is an instance of a Class. Therefore, we will modify the code in src\/api\/users\/users-resolvers.js to the following:\nclass UsersResolvers { getUsersByName ({body}) { const {name} = body; const allUsers = [{ id: 1, name: &#39;Anatoly&#39;, age: 42 }, { id: 2, name: &#39;Yulia&#39;, age: 34 }, { id: 3, name: &#39;John&#39;, age: 55 }]; const filteredUsers = allUsers.filter(user =&gt; user.name === name); return filteredUsers; } } export default UsersResolvers; We also need to make changes to our src\/api\/resolvers-provider.js to allow it to create instances of a class and retrieve references to its class methods:\n... for (const resolverFile of resolverFiles) { const module = await import(resolverFile); const instantiatedResolver = new module.default(); Object.getOwnPropertyNames(module.default.prototype).forEach(key =&gt; { if (key !== &#39;constructor&#39;) { const resolver = instantiatedResolver[key]; registerResolver(key, resolver.bind(instantiatedResolver.self)); } }) } ... Now that all the preparations have been completed, we can start writing our first JavaScript decorator. Let&rsquo;s create a new folder called src\/decorators and add a file to it called auth-decorator.js:\nauth-decorator.js export function authRequired(userType){ return function (value, { kind, name }) { if (kind === &#34;method&#34; || kind === &#34;getter&#34; || kind === &#34;setter&#34;) { return function (...args) { const {authorizedUser} = args[0]; if (authorizedUser !== userType) { throw new Error(&#34;Unauthenticated&#34;); } const ret = value.call(this, ...args); return ret; }; } } } And we can apply it to the getUsersByName method in users-resolvers.js as follows:\n... @authRequired(&#34;admin&#34;) getUsersByName ({body}) { ... } ... By adding the authRequired decorator to a resolver function, such as getUsersByName in users-resolvers.js, requests to that resolver will require authentication. This means that the request must contain a value of admin in the Authentication header, or else the request will be rejected with a 401 error indicating that it is unauthenticated. This is just a basic example of what can be done with decorators. In general, anything that can be achieved with middleware can be achieved with decorators, offering great flexibility in the way you handle requests in your application.\nStep 4 - Creating React Hook which will seamlessly invoke resolvers We have implemented server side approach which replaces regular API with endpoints by approach with resolvers, let&rsquo;s create ReactJS hook which will call to these resolvers seamlessly:\nimport axios from &#34;axios&#34;; import {useState} from &#34;react&#34;; const RESOLVER_API_URL = &#34;http:\/\/localhost:4000\/api&#34;; export const useResolver = (resolverName) =&gt; { const [result, setResult] = useState(null); const [loading, setLoading] = useState(null); const invokeResolver = async data =&gt; { setLoading(true); try { const url = `${RESOLVER_API_URL}\/${resolverName}`; const config = { url, headers: { Authorization: &#39;admin&#39; }, method: &#39;POST&#39;, data: data } const response = await axios(config); setResult(response.data); return response.data; } catch (err) { const errText = `Error invoking resolver ${resolverName}`; console.log(errText, err); throw new Error(errText); } finally { setLoading(false); } } return [invokeResolver, result, loading]; } A call to any resolver can now be as simple as the following:\nconst [getUsersByName, users, loadingUsers] = useResolver(&#34;getUsersByName&#34;); The getUsersByName function can now be called using a simple syntax. The results of the invocation are stored in the users property, while the loadingUsers boolean flag indicates the current invocation state.\nHere&rsquo;s the complete example of a React component that uses this hook:\nimport React, {useState} from &#34;react&#34;; import {useResolver} from &#34;..\/..\/resolvers\/resolvers-hook&#34;; const Users = () =&gt; { const [getUsersByName, users, loadingUsers] = useResolver(&#34;getUsersByName&#34;); const [inputValue, setInputValue] = useState(&#39;&#39;); const handleInputChange = (event) =&gt; { setInputValue(event.target.value); } return ( &lt;div&gt; { loadingUsers &amp;&amp; &lt;div&gt;LOADING&lt;\/div&gt; } Users with the name: &lt;input type=&#34;text&#34; value={inputValue} onChange={handleInputChange} \/&gt; &lt;button onClick={() =&gt; getUsersByName({ name: inputValue })}&gt;Load Users&lt;\/button&gt; &lt;pre&gt; {JSON.stringify(users, null, 2)} &lt;\/pre&gt; &lt;\/div&gt; ) } export default Users; Credits:\nChatGPT, I would like to express my gratitude to ChatGPT for the incredible help provided to me. The chatbot was instrumental in guiding me through various questions and tasks, and helped me to improve my English writing skills. The examples and explanations given were invaluable in understanding complex concepts. I would like to thank the entire team behind ChatGPT for creating such an amazing resource. GraphQL developer community, I would like to acknowledge the contributions of the GraphQL developer community, including Facebook and Apollo. Much of what I have accomplished in this project has been inspired by their codebase.&quot; ","permalink":"https:\/\/anatoly.dev\/posts\/2023\/05\/reinventing-rpc\/","summary":"<p><em>Author&rsquo;s Note (2025): When I originally wrote this article, I didn&rsquo;t realize I was essentially reinventing RPC (Remote Procedure Call) - a pattern that&rsquo;s been around for decades. What I built here is very similar to JSON-RPC over HTTP, just without knowing it had a name! Today, I&rsquo;d recommend using battle-tested solutions like tRPC or oRPC which provide the same benefits I was seeking (type safety, simplicity, single endpoint) but with better tooling, community support, and production-readiness. However, I&rsquo;m keeping this article as-is because building this from scratch taught me valuable lessons about API design, and sometimes reinventing the wheel is the best way to understand why the wheel is shaped the way it is.<\/em><\/p>","title":"How I Accidentally Reinvented RPC: A Lightweight Alternative to GraphQL"}]