<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Khaled Zeitar on Medium]]></title>
        <description><![CDATA[Stories by Khaled Zeitar on Medium]]></description>
        <link>https://medium.com/@khaledzeitar?source=rss-a35308db09bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gPJI-nGvKoXRS5SrdxnM1Q.jpeg</url>
            <title>Stories by Khaled Zeitar on Medium</title>
            <link>https://medium.com/@khaledzeitar?source=rss-a35308db09bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:26:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khaledzeitar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Midnight Thoughts: Can I Train an LLM at Home?]]></title>
            <link>https://medium.com/@khaledzeitar/midnight-thoughts-can-i-train-an-llm-at-home-997859370c3b?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/997859370c3b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 20:30:26 GMT</pubDate>
            <atom:updated>2026-09-08T20:30:26.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8X_50-2SfPtySl0izCI5Q.jpeg" /></figure><p>It’s midnight. You’re not asleep. And somehow your brain has landed on: <em>“How do I train an LLM at home? And while I’m at it, how do I invent a brand-new training algorithm, with zero prior experience?”</em></p><p>If that sounds oddly specific, it’s because it happened to me, verbatim, a few nights ago. This article is the walk from that 3 am ambition down to something I could actually <em>do</em> — and along the way, a plain-language map of how models like GPT-2 and today’s trillion-parameter giants actually get built, and what really separates them.</p><h3>Part 1: The 3 am spiral</h3><p>The two questions I actually typed were:</p><ol><li>How do I train an LLM at home?</li><li>How do I find a new training algorithm, with no prior experience?</li></ol><p>Both are the kind of question that feels reasonable at midnight and slightly unhinged by daylight. But they’re not <em>bad</em> questions — they’re just aimed at the wrong scale. So let’s right-size them.</p><p><strong>On training at home:</strong> you’re not pretraining a frontier model on a gaming PC. But you can train <em>real</em> small models — a working transformer that tokenizes, learns, and generates text — on a single GPU, sometimes even a laptop. The honest version of “train an LLM at home” is either fine-tuning an existing open model (LoRA/QLoRA on something like Llama 3 8B), or training a genuinely small model from scratch to learn the mechanics.</p><p><strong>On inventing a new algorithm with no experience:</strong> the honest version is that novel optimizers and training tricks come from people steeped in the existing ones. Nobody skips that step. But there’s a real, unglamorous path: get hands-on with a small model, read the landmark papers end to end, and start running tiny, single-variable experiments. That loop — change one thing, measure it, keep or discard — <em>is</em> research. It’s just not a lightning bolt.</p><p>Which is how I ended up at <a href="https://github.com/karpathy/nanochat">nanochat</a>, Andrej Karpathy’s “simplest experimental harness for training LLMs.” It’s designed to run on a single GPU node, and — this is the part that hooked me — it covers the <em>entire</em> pipeline: tokenization, pretraining, finetuning, evaluation, and inference, all in code small enough to actually read.</p><p>The headline number that makes this real instead of aspirational: you can train your own GPT-2-capability model — the same GPT-2 that cost roughly $43,000 to train in 2019 — for about <strong>$48</strong>, in around two hours on a rented 8×H100 GPU node. On a spot instance, closer to $15.</p><p>And critically for the “at home” part: all of the code runs on a single GPU too (just slower), and there’s a CPU/MPS script that trains a deliberately shrunk toy model in well under an hour, purely so you can watch the whole pipeline run on your own laptop before spending a cent.</p><p>That reframed the midnight question. Not <em>“how do I build a 2-trillion-parameter model,”</em> but <em>“how do I understand, end to end, what building any model actually requires — and then run the smallest real version of it myself.”</em></p><h3>Part 2: What a model actually is, mechanically</h3><p>Before comparing small and large models, it helps to know what the knobs even are. Every transformer-based LLM — 2 billion parameters or 2 trillion — is described by the same handful of dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtkpLM3BrLpdGIRnRNxLrw.png" /></figure><p>In plain terms:</p><ul><li><strong>Depth</strong> — how many transformer layers are stacked on top of each other. Each layer refines the model’s understanding a bit more. This is nanochat’s single exposed dial (--depth), and GPT-2-level capability happens to land around depth 26.</li><li><strong>Width (hidden size)</strong> — how large the internal vector representing each token is, inside each layer. Wider means more room to encode nuance.</li><li><strong>Attention heads</strong> — within a layer, attention splits into several parallel “heads,” each free to specialize in a different kind of relationship between tokens (grammar, long-range topic tracking, and so on).</li><li><strong>Context length</strong> — how many tokens the model can consider at once when predicting the next one. This is a hard ceiling on how much it can “remember” of the current conversation.</li><li><strong>Vocabulary size</strong> — how many distinct tokens the tokenizer can produce. A bigger vocabulary lets each token carry more meaning, at the cost of a bigger embedding table.</li><li><strong>Total parameters</strong> — the number everyone quotes. It isn’t chosen directly — it <em>falls out</em> of depth, width, heads, and vocabulary size multiplied across all layers. You don’t pick “2 trillion” the way you pick a T-shirt size; you pick depth and width, and 2 trillion is what results.</li></ul><p>The reason nanochat can auto-calculate “all other hyperparameters” from a single depth value is that these dimensions aren’t independent — there’s a compute-optimal <em>shape</em> for any given size, and getting that balance wrong wastes the compute you spend.</p><h3>Part 3: 2 billion vs. 2 trillion — same recipe, different universe</h3><p>Here’s the thing that surprised me most: going from 2B to 2T parameters isn’t “the same process, bigger oven.” It’s a different engineering problem, full stop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TG1ZokRahV8HbfNzf7aIpA.png" /></figure><p>A few specifics behind that table:</p><p><strong>Distributed training stops being optional.</strong> A 2B model can often be trained with plain data parallelism — every GPU holds a full copy of the model. A 2T model doesn’t even <em>fit</em> in one GPU’s memory. You have to split the model itself across GPUs (tensor and pipeline parallelism) <em>and</em> split the data across GPUs (data parallelism), simultaneously. Getting this right is arguably the hardest part of frontier-scale infrastructure — harder, in practice, than most of the modeling decisions.</p><p><strong>Hardware failure becomes a design requirement, not an exception.</strong> Run tens of thousands of GPUs for months, and something is <em>always</em> failing — a GPU dies, a network link flakes, a node hangs. Frontier labs build elaborate automatic checkpointing and restart systems just so the run survives, because losing a multi-month training job to one bad GPU is not an option.</p><p><strong>Data has to scale with the model, not lag behind it.</strong> This is the actual answer to a question I found myself asking mid-conversation: <em>is a 2T model trained on more data, or is it just deeper?</em> The answer is <strong>both, in a specific ratio.</strong> The “Chinchilla” scaling-law finding (DeepMind, 2022) was that many earlier large models were undertrained — huge parameter counts, but not enough data to justify that size. The compute-optimal rule of thumb that came out of it: roughly 20 tokens of training data per parameter. So a 2T-parameter model isn’t a scaled-up 2B model with the same data diet — it sits at a different point on a size-versus-data curve, and only pays off if the data volume scales with it.</p><p><strong>Small mistakes compound with scale.</strong> At 2B parameters, a slightly-off learning rate schedule costs you some GPU-hours. At 2T, the identical mistake costs millions of dollars. That’s precisely why labs run small-scale “scaling law” experiments first — exactly the depth-sweep idea nanochat is built around — to predict what will work <em>before</em> committing to the expensive run.</p><h3>Part 4: What I’m actually going to do about it</h3><p>So, no, I’m not training a 2-trillion-parameter model in my bedroom. But the midnight question wasn’t really unanswerable — it just needed to shrink to something real.</p><p>Here’s how I’m actually approaching it:</p><p>First, clone nanochat and run it locally — free, on my own laptop:</p><pre>git clone https://github.com/karpathy/nanochat.git<br>cd nanochat<br>bash runs/runcpu.sh</pre><p>While that runs, I want to actually read the core files — gpt.py, tokenizer.py, optim.py — instead of just skimming them.</p><p>Then, rather than jumping to something big and expensive, I’ll try smaller single-GPU runs with a reduced --depth. Cheaper, faster, and a better way to learn.</p><p>And the real “research” part: change one variable at a time, compare val_bpb and the CORE score, see what moves. Not a genius breakthrough — just tweak, measure, repeat.</p><p>I’ll start there, and see how it goes.</p><p>That last step is the part that quietly answers my second midnight question. nanochat maintains a public leaderboard tracking the wall-clock time to reach GPT-2-level capability, and recent leaderboard entries are exactly this loop in action — a dataset swap, a batch-size change, an “autoresearch” round — each one trimming training time down further, each one a small, testable, single-variable change against a clear metric.</p><p>That’s what “finding a new training algorithm with no prior experience” actually looks like in practice. Not a eureka moment. A loop: change one thing, measure it, keep it or throw it away, repeat.</p><p>Somewhere out there, someone&#39;s running their own val_bpb curve right now, nudging one hyperparameter at a time, waiting to see if it dips.</p><p>That&#39;s not a headline. But it&#39;s how every big model, and every big idea, actually got made — one small, testable change at a time.</p><p>I&#39;m about to go find out what mine looks like.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=997859370c3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Calculators Killed Mental Math (And Why AI Won’t Kill Coding)]]></title>
            <link>https://medium.com/@khaledzeitar/how-calculators-killed-mental-math-and-why-ai-wont-kill-coding-f18f98f512ed?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18f98f512ed</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 17:54:17 GMT</pubDate>
            <atom:updated>2026-03-09T17:54:17.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ed78-Sf-gPzNt5cM-YPAJQ.png" /><figcaption>Credit: Generated by ChatGPT! :)</figcaption></figure><p>I remember the exact moment mental math died for me.</p><p>I was in school, working through yet another page of long division problems, when someone showed up with one of those cheap Casio calculators. You know the ones — slightly yellowed plastic, buttons that stuck sometimes, but suddenly you could breeze through an entire page of homework in minutes.</p><p>And just like that, all those years of memorizing multiplication tables and doing calculations by hand felt… quaint. Like learning to churn butter when you have a perfectly good fridge.</p><p>The transition wasn’t instant. There was resistance. Parents worried we’d lose our basic arithmetic skills. Teachers insisted we show our work. Some schools even banned calculators from certain exams, convinced they were creating a generation of mathematical zombies.</p><p>And you know what? They were partly right. I can barely do division on paper anymore. Ask me to calculate 18% tip on $67.50 without pulling out my phone, and I’ll stare at you blankly for an uncomfortably long time.</p><p>But here’s the thing — I also don’t <em>need</em> to. Because while my mental arithmetic got worse, my ability to actually <em>use</em> mathematics got exponentially better.</p><p>That’s the part people forget.</p><p>Calculators didn’t make us worse at math. They changed what “being good at math” meant. It stopped being about computation and started being about understanding concepts, setting up problems, and interpreting results. I can model complex systems, analyze data, and make predictions that would have been impossible for me to do by hand — even if I was a mental math prodigy.</p><p>The tool removed the friction so I could focus on the thinking.</p><h3>Sound Familiar?</h3><p>I see where this is going, and I bet you do too.</p><p>Replace “calculator” with “AI coding assistant” and the same conversations happening in 1980 are happening today on Twitter, at conferences, and in team standups.</p><p>“AI will make developers lazy.”</p><p>“New devs won’t learn the fundamentals.”</p><p>“We’re creating a generation of copy-paste coders who don’t understand how anything works.”</p><p>And look — I get the fear. I really do. There’s genuine satisfaction in working through a complex algorithm from scratch. There’s value in the struggle. I’ve had moments where pair programming with an AI tool felt almost <em>too</em> easy, like I was cheating somehow.</p><p>But I also remember my dad saying the same thing about calculators while he used his slide rule.</p><h3>The Shift from How to What</h3><p>Here’s what I think is actually happening:</p><p>AI in coding is doing for programming what calculators did for mathematics — it’s shifting the value from <em>how</em> to <em>what</em>.</p><p>In a world where AI can write boilerplate, suggest optimizations, and handle routine debugging, the value of a developer isn’t about how quickly you can type or how many language features you have memorized. It’s about:</p><ul><li>Problem formulation — Can you break down ambiguous business requirements into something solvable?</li><li>System design — Do you understand how components fit together at scale?</li><li>Judgment — When AI gives you three solutions, can you pick the right one for your context?</li><li>Debugging instinct — When something breaks, do you know where to look?</li></ul><p>These are the “being good at math” skills of our time. And they’re way harder to automate than writing a for-loop.</p><h3>But Won’t We Lose Fundamentals?</h3><p>Okay, valid concern. If we lean too hard on AI tools, do we risk creating developers who can’t code without them?</p><p>Maybe. But also: so what?</p><p>I can’t do long division on paper, but I understand what division <em>is</em>. I know when to use it and what the result means. If you put a gun to my head and forced me to do it by hand, I’d struggle — but I could probably figure it out because I understand the underlying concept.</p><p>Same with coding. New developers might learn differently than we did. They might reach for AI tools sooner and struggle more when thrown into a blank text editor. But they’ll still need to understand control flow, data structures, and algorithmic thinking to effectively prompt and iterate with AI.</p><p>The fundamentals won’t disappear — they’ll just be learned and applied differently.</p><h3>The Real Question</h3><p>Here’s what I think we should be asking instead of “will AI replace developers:”</p><p>What becomes possible when we remove the friction?</p><p>Calculators didn’t just make arithmetic faster — they enabled entirely new kinds of mathematics that weren’t practical before. Complex modeling, statistical analysis, data science.</p><p>AI coding assistants aren’t just making us faster at writing the same code — they’re enabling new kinds of development. Prototypes that happen in real-time. Explorations of multiple architectural approaches simultaneously. Lower barriers to entry for people with great ideas but less traditional training.</p><p>Maybe, just maybe, that’s worth losing some mental arithmetic skills along the way.</p><h3>The Bottom Line</h3><p>The calculator didn’t ruin mathematics. It ruined <em>one specific kind</em> of mathematics while opening the door to something much bigger.</p><p>I suspect AI will do the same for development. Some things will be lost — and yeah, sometimes I’ll miss them. But I’m way more excited about what we gain.</p><p>The question isn’t whether AI will change how we code. It already has. The question is whether we’ll adapt our thinking about what “being good at coding” actually means.</p><p>My money’s on the developers who figure that out first.</p><p><em>What do you think? Are we losing something essential, or just trading one set of skills for another? I’d love to hear your perspective.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18f98f512ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Let AI Write Most of My Code for a Month. Here’s What Happened.]]></title>
            <link>https://medium.com/@khaledzeitar/i-let-ai-write-most-of-my-code-for-a-month-heres-what-happened-0036528c7504?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0036528c7504</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 18:29:32 GMT</pubDate>
            <atom:updated>2026-01-17T18:29:32.728Z</atom:updated>
            <content:encoded><![CDATA[<p>It started innocently enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_LNEzJHjpdjABGvKYCcFw.png" /></figure><p>I was staring at a blank editor, trying to build a <a href="https://github.com/kzeitar/freeport">simple CLI tool</a>. Something that should take a few days max. But you know how it goes — stack overflow rabbit holes, documentation that reads like legalese, the constant context switching between “what am I building?” and “how do I even do this?”</p><p>So I did what many of us do now. I fired up an AI assistant.</p><p>“Write a CLI tool in Golang that accepts a port number and kills any process running on that port.”</p><p>A couple of minutes later, I had working code. It wasn’t just working — it was <em>polished</em>. Error handling, helpful messages, cross-platform compatibility. The stuff that would have taken me hours to get right.</p><p>Cool, right?</p><p>Here’s the thing — over the last month, I kept going. I let AI write more and more of my code. Everything from boilerplate to business logic. And I learned something important about this approach.</p><p>Something I think every developer should hear.</p><h3>The Good Stuff (Why It’s Tempting)</h3><p>Let’s start with the obvious: <strong>AI makes you feel unstoppable.</strong></p><p>Projects that used to take a week suddenly take two days. You’re shipping faster than ever. The friction just… disappears. Stuck on a gnarly regex? AI handles it. Can’t remember that one library API? AI shows you. That weird bug that’s been driving you crazy? AI suggests three possible fixes.</p><p>And the momentum — that’s the real drug. You’re actually <em>finishing</em> things. You’re not abandoning projects halfway through because you hit a wall. You ship something, feel good about it, and move on to the next thing.</p><p>For someone who struggles with overwhelm and perfectionism (guilty), this feels revolutionary.</p><p>But here’s what I noticed happening.</p><h3>The Problem With Code You Don’t Understand</h3><p>About two weeks in, I shipped a side project. A simple tool that pulled data from an API and displayed it nicely. AI had written most of it — the API calls, the data parsing, the error handling, the whole deal.</p><p>It worked. I was proud. I moved on.</p><p>A week later, someone reported a bug. The data wasn’t displaying correctly in a specific case.</p><p>I opened the code and stared at it.</p><p>And I realized… I had no idea how it worked.</p><p>Like, I could tell you what it <em>did</em>. But I couldn’t tell you <em>why</em> it worked that way. I couldn’t explain the data flow. I couldn’t debug it because I didn’t understand the decisions AI had made.</p><p>So I did what felt natural — I asked AI to fix the bug.</p><p>It did. The bug disappeared. But I felt… weird about it. I’d shipped a fix I didn’t understand, for a project I didn’t understand, to solve a problem I didn’t fully grasp.</p><p>I was essentially a copy-paster, but with better branding.</p><h3>The Debugging Hell</h3><p>Here’s where it gets worse.</p><p>A month into this experiment, I was working on something more complex. Multiple files, some tricky state management, the kind of thing where small changes have big ripple effects.</p><p>Something broke. Not a clear error — just… wrong behavior.</p><p>I spent three hours trying to fix it. Three hours of pasting code into AI, getting suggestions that almost worked but not quite, watching the bug mutate into different bugs, feeling my confidence erode.</p><p>Here’s the thing about AI: it’s great at writing code that works. It’s <em>okay</em> at fixing code. But when you’re deep in the weeds of a complex system you don’t fully understand? AI can’t save you.</p><p>Because it doesn’t understand the context either. It doesn’t know the history of decisions you made. It can’t see the system as a whole.</p><p>It just sees tokens and patterns.</p><p>That night, at 2 AM, staring at code I’d technically “written” but didn’t understand, I realized something:</p><p><strong>I’d outsourced the thinking, not just the typing.</strong></p><h3>What You Actually Lose</h3><p>It’s not just about understanding your code, though that’s huge.</p><p><strong>It’s about growth.</strong></p><p>I looked back at that month of AI-assisted development and asked myself: “What did I learn?”</p><p>The honest answer? Not much.</p><p>I’d shipped more projects than usual, sure. But I hadn’t become a better developer. I hadn’t leveled up my problem-solving. I hadn’t even really engaged with the interesting parts of the problems I was solving.</p><p>I’d become really good at… prompting. At assembling pieces. At shipping fast.</p><p>But the deep satisfaction that comes from genuinely solving a hard problem? That was gone.</p><p>And here’s the scary part: I could feel myself getting <em>dependent</em>. I’d start a project and immediately think “I’ll just have AI handle that part.” I was avoiding the hard stuff — the stuff that actually makes you grow.</p><h3>The Middle Ground (What I Do Now)</h3><p>So I stopped. Not completely — that would be throwing the baby out with the bathwater. But I changed my approach.</p><p><strong>Here’s what works for me:</strong></p><h4>AI Handles The Boring Stuff</h4><p>✅ Boilerplate code — project setup, config files, repetitive patterns</p><p>✅ Research — “What’s the best way to parse JSON in Go?” or “How does this library work?”</p><p>✅ Unblocking — when I’m genuinely stuck, AI helps me see options I hadn’t considered</p><p>✅ Code review — “Find security issues in this” or “What would you improve?”</p><p>✅ Tests — generating unit tests, especially for edge cases I hadn’t thought of</p><p>✅ Documentation — writing READMEs, adding comments (but only after I understand what’s happening)</p><h4>I Handle The Important Stuff</h4><p>❌ Complex business logic — if I don’t understand the core problem deeply, no amount of AI will save me</p><p>❌ Security-sensitive code — AI misses things, and I need to be able to defend every security decision</p><p>❌ Performance-critical paths — AI writes “okay” code, not fast code</p><p>❌ Architecture decisions — AI doesn’t know my context, my constraints, my tradeoffs</p><p>❌ Production debugging — if I don’t understand the system, I’m helpless when things break</p><h3>The Golden Rule</h3><p>Here’s the rule I live by now:</p><p><strong>Never ship code you couldn’t debug yourself.</strong></p><p>Before committing AI-generated code, I ask myself:</p><ol><li>Can I explain what this code does, line by line?</li><li>Do I understand <em>why</em> it’s written this way and not some other way?</li><li>If this breaks at 3 AM on a Sunday, could I fix it without AI’s help?</li></ol><p>If the answer to any of these is “no” — I don’t ship it.</p><p>Period.</p><h3>What This Actually Looks Like In Practice</h3><p>Let me give you a concrete example.</p><p>Recently, I built a <a href="https://github.com/kzeitar/freeport/">CLI tool</a> that kills processes running on specific ports. Simple stuff.</p><p><strong>Here’s how AI helped:</strong></p><ul><li>It generated the CLI argument parsing boilerplate</li><li>It showed me how to find processes by port (<em>I hadn’t done this before</em>)</li><li>It suggested cross-platform considerations I hadn’t thought of</li><li>It helped me write helpful error messages</li></ul><p><strong>Here’s what I did myself:</strong></p><ul><li>I decided on the overall structure and flow</li><li>I wrote the core logic (finding the process, killing it safely)</li><li>I tested edge cases manually to understand failure modes</li><li>I read every line of code before committing it</li><li>I could explain the entire program to you if you asked</li></ul><p>The result? I built it in two days instead of five. But I <em>understood</em> what I built.</p><p>And when someone reported a bug on Windows (naturally), I knew exactly where to look. I wasn’t guessing. I wasn’t pasting errors into AI hoping for the best.</p><p>I was a developer who’d used tools to work faster — not an assembler of other people’s code.</p><h3>The Real Question</h3><p>So should you use AI when you code?</p><p>I think the better question is: <strong>What’s your goal?</strong></p><p>If you’re trying to ship a side project fast and you don’t care about growing as a developer? Go for it. Let AI write everything. Ship fast, learn what happens.</p><p>If you’re building something serious — something that needs to last, something that might break in production at 3 AM? Then you need to understand what you’re building. Use AI as a tool, not a replacement for thinking.</p><p>If you’re early in your career and trying to grow? Be careful. There’s no substitute for struggling through hard problems. That struggle is where the learning happens.</p><p>If you’re experienced and just want to move faster? Use AI intelligently. Let it handle the stuff that’s below your skill level. Do the stuff that’s at or above it.</p><h3>Where I Landed</h3><p>A month later, here’s what I’ve settled into:</p><p>AI writes about 50–60% of my code. But I read 100% of it. I understand 100% of it. And I could debug 100% of it if I had to.</p><p>The speed gains are still there. The momentum is still there.</p><p>But the growth is back too. The satisfaction of solving hard problems. The confidence that comes from truly understanding what I’ve built.</p><p>I’m not just shipping faster. I’m becoming a better developer while I do it.</p><h3>The Bottom Line</h3><p>AI is an incredible tool. Maybe the best thing to happen to developer productivity in my lifetime.</p><p>But it’s just that — a tool.</p><p>Like any tool, it can amplify your abilities or it can become a crutch. The difference isn’t in the tool itself. It’s in how you use it.</p><p>So use AI. Embrace it. Let it make you faster, more productive, less frustrated.</p><p>But never, ever ship code you don’t understand.</p><p>Your future self — the one debugging production issues at 2 AM — will thank you.</p><p><em>What’s your experience with AI-assisted coding? Have you found a balance that works for you? I’d love to hear your story.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0036528c7504" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Rate Limiting Patterns: Multi-Tier, Compound Limiters, and Distributed Systems]]></title>
            <link>https://medium.com/@khaledzeitar/advanced-rate-limiting-patterns-multi-tier-compound-limiters-and-distributed-systems-131ed816da45?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/131ed816da45</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 19:16:00 GMT</pubDate>
            <atom:updated>2025-12-27T19:16:00.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bEGjLHi0JUxAIA4sTZwRA.png" /></figure><p>You’ve got basic rate limiting working (<a href="https://medium.com/@khaledzeitar/why-your-node-js-api-needs-rate-limiting-cc49b4abcf6b">Part 1</a>, <a href="https://medium.com/@khaledzeitar/from-zero-to-production-implementing-rate-limiting-in-node-js-51b4408a876d">Part 2</a>). Your API is protected. Life is good.</p><p>Then your product manager walks over: “We need different rate limits for free and paid users.” Or your infrastructure team says “We’re adding a second server, will your rate limiting still work?” Or you realize that your image processing endpoint needs way stricter limits than your read-only endpoints.</p><p>This is where things get interesting. Let’s talk about advanced patterns that I’ve actually used in production.</p><h3>Different limits for different users</h3><p>The SaaS problem: free users get 100 requests per hour, paid users get 1000, enterprise gets basically unlimited. How do you handle this?</p><p>The naive approach is to check the user’s tier and then use an if statement to pick different limits. That works until you have 5 tiers and 10 endpoints and now you have 50 different limit configurations scattered through your code.</p><p>Here’s a cleaner way:</p><pre>import { RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>const storage = new InMemoryStorage();<br><br>const tiers = {<br>  free: new RateLimiterFactory({<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;free-tier&#39;,<br>    limit: 100,<br>    rate: { interval: &#39;1 hour&#39;, amount: 100 }<br>  }, storage),<br>  pro: new RateLimiterFactory({<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;pro-tier&#39;,<br>    limit: 1000,<br>    rate: { interval: &#39;1 hour&#39;, amount: 1000 }<br>  }, storage),<br>  enterprise: new RateLimiterFactory({<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;enterprise-tier&#39;,<br>    limit: 10000,<br>    rate: { interval: &#39;1 hour&#39;, amount: 10000 }<br>  }, storage)<br>};<br><br>const multiTierRateLimit = async (req, res, next) =&gt; {<br>  const userTier = req.user?.tier || &#39;free&#39;;<br>  const factory = tiers[userTier];<br>  const limiter = factory.create(req.user.id);<br>  const result = await limiter.consume(1);<br>  res.setHeader(&#39;X-RateLimit-Tier&#39;, userTier);<br>  res.setHeader(&#39;X-RateLimit-Remaining&#39;, result.getRemainingTokens().toString());<br>  if (!result.isAccepted()) {<br>    return res.status(429).json({<br>      error: &#39;Rate limit exceeded&#39;,<br>      tier: userTier,<br>      retryAfter: result.getRetryAfter()<br>    });<br>  }<br>  next();<br>};</pre><p>Here’s a clever conversion tactic: when free users hit their limit, tell them they can upgrade. This is a natural conversion point:</p><pre>if (!result.isAccepted() &amp;&amp; userTier === &#39;free&#39;) {<br>  return res.status(429).json({<br>    error: &#39;Rate limit exceeded&#39;,<br>    message: &#39;Upgrade to Pro for 10x higher limits&#39;,<br>    upgradeUrl: &#39;https://yourapp.com/pricing&#39;,<br>    retryAfter: result.getRetryAfter()<br>  });<br>}</pre><p>This can convert at 2–3%, which is better than most upsell prompts.</p><h3>Enforcing multiple limits at once</h3><p>A common production scenario: you need to prevent both burst attacks (someone hammering the API with 100 requests per second) AND sustained abuse (someone making 50,000 requests per day). A single rate limiter can’t do both effectively.</p><p>The solution is compound limiters — checking multiple limits for every request:</p><pre>import { CompoundRateLimiterFactory, RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>const storage = new InMemoryStorage();<br><br>const perSecondFactory = new RateLimiterFactory({<br>  policy: &#39;token_bucket&#39;,<br>  id: &#39;per-second&#39;,<br>  limit: 10,<br>  rate: { interval: &#39;1 second&#39;, amount: 10 }<br>}, storage);<br><br>const perHourFactory = new RateLimiterFactory({<br>  policy: &#39;token_bucket&#39;,<br>  id: &#39;per-hour&#39;,<br>  limit: 1000,<br>  rate: { interval: &#39;1 hour&#39;, amount: 1000 }<br>}, storage);<br><br>const compound = new CompoundRateLimiterFactory([<br>  perSecondFactory,<br>  perHourFactory<br>]);<br><br>const limiter = compound.create(&#39;user-123&#39;);<br><br>const result = await limiter.consume(1);</pre><p>The request only goes through if ALL limiters accept it. If any limiter rejects, the whole request is rejected.</p><p>This is powerful because you can layer protection. Here’s a production-ready configuration:</p><pre>const apiLimiter = new CompoundRateLimiterFactory([<br>  // Prevent flooding<br>  new RateLimiterFactory({<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;burst&#39;,<br>    limit: 20,<br>    rate: { interval: &#39;1 second&#39;, amount: 20 }<br>  }, storage),</pre><pre>// Prevent sustained abuse<br>  new RateLimiterFactory({<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;sustained&#39;,<br>    limit: 1000,<br>    rate: { interval: &#39;1 minute&#39;, amount: 100 }<br>  }, storage),<br>  // Daily quota<br>  new RateLimiterFactory({<br>    policy: &#39;fixed_window&#39;,<br>    id: &#39;daily&#39;,<br>    limit: 10000,<br>    rate: { interval: &#39;1 day&#39;, amount: 10000 }<br>  }, storage)<br>]);</pre><p>Three layers of protection:</p><ul><li>Can’t exceed 20 requests per second</li><li>Can’t sustain more than 100 requests per minute (1000 tokens that refill at 100/minute)</li><li>Daily cap of 10,000 total</li></ul><p>Someone trying to abuse your API has to get through all three.</p><h3>Global limits plus per-user limits</h3><p>Sometimes you need to protect the entire system AND individual users. Example: your API calls an expensive third-party service that has its own rate limits. You need a global limit to stay under their cap, plus per-user limits for fairness.</p><pre>const globalFactory = new RateLimiterFactory({<br>  policy: &#39;token_bucket&#39;,<br>  id: &#39;global&#39;,<br>  limit: 10000,<br>  rate: { interval: &#39;1 second&#39;, amount: 10000 }<br>}, storage);</pre><pre>const perUserFactory = new RateLimiterFactory({<br>  policy: &#39;token_bucket&#39;,<br>  id: &#39;per-user&#39;,<br>  limit: 100,<br>  rate: { interval: &#39;1 minute&#39;, amount: 100 }<br>}, storage);<br>const rateLimitMiddleware = async (req, res, next) =&gt; {<br>  const userId = req.user?.id || req.ip;<br>  // Check global limit first (same identifier for everyone)<br>  const globalLimiter = globalFactory.create(&#39;api&#39;);<br>  const globalResult = await globalLimiter.consume(1);<br>  if (!globalResult.isAccepted()) {<br>    return res.status(503).json({<br>      error: &#39;Service temporarily unavailable&#39;,<br>      message: &#39;API is experiencing high traffic&#39;,<br>      retryAfter: globalResult.getRetryAfter()<br>    });<br>  }<br>  // Then check per-user limit<br>  const userLimiter = perUserFactory.create(userId);<br>  const userResult = await userLimiter.consume(1);<br>  if (!userResult.isAccepted()) {<br>    return res.status(429).json({<br>      error: &#39;Rate limit exceeded&#39;,<br>      retryAfter: userResult.getRetryAfter()<br>    });<br>  }<br>  next();<br>};</pre><p>Note the different status codes: 503 for global (system issue), 429 for per-user (your issue). This helps clients understand what’s happening.</p><h3>Different costs for different endpoints</h3><p>Not all endpoints are created equal. Reading a user profile is cheap. Generating a PDF report with 10,000 rows is expensive. You can reflect this in your rate limiting:</p><pre>const factory = new RateLimiterFactory({<br>  policy: &#39;token_bucket&#39;,<br>  id: &#39;api&#39;,<br>  limit: 1000,<br>  rate: { interval: &#39;1 hour&#39;, amount: 1000 }<br>}, storage);</pre><pre>// Simple read: 1 token<br>app.get(&#39;/api/user/:id&#39;, async (req, res) =&gt; {<br>  const limiter = factory.create(req.user.id);<br>  const result = await limiter.consume(1);<br>  // handle result...<br>});<br><br>// Complex search: 10 tokens<br>app.post(&#39;/api/search&#39;, async (req, res) =&gt; {<br>  const limiter = factory.create(req.user.id);<br>  const result = await limiter.consume(10);<br>  // handle result...<br>});<br><br>// Heavy report: 100 tokens<br>app.post(&#39;/api/reports&#39;, async (req, res) =&gt; {<br>  const limiter = factory.create(req.user.id);<br>  const result = await limiter.consume(100);<br>  // handle result...<br>});</pre><p>Now users have 1000 tokens to spend however they want. They can make 1000 simple requests, or 10 reports, or any combination. This is way more flexible than separate limits per endpoint.</p><h3>The reservation pattern</h3><p>Here’s a powerful pattern that’s often overlooked: reservations. Say you have long-running operations like video processing, large file uploads, or batch jobs. You want to rate limit how many jobs a user can start, but you don’t want to reject them immediately if they’re at their limit — you want to queue them and wait for capacity.</p><pre>const limiter = factory.create(req.user.id);</pre><pre>// Reserve tokens, wait up to 30 seconds for availability<br>try {<br>  const reservation = await limiter.reserve(1, 30);<br>  if (!reservation.isAccepted()) {<br>    return res.status(429).json({<br>      error: &#39;Rate limit exceeded&#39;,<br>      message: &#39;Too many concurrent jobs&#39;,<br>      retryAfter: reservation.getRetryAfter()<br>    });<br>  }<br>  // Wait for the reservation (blocks until tokens are available or timeout)<br>  await reservation.wait();<br>  // Now we&#39;re guaranteed to have the tokens<br>  res.json({ message: &#39;Job started&#39;, jobId: &#39;...&#39; });<br>  startJobProcessing(req.body);<br>} catch (error) {<br>  // Handle MaxWaitDurationExceededError<br>  return res.status(429).json({<br>    error: &#39;Rate limit exceeded&#39;,<br>    message: &#39;Unable to acquire tokens within wait time&#39;<br>  });<br>}</pre><p>The key difference between consume() and reserve():</p><ul><li>consume(): Either gets tokens immediately or fails—perfect for real-time API requests</li><li>reserve(): Will wait (up to your timeout) for tokens to become available—ideal for job queues and async operations</li></ul><p>This is perfect for smoothing out traffic spikes. Instead of rejecting users during peak times, you queue them up and process requests as capacity becomes available. Your users get a better experience (queued instead of rejected), and you get better resource utilization.</p><h3>Scaling to multiple servers</h3><p>Once you have multiple application servers, in-memory storage stops working. Each server has its own memory, so the limits aren’t shared. User makes 100 requests to server A, then 100 to server B — they’ve just bypassed your 100-request limit.</p><p>You need shared storage. Redis is the usual choice:</p><pre>import { StorageInterface, State } from &#39;@zeitar/throttle&#39;;<br>import { createClient, RedisClientType } from &#39;redis&#39;;</pre><pre>export class RedisStorage implements StorageInterface {<br>  private client: RedisClientType;<br>  constructor(client: RedisClientType) {<br>    this.client = client;<br>  }<br>  async save(key: string, state: State, ttl: number): Promise&lt;void&gt; {<br>    const serialized = JSON.stringify({<br>      tokens: state.tokens,<br>      timestamp: state.timestamp,<br>      hitCount: state.hitCount<br>    });<br>    await this.client.set(key, serialized, { EX: ttl });<br>  }<br>  async fetch(key: string): Promise&lt;State | null&gt; {<br>    const data = await this.client.get(key);<br>    if (!data) return null;<br>    const parsed = JSON.parse(data);<br>    return {<br>      tokens: parsed.tokens,<br>      timestamp: parsed.timestamp,<br>      hitCount: parsed.hitCount ?? 0<br>    };<br>  }<br>  async delete(key: string): Promise&lt;void&gt; {<br>    await this.client.del(key);<br>  }<br>}<br>// Usage<br>const redisClient = createClient({ url: &#39;redis://localhost:6379&#39; });<br>await redisClient.connect();<br>const factory = new RateLimiterFactory(<br>  {<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;api&#39;,<br>    limit: 1000,<br>    rate: { interval: &#39;1 hour&#39;, amount: 1000 }<br>  },<br>  new RedisStorage(redisClient)<br>);</pre><p>Now all your servers share the same rate limit state. Problem solved.</p><h3>Adding distributed locking</h3><p>There’s one more thing you need for multi-server deployments: locking. Without it, you can have race conditions where two servers read the same state simultaneously, both think they have tokens available, both decrement, and now you’ve issued more tokens than you should have.</p><pre>import { LockInterface } from &#39;@zeitar/throttle&#39;;</pre><pre>export class RedisLock implements LockInterface {<br>  private client: RedisClientType;<br>  private lockTimeout: number;<br>  constructor(client: RedisClientType, lockTimeout = 5000) {<br>    this.client = client;<br>    this.lockTimeout = lockTimeout;<br>  }<br>  async acquire(key: string): Promise&lt;boolean&gt; {<br>    const lockKey = `lock:${key}`;<br>    const acquired = await this.client.set(lockKey, &#39;1&#39;, {<br>      NX: true,  // Only set if not exists<br>      PX: this.lockTimeout  // Milliseconds<br>    });<br>    return acquired !== null;<br>  }<br>  async release(key: string): Promise&lt;void&gt; {<br>    await this.client.del(`lock:${key}`);<br>  }<br>}<br>const factory = new RateLimiterFactory(<br>  config,<br>  new RedisStorage(redisClient),<br>  new RedisLock(redisClient)<br>);</pre><p>Now your rate limiting works correctly across any number of servers.</p><h3>Dynamic limits based on user behavior</h3><p>Here’s something I implemented for a client: adjust limits based on how trustworthy a user is.</p><pre>const createDynamicLimiter = (user: User) =&gt; {<br>  // New accounts get strict limits<br>  // Accounts older than 90 days with no violations get higher limits<br>  const isTrusted = user.accountAge &gt; 90 &amp;&amp; user.violationCount === 0;</pre><pre>const limit = isTrusted ? 5000 : 1000;<br>  return new RateLimiterFactory({<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;dynamic&#39;,<br>    limit,<br>    rate: { interval: &#39;1 hour&#39;, amount: limit }<br>  }, storage).create(user.id);<br>};<br>app.use(async (req, res, next) =&gt; {<br>  const limiter = createDynamicLimiter(req.user);<br>  const result = await limiter.consume(1);<br>  // check result...<br>});</pre><p>You could also adjust based on:</p><ul><li>Payment tier (paid users get higher limits automatically)</li><li>API key vs OAuth (different trust levels)</li><li>Historical behavior (penalize users who frequently hit limits)</li><li>Time of day (be more lenient during off-peak hours)</li></ul><h3>Putting it all together</h3><p>Here’s a realistic production setup that combines several patterns:</p><pre>import { RateLimiterFactory, CompoundRateLimiterFactory } from &#39;@zeitar/throttle&#39;;<br>import { RedisStorage, RedisLock } from &#39;./redis-impl&#39;;<br>import { createClient } from &#39;redis&#39;;</pre><pre>const redisClient = createClient({ url: process.env.REDIS_URL });<br>await redisClient.connect();<br>const storage = new RedisStorage(redisClient);<br>const lock = new RedisLock(redisClient);<br>// Define tier configurations<br>const createTierLimiter = (tier: &#39;free&#39; | &#39;pro&#39; | &#39;enterprise&#39;) =&gt; {<br>  const configs = {<br>    free: { burst: 10, sustained: 100, daily: 1000 },<br>    pro: { burst: 50, sustained: 1000, daily: 50000 },<br>    enterprise: { burst: 200, sustained: 10000, daily: 1000000 }<br>  };<br>  const config = configs[tier];<br>  return new CompoundRateLimiterFactory([<br>    new RateLimiterFactory({<br>      policy: &#39;token_bucket&#39;,<br>      id: `${tier}-burst`,<br>      limit: config.burst,<br>      rate: { interval: &#39;1 second&#39;, amount: config.burst }<br>    }, storage, lock),<br>    new RateLimiterFactory({<br>      policy: &#39;token_bucket&#39;,<br>      id: `${tier}-sustained`,<br>      limit: config.sustained,<br>      rate: { interval: &#39;1 minute&#39;, amount: config.sustained }<br>    }, storage, lock),<br>    new RateLimiterFactory({<br>      policy: &#39;fixed_window&#39;,<br>      id: `${tier}-daily`,<br>      limit: config.daily,<br>      rate: { interval: &#39;1 day&#39;, amount: config.daily }<br>    }, storage, lock)<br>  ]);<br>};<br>const tierLimiters = {<br>  free: createTierLimiter(&#39;free&#39;),<br>  pro: createTierLimiter(&#39;pro&#39;),<br>  enterprise: createTierLimiter(&#39;enterprise&#39;)<br>};<br>app.use(async (req, res, next) =&gt; {<br>  const tier = req.user?.tier || &#39;free&#39;;<br>  const compound = tierLimiters[tier];<br>  const limiter = compound.create(req.user?.id || req.ip);<br>  try {<br>    const result = await limiter.consume(1);<br>    res.setHeader(&#39;X-RateLimit-Tier&#39;, tier);<br>    res.setHeader(&#39;X-RateLimit-Remaining&#39;, result.getRemainingTokens().toString());<br>    if (!result.isAccepted()) {<br>      return res.status(429).json({<br>        error: &#39;Rate limit exceeded&#39;,<br>        tier,<br>        retryAfter: result.getRetryAfter()<br>      });<br>    }<br>    next();<br>  } catch (error) {<br>    console.error(&#39;Rate limiter error:&#39;, error);<br>    next(); // Fail open<br>  }<br>});</pre><p>This gives you:</p><ul><li>Three tiers with different limits</li><li>Burst protection (per-second limit)</li><li>Sustained protection (per-minute limit)</li><li>Daily quotas</li><li>Works across multiple servers (Redis)</li><li>Thread-safe (distributed locking)</li><li>Fails gracefully if Redis goes down</li></ul><h3>Performance notes</h3><p>Some real numbers from production:</p><p>In-memory storage: Sub-millisecond latency, about 100 bytes per active limiter. With 1 million active users, you’re looking at ~100MB of memory. Very fast, but doesn’t work with multiple servers.</p><p>Redis (local): 1–5ms latency. You’re adding a network hop to every request, but it’s usually on the same local network so it’s fast.</p><p>Redis (cloud): 5–20ms latency depending on distance. Still acceptable for most APIs, but something to keep in mind if you’re optimizing for the last bit of performance.</p><p>Locking overhead: Adds 1–3ms. Worth it for correctness in multi-server deployments.</p><p>All the algorithms are O(1) — constant time regardless of request rate. They don’t slow down as you scale.</p><h3>When things go wrong</h3><p>Redis goes down: Your rate limiter will throw errors. This is why the “fail open” pattern is critical — log the error but let requests through. Better to temporarily lose rate limiting than to block all traffic.</p><p>Lock timeout: If a server crashes while holding a lock, the lock will expire after your timeout (default 5 seconds). New requests will wait briefly then proceed. Not perfect, but handles the case.</p><p>Misconfigured limits: Setting the daily limit to 100 instead of 10,000 is easier than you think. You’ll figure it out quickly if your monitoring shows a spike in 429 responses. This is why you need monitoring.</p><h3>The path forward</h3><p>Start simple:</p><ol><li>Basic rate limiting with Token Bucket and in-memory storage</li><li>Add monitoring to see actual usage patterns</li><li>Adjust limits based on data</li><li>Add tier-based limits when you have paid plans</li><li>Move to Redis when you add a second server</li><li>Add compound limits if you’re seeing specific attack patterns</li></ol><p>Don’t build the complex version on day one. You won’t know what limits make sense until you have real traffic.</p><h3>Open source contribution</h3><p>Everything here is built on <a href="https://github.com/kzeitar/throttle">https://github.com/kzeitar/throttle</a>. If you want to:</p><ul><li>Add a new storage backend (PostgreSQL, DynamoDB, whatever)</li><li>Implement a new algorithm</li><li>Improve the existing code</li><li>Add examples for your favorite framework</li></ul><p>The codebase is designed to be extended. It’s TypeScript, well-tested, and the architecture is straightforward. Pull requests welcome.</p><p>Links:</p><ul><li>GitHub: <a href="https://github.com/kzeitar/throttle">https://github.com/kzeitar/throttle</a></li><li>Docs: <a href="https://github.com/kzeitar/throttle#documentation">https://github.com/kzeitar/throttle#documentation</a></li><li>Custom storage guide: <a href="https://github.com/kzeitar/throttle/blob/main/docs/custom-storage.md">https://github.com/kzeitar/throttle/blob/main/docs/custom-storage.md</a></li></ul><p>Series:</p><ul><li><a href="https://medium.com/@khaledzeitar/why-your-node-js-api-needs-rate-limiting-cc49b4abcf6b">Part 1: Why Your API Needs Rate Limiting</a></li><li><a href="https://medium.com/@khaledzeitar/from-zero-to-production-implementing-rate-limiting-in-node-js-51b4408a876d">Part 2: From Zero to Production</a></li></ul><p>That’s it. You now know more about rate limiting than most backend engineers. Go build something that doesn’t fall over when it gets popular.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=131ed816da45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Production: Implementing Rate Limiting in Node.js]]></title>
            <link>https://medium.com/@khaledzeitar/from-zero-to-production-implementing-rate-limiting-in-node-js-51b4408a876d?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b4408a876d</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 19:08:03 GMT</pubDate>
            <atom:updated>2025-12-27T19:16:53.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58XqQfoMNVdvgJnoKxI8PQ.png" /></figure><p>In <a href="https://medium.com/@khaledzeitar/why-your-node-js-api-needs-rate-limiting-cc49b4abcf6b">Part 1</a> we covered why you need rate limiting. Now let’s actually build it.</p><p>This guide walks through a complete implementation — not just the happy path code, but the testing, the edge cases, and the things that will bite you in production if you’re not careful.</p><h3>Installation</h3><pre>npm install @zeitar/throttle</pre><p>That’s genuinely it. No peer dependencies, no configuration to set up first, nothing. Let’s write some code.</p><h3>Understanding the pieces</h3><p>Before we start throwing code around, here’s what you’re working with:</p><p>The factory is your configuration. You set up the rules once — what algorithm to use, what the limits are, etc. Think of it like a blueprint.</p><p>The limiter is an instance for a specific user or IP address. You create one from the factory for each request. Each limiter tracks its own state.</p><p>The storage is where that state lives. Start with in-memory (included). Move to Redis later when you need to scale across servers.</p><p>Simple enough. Now the tricky part is choosing your algorithm.</p><h3>Picking the right algorithm</h3><p>There are four options and the choice actually matters. Here’s how I think about it:</p><h3>Token Bucket — start here</h3><p>This is my default recommendation. Here’s how it works: every user has a bucket with some number of tokens in it. Each request takes one or more tokens from the bucket. Tokens refill at a steady rate.</p><p>The beautiful part is that users can “save up” tokens and spend them in a burst. If you set a limit of 100 tokens per hour, users can make 20 quick requests in a row if they want — as long as they don’t exceed 100 over the full hour.</p><pre>import { RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>const factory = new RateLimiterFactory(<br>  {<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;api&#39;,<br>    limit: 100,              // bucket holds 100 tokens max<br>    rate: {<br>      interval: &#39;1 hour&#39;,    // refill period<br>      amount: 100            // add 100 tokens per hour<br>    }<br>  },<br>  new InMemoryStorage()<br>);</pre><p>This handles the mobile app scenario perfectly. App comes back online, needs to sync 15 items, makes 15 quick requests, all good. But someone trying to abuse your API can’t sustain high traffic.</p><p>Use this for general-purpose APIs, microservices, most REST endpoints.</p><h3>Fixed Window — simple quotas</h3><p>Count requests in fixed time blocks. 100 requests from 2:00 to 3:00, then reset at 3:00.</p><pre>const factory = new RateLimiterFactory(<br>  {<br>    policy: &#39;fixed_window&#39;,<br>    id: &#39;daily-quota&#39;,<br>    limit: 1000,<br>    rate: {<br>      interval: &#39;1 day&#39;,<br>      amount: 1000<br>    }<br>  },<br>  new InMemoryStorage()<br>);</pre><p>The problem: users can make 1000 requests at 11:59pm, then another 1000 at 12:01am. You get a burst at the boundary. For many use cases this is fine — if you’re doing daily quotas or billing limits, it doesn’t really matter.</p><p>Use this when you need simple “X per day” limits and don’t care about boundary bursts.</p><h3>Sliding Window — precision matters</h3><p>This is like Fixed Window but without the boundary problem. It tracks exact timestamps and gives you smooth, precise limiting.</p><pre>const factory = new RateLimiterFactory(<br>  {<br>    policy: &#39;sliding_window&#39;,<br>    id: &#39;payments&#39;,<br>    limit: 10,<br>    rate: {<br>      interval: &#39;1 minute&#39;,<br>      amount: 10<br>    }<br>  },<br>  new InMemoryStorage()<br>);</pre><p>The tradeoff is complexity and memory — you’re storing more state. Use this for sensitive operations where precision matters: payment processing, password resets, anything security-critical.</p><h3>No Limit — testing mode</h3><p>Does exactly what it says. Accepts everything. Use this in your test suite so your tests don’t get rate limited.</p><h3>Decision tree</h3><ul><li>Building a general API? Token Bucket</li><li>Need daily/hourly quotas? Fixed Window</li><li>Handling payments or auth? Sliding Window</li><li>Running tests? No Limit</li></ul><p>When in doubt, use Token Bucket. It’s the sweet spot between flexibility and simplicity.</p><h3>Complete Express implementation</h3><p>Alright, let’s build a real middleware that you can actually use:</p><pre>import express, { Request, Response, NextFunction } from &#39;express&#39;;<br>import { RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>const app = express();<br>const globalLimiter = new RateLimiterFactory(<br>  {<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;global&#39;,<br>    limit: 100,<br>    rate: { interval: &#39;1 minute&#39;, amount: 100 }<br>  },<br>  new InMemoryStorage()<br>);<br>const rateLimitMiddleware = (factory: RateLimiterFactory) =&gt; {<br>  return async (req: Request, res: Response, next: NextFunction) =&gt; {<br>    const identifier = req.ip || &#39;unknown&#39;;<br>    const limiter = factory.create(identifier);<br>    try {<br>      const result = await limiter.consume(1);<br>      // These headers are part of the spec (RFC 6585)<br>      res.setHeader(&#39;X-RateLimit-Limit&#39;, &#39;100&#39;);<br>      res.setHeader(&#39;X-RateLimit-Remaining&#39;, result.getRemainingTokens().toString());<br>      res.setHeader(&#39;X-RateLimit-Reset&#39;, Math.floor(result.getRetryAfter() + Date.now() / 1000).toString());<br>      if (!result.isAccepted()) {<br>        res.setHeader(&#39;Retry-After&#39;, result.getRetryAfter().toString());<br>        return res.status(429).json({<br>          error: &#39;Too Many Requests&#39;,<br>          message: &#39;Rate limit exceeded&#39;,<br>          retryAfter: result.getRetryAfter()<br>        });<br>      }<br>      next();<br>    } catch (error) {<br>      // IMPORTANT: Fail open. If rate limiting breaks, don&#39;t block all traffic.<br>      console.error(&#39;Rate limiter error:&#39;, error);<br>      next();<br>    }<br>  };<br>};<br>app.use(rateLimitMiddleware(globalLimiter));<br>app.get(&#39;/api/data&#39;, (req, res) =&gt; {<br>  res.json({ data: &#39;Your data here&#39; });<br>});<br>app.listen(3000);</pre><p>A few things to note here:</p><p>The headers matter. X-RateLimit-Remaining tells clients how many requests they have left. Retry-After tells them when to try again. Good HTTP clients will automatically back off based on these.</p><p>Status code 429 is the standard for “you’re rate limited.” Use it.</p><p>That try/catch is critical. If your rate limiter throws an error, you don’t want to take down your entire API. Log it and let the request through. This is called “failing open” and it’s the right default.</p><h3>Different limits for different endpoints</h3><p>Real APIs need different rules for different operations. Authentication needs to be strict. Public endpoints can be loose. Here’s how:</p><pre>const storage = new InMemoryStorage();</pre><pre>const authLimiter = new RateLimiterFactory(<br>  {<br>    policy: &#39;sliding_window&#39;,<br>    id: &#39;auth&#39;,<br>    limit: 5,<br>    rate: { interval: &#39;15 minutes&#39;, amount: 5 }<br>  },<br>  storage<br>);<br>const readLimiter = new RateLimiterFactory(<br>  {<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;read&#39;,<br>    limit: 1000,<br>    rate: { interval: &#39;1 hour&#39;, amount: 1000 }<br>  },<br>  storage<br>);<br>const writeLimiter = new RateLimiterFactory(<br>  {<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;write&#39;,<br>    limit: 100,<br>    rate: { interval: &#39;1 hour&#39;, amount: 100 }<br>  },<br>  storage<br>);<br>app.post(&#39;/auth/login&#39;, rateLimitMiddleware(authLimiter), loginHandler);<br>app.get(&#39;/api/users&#39;, rateLimitMiddleware(readLimiter), getUsersHandler);<br>app.post(&#39;/api/users&#39;, rateLimitMiddleware(writeLimiter), createUserHandler);</pre><p>Notice I’m using the same storage instance for all of them. That’s intentional — they can share the underlying storage, but each limiter tracks its own keys and limits.</p><h3>Testing this properly</h3><p>Here’s the thing about testing rate limiters: you need to actually hit the limit to verify it works. Don’t just test the happy path.</p><pre>import { RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>describe(&#39;Rate Limiter&#39;, () =&gt; {<br>  it(&#39;should accept requests within limit&#39;, async () =&gt; {<br>    const storage = new InMemoryStorage();<br>    const factory = new RateLimiterFactory(<br>      {<br>        policy: &#39;token_bucket&#39;,<br>        id: &#39;test&#39;,<br>        limit: 10,<br>        rate: { interval: &#39;1 minute&#39;, amount: 10 }<br>      },<br>      storage<br>    );<br>    const limiter = factory.create(&#39;user-123&#39;);<br>    // First 10 should work<br>    for (let i = 0; i &lt; 10; i++) {<br>      const result = await limiter.consume(1);<br>      expect(result.isAccepted()).toBe(true);<br>    }<br>    // 11th should be rejected<br>    const result = await limiter.consume(1);<br>    expect(result.isAccepted()).toBe(false);<br>    expect(result.getRetryAfter()).toBeGreaterThan(0);<br>  });<br>  it(&#39;should isolate different users&#39;, async () =&gt; {<br>    const storage = new InMemoryStorage();<br>    const factory = new RateLimiterFactory(<br>      {<br>        policy: &#39;token_bucket&#39;,<br>        id: &#39;test&#39;,<br>        limit: 5,<br>        rate: { interval: &#39;1 minute&#39;, amount: 5 }<br>      },<br>      storage<br>    );<br>    const user1Limiter = factory.create(&#39;user-1&#39;);<br>    const user2Limiter = factory.create(&#39;user-2&#39;);<br>    // Burn through user 1&#39;s tokens<br>    for (let i = 0; i &lt; 5; i++) {<br>      await user1Limiter.consume(1);<br>    }<br>    const user1Result = await user1Limiter.consume(1);<br>    const user2Result = await user2Limiter.consume(1);<br>    expect(user1Result.isAccepted()).toBe(false);<br>    expect(user2Result.isAccepted()).toBe(true);<br>  });<br>});</pre><p>For integration tests where you don’t want rate limiting interfering:</p><pre>import { NoLimiter } from &#39;@zeitar/throttle&#39;;</pre><pre>const limiter = process.env.NODE_ENV === &#39;test&#39;<br>  ? new NoLimiter()<br>  : factory.create(userId);</pre><h3>Monitoring</h3><p>You can’t improve what you don’t measure. Here’s what to track:</p><pre>const rateLimitMiddleware = (factory: RateLimiterFactory) =&gt; {<br>  return async (req: Request, res: Response, next: NextFunction) =&gt; {<br>    const identifier = req.ip || &#39;unknown&#39;;<br>    const limiter = factory.create(identifier);<br>    const startTime = Date.now();</pre><pre>try {<br>      const result = await limiter.consume(1);<br>      logger.info(&#39;rate_limit_check&#39;, {<br>        identifier,<br>        accepted: result.isAccepted(),<br>        remaining: result.getRemainingTokens(),<br>        retryAfter: result.getRetryAfter(),<br>        latency: Date.now() - startTime,<br>        endpoint: req.path,<br>        method: req.method<br>      });<br>      if (!result.isAccepted()) {<br>        logger.warn(&#39;rate_limit_exceeded&#39;, {<br>          identifier,<br>          endpoint: req.path,<br>          retryAfter: result.getRetryAfter()<br>        });<br>      }<br>      // rest of the middleware...<br>    }<br>  };<br>};</pre><p>Track:</p><ul><li>How often you’re rejecting requests (if it’s too high, your limits are too strict)</li><li>Which IPs/users are getting rate limited (might indicate abuse or a bug in their code)</li><li>Latency of the rate limiter itself (should be sub-millisecond with in-memory storage)</li></ul><h3>Common mistakes to avoid</h3><h3>Mistake 1: Using a different identifier for every request</h3><pre>// DON&#39;T DO THIS<br>const limiter = factory.create(Math.random().toString());</pre><p>Every request gets a new limiter with a fresh limit. You’ve effectively disabled rate limiting. Use something consistent like user ID or IP address.</p><h3>Mistake 2: Not handling the case where the rate limiter fails</h3><pre>// BAD<br>try {<br>  const result = await limiter.consume(1);<br>  if (!result.isAccepted()) {<br>    return res.status(429).json({ error: &#39;Rate limited&#39; });<br>  }<br>} catch (error) {<br>  // This blocks ALL traffic if the rate limiter breaks<br>  return res.status(500).json({ error: &#39;Server error&#39; });<br>}</pre><p>If your rate limiter throws (storage is down, etc), you’re now rejecting all traffic. Always fail open:</p><pre>// GOOD<br>try {<br>  const result = await limiter.consume(1);<br>  if (!result.isAccepted()) {<br>    return res.status(429).json({ error: &#39;Rate limited&#39; });<br>  }<br>} catch (error) {<br>  logger.error(&#39;Rate limiter failed&#39;, error);<br>  // Continue - don&#39;t block the request<br>}<br>next();</pre><h3>Mistake 3: Forgetting to set the Retry-After header</h3><p>Clients need to know when they can try again. Without this header, they’ll just retry immediately and hammer your API harder:</p><pre>if (!result.isAccepted()) {<br>  res.setHeader(&#39;Retry-After&#39;, result.getRetryAfter().toString());<br>  return res.status(429).json({<br>    error: &#39;Too many requests&#39;,<br>    retryAfter: result.getRetryAfter()<br>  });<br>}</pre><h3>Mistake 4: Testing in production first</h3><p>Add this to a staging environment first. Send some traffic through it. Make sure your limits make sense before you deploy to production and potentially lock out real users.</p><h3>Layered protection: combining with network-level rate limiting</h3><p>Remember: this library handles application-level rate limiting. For complete protection, you need multiple layers.</p><p>Here’s a realistic production setup:</p><p><strong>Layer 1: Edge protection (Cloudflare/AWS Shield)</strong></p><ul><li>Blocks massive DDoS attacks before they hit your infrastructure</li><li>Handles millions of requests per second</li><li>Geographic blocking, bot detection</li></ul><p><strong>Layer 2: Reverse proxy (NGINX/Caddy)</strong></p><ul><li>Basic rate limiting at the connection level</li><li>Protects against traffic spikes and simple floods</li></ul><pre># NGINX example - limit connections before they hit your app<br>limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;</pre><pre>server {<br>    location /api {<br>        limit_req zone=api burst=20 nodelay;<br>        proxy_pass http://node-app;<br>    }<br>}</pre><p><strong>Layer 3: Application level (this library)</strong></p><ul><li>Per-user quotas and business logic</li><li>Different limits for different tiers</li><li>Authentication attempt limiting</li><li>Expensive operation throttling</li></ul><p>This gives you defense in depth. The proxy blocks obvious abuse cheaply, and your application handles the nuanced cases.</p><p>Why not just use NGINX rate limiting for everything? Because NGINX doesn’t know about your users, their subscription tiers, which endpoints are expensive, or your business rules. That’s what application-level limiting is for.</p><p>A typical production setup might have NGINX at 100 requests/second per IP (generous) and then use this library for the real business logic — 1000/hour for free users, 10000/hour for paid users, 5 attempts per 15 minutes for auth endpoints, etc.</p><h3>Production checklist</h3><p>Before you ship this:</p><ul><li>Test with realistic traffic patterns (not just single requests)</li><li>Make sure your limits aren’t too strict (check your actual usage patterns first)</li><li>Set up monitoring and alerts for when rate limits are hit</li><li>Document your rate limits somewhere clients can see them</li><li>Have a plan for adjusting limits (store them in config, not hardcoded)</li><li>Test the failure mode (what happens if storage goes down?)</li><li>Make sure you’re using consistent identifiers (user ID, IP, etc)</li><li>Add network-level rate limiting (NGINX, Cloudflare, etc) for DDoS protection</li><li>Configure your reverse proxy with basic connection limits</li><li>Consider edge protection if you’re expecting high traffic or are a likely target</li></ul><h3>Copy-paste starter</h3><p>Want to just get started? Here’s a template:</p><pre>import express from &#39;express&#39;;<br>import { RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>const app = express();<br>const storage = new InMemoryStorage();<br>const limiters = {<br>  global: new RateLimiterFactory({<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;global&#39;,<br>    limit: 100,<br>    rate: { interval: &#39;1 minute&#39;, amount: 100 }<br>  }, storage),<br>  auth: new RateLimiterFactory({<br>    policy: &#39;sliding_window&#39;,<br>    id: &#39;auth&#39;,<br>    limit: 5,<br>    rate: { interval: &#39;15 minutes&#39;, amount: 5 }<br>  }, storage)<br>};<br>const rateLimit = (limiterKey: keyof typeof limiters) =&gt; {<br>  return async (req, res, next) =&gt; {<br>    const identifier = req.user?.id || req.ip;<br>    const limiter = limiters[limiterKey].create(identifier);<br>    try {<br>      const result = await limiter.consume(1);<br>      res.setHeader(&#39;X-RateLimit-Remaining&#39;, result.getRemainingTokens().toString());<br>      if (!result.isAccepted()) {<br>        res.setHeader(&#39;Retry-After&#39;, result.getRetryAfter().toString());<br>        return res.status(429).json({<br>          error: &#39;Too Many Requests&#39;,<br>          retryAfter: result.getRetryAfter()<br>        });<br>      }<br>      next();<br>    } catch (error) {<br>      console.error(&#39;Rate limiter error:&#39;, error);<br>      next();<br>    }<br>  };<br>};<br>app.use(&#39;/api&#39;, rateLimit(&#39;global&#39;));<br>app.post(&#39;/auth/login&#39;, rateLimit(&#39;auth&#39;), loginHandler);<br>app.listen(3000);</pre><h3>What’s next</h3><p>This gets you a solid, production-ready rate limiter for a single-server deployment. The next article covers advanced patterns:</p><ul><li>Different limits for free vs paid users</li><li>Combining multiple limits (10/second AND 1000/hour)</li><li>Scaling to multiple servers with Redis</li><li>Custom cost per endpoint (simple requests cost 1 token, expensive operations cost 10)</li><li>Dynamic limits based on user behavior</li></ul><p>But honestly, what we’ve covered here is enough for most applications. Don’t over-engineer it until you need to.</p><p>Links:</p><ul><li>GitHub: <a href="https://github.com/kzeitar/throttle">https://github.com/kzeitar/throttle</a></li><li>Full docs: <a href="https://github.com/kzeitar/throttle#documentation">https://github.com/kzeitar/throttle#documentation</a></li><li>Framework examples: <a href="https://github.com/kzeitar/throttle/blob/main/docs/framework-integration.md">https://github.com/kzeitar/throttle/blob/main/docs/framework-integration.md</a></li></ul><p>Series:</p><ul><li><a href="https://medium.com/@khaledzeitar/why-your-node-js-api-needs-rate-limiting-cc49b4abcf6b">Part 1: Why Your API Needs Rate Limiting</a></li><li><a href="https://medium.com/@khaledzeitar/advanced-rate-limiting-patterns-multi-tier-compound-limiters-and-distributed-systems-131ed816da45">Part 3: Advanced Patterns and Scaling</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b4408a876d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Node.js API Needs Rate Limiting]]></title>
            <link>https://medium.com/@khaledzeitar/why-your-node-js-api-needs-rate-limiting-cc49b4abcf6b?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc49b4abcf6b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 18:58:22 GMT</pubDate>
            <atom:updated>2025-12-26T19:08:23.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NB0j4O8XeUfFaIV4SSpG7Q.png" /></figure><p>Picture this scenario: 3:47 AM on a Monday. An on-call engineer’s phone erupts with notifications — not the gentle buzz of a single message, but the relentless vibration of an emergency. They grab it with one eye still closed to see their screen flooded with alerts. The AWS CloudWatch alarm: “API response time &gt;10s.” The PagerDuty escalation: “Critical — API Gateway 5xx errors &gt;50%.” A text from the CTO: “We’re down. NOW.”</p><p>They stumble to their laptop, still in the clothes they fell asleep in after a Sunday deploy. The Datadog dashboard loads — and reveals the nightmare. The /api/users endpoint: 2.3 million requests in the past 6 hours. Normal traffic? Maybe 50,000 per day. The graph looks like someone held down the refresh button with a brick.</p><p>The logs tell the story: Same IP address. Same user agent. Request after request after request, each one identical: GET /api/users?page=1. A retry header in every single one: X-Retry-Count: 847. Someone&#39;s client was stuck in an infinite loop, and they&#39;d been asleep for hours while their code hammered the API.</p><p>The damage: Response times at 23 seconds. Database connections maxed out. Redis struggling. Legitimate users getting timeouts on login. The support Slack channel already had 15 messages from angry customers.</p><p>The culprit? A mobile app developer who’d pushed a hotfix Friday night. When finally reached, they were mortified: “I just added a retry for network errors. I didn’t think about what happens if the <em>server</em> is slow.”</p><p>Their app had 5,000 active users. Each one retrying every failed request. Exponential backoff? Nope. Circuit breaker? Nope. Rate limiting on the API? You already know the answer.</p><p>By the time the flood was killed with an emergency IP block, the company had racked up $8,347 in infrastructure overages. Their SLA? Thoroughly violated. Their on-call rotation? Thoroughly exhausted.</p><p>They didn’t have rate limiting. That changed the same day.</p><p>This isn’t a hypothetical scenario — it’s a pattern that plays out across the industry with frightening regularity.</p><h3>The problem nobody talks about until it’s too late</h3><p>Here’s the thing about building APIs: you start small, maybe an internal tool or a simple REST service. You’ve got elegant endpoints, clean code, optimized queries. Everything works great with your handful of users making a few hundred requests a day.</p><p>Then one of three things happens:</p><p>Scenario A: Someone integrates your API into their mobile app and forgets to add request deduplication. Now you’re getting 50 requests per second from a single device because their offline sync logic is broken.</p><p>Scenario B: Your service gets popular on Product Hunt. Traffic spikes 100x overnight. Suddenly every request is slow because you’re overwhelmed, which makes clients retry, which makes everything slower, which makes more clients retry… death spiral.</p><p>Scenario C: Someone decides to scrape your entire API. Or run a dictionary attack against your auth endpoint. Or just be a jerk and see how much traffic it takes to knock you offline.</p><p>Without rate limiting, you’re completely exposed to all of this. And the worst part is you won’t see it coming.</p><h3>What rate limiting actually does</h3><p>At its core, rate limiting is simple: it controls how many requests a client can make in a given time period. Think of it like a bouncer at a club who makes sure no one person rushes the door and overwhelms the venue.</p><p>But the devil’s in the details. A naive implementation might just count requests and block everything after you hit a threshold. That breaks legitimate use cases. Your mobile app needs to sync 20 items when it comes back online — should that really count as 20 separate limits? Probably not.</p><p>Good rate limiting needs to:</p><ul><li>Allow short bursts of legitimate traffic</li><li>Prevent sustained abuse</li><li>Be fair across all users</li><li>Work across multiple servers in a cluster</li><li>Give clients clear feedback about when they can retry</li></ul><p>That last point is critical and often overlooked. If you’re going to reject a request, you need to tell the client when they can try again. Otherwise they’ll just retry immediately and make everything worse.</p><h3>What rate limiting can’t do (and that’s okay)</h3><p>Let’s be clear about something important: application-level rate limiting like this library is not designed to protect against DDoS attacks or massive traffic floods. Here’s why:</p><p>By the time a request reaches your Node.js application, you’ve already consumed resources — your server accepted the connection, parsed the HTTP headers, routed it to your app. If someone sends 100,000 requests per second trying to DoS you, your application will try to process all of them just to rate limit them. That defeats the purpose.</p><p>Real DoS protection needs to happen much earlier in the stack:</p><ul><li>At the network edge: Use Cloudflare, AWS Shield, or similar services</li><li>At the reverse proxy: NGINX rate limiting, Caddy rate limit module, Apache mod_ratelimit</li><li>At the load balancer: Most cloud load balancers have built-in rate limiting</li></ul><p>These solutions are designed to reject traffic before it consumes your application resources. They’re written in C/Rust, they run at the network layer, and they can handle millions of requests per second with minimal overhead.</p><p>So what is application-level rate limiting good for?</p><p>It protects against:</p><ul><li>Misbehaving clients (bugs, infinite loops, retry storms)</li><li>Abusive users (scrapers, brute force attacks, quota violations)</li><li>Resource exhaustion (one user monopolizing expensive operations)</li><li>Third-party API quota management (staying under external service limits)</li><li>Fair usage enforcement (different limits for free vs paid tiers)</li></ul><p>Think of it this way: network-level protection is your castle walls and moat. Application-level rate limiting is the guards checking IDs at the door. You need both, but they serve different purposes.</p><p>In practice, you want layered security:</p><ol><li>CloudFlare/AWS WAF blocks obvious attacks at the edge</li><li>NGINX rate limiting handles traffic spikes at the proxy layer</li><li>This library manages per-user quotas, authentication attempts, and business logic limits</li></ol><p>This library solves the “legitimate but problematic traffic” problem, not the “someone is trying to knock you offline” problem. And that’s exactly what it should do.</p><h3>The real cost of ignoring this</h3><p>Here’s what happens when you don’t have rate limiting:</p><p>The incident above cost $8,347 in infrastructure overages — and they caught it within 6 hours. But there are worse cases. One startup had someone discover their image processing API and process their entire photo library through it. 50,000 images. At $0.02 per image plus compute costs, that was a $3,000 surprise on top of the performance degradation.</p><p>But it’s not just money. When one client monopolizes your resources, everyone else suffers. Your API slows down for legitimate users. You start getting support tickets. Your error rates spike. If you’re calling third-party APIs, you might blow through your quotas with those services too.</p><p>And the security implications are worse. Without rate limiting on authentication endpoints, you’re basically inviting credential stuffing attacks. Someone can try thousands of username/password combinations and you have no defense except maybe noticing it in your logs after the fact.</p><h3>Why @zeitar/throttle exists</h3><p>Looking at rate limiting solutions in the Node.js ecosystem, there’s a gap. Most existing libraries have limitations:</p><ul><li>Tied to specific frameworks (Express only, Fastify only)</li><li>Framework-agnostic ones often have awkward APIs</li><li>TypeScript support is often an afterthought</li><li>Force a choice between simplicity (but limited features) or power (but complex setup)</li><li>Almost none support multiple algorithms</li></ul><p>The goal was something different: full TypeScript support from day one. Multiple algorithms because different scenarios need different approaches. Zero dependencies to keep the footprint small. And clean architecture that’s actually readable.</p><p>That’s @zeitar/throttle: <a href="https://github.com/kzeitar/throttle">https://github.com/kzeitar/throttle</a></p><h3>What makes it different</h3><p>The library supports four rate limiting algorithms. Most libraries give you one and call it a day, but here’s why having options matters:</p><p>Token Bucket is what you want for most APIs. Users get a bucket of tokens that refills over time. They can make a burst of requests (using multiple tokens at once) but can’t sustain high traffic indefinitely. This handles the mobile app sync scenario perfectly.</p><p>Fixed Window is simpler — count requests in hourly or daily chunks. It’s great for “you get 1000 API calls per day” style quotas. The downside is you can game it by making 1000 requests at 11:59pm and another 1000 at 12:01am, but for many use cases that’s fine.</p><p>Sliding Window is the most precise. It doesn’t have the boundary problem that Fixed Window has. You want this for sensitive operations like payment processing or password resets where precision matters more than performance.</p><p>No Limit is for testing. Sometimes you need to disable rate limiting in your test suite or for specific trusted clients.</p><p>Here’s the simplest possible usage:</p><pre>import { RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>const factory = new RateLimiterFactory(<br>  {<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;api&#39;,<br>    limit: 100,<br>    rate: {<br>      interval: &#39;1 hour&#39;,<br>      amount: 100<br>    }<br>  },<br>  new InMemoryStorage()<br>);<br>const limiter = factory.create(&#39;user-123&#39;);<br>const result = await limiter.consume(5);<br>if (result.isAccepted()) {<br>  console.log(`Request accepted. ${result.getRemainingTokens()} tokens left`);<br>} else {<br>  console.log(`Rate limited. Try again in ${result.getRetryAfter()} seconds`);<br>}</pre><p>That’s it. No configuration files, no complex setup, no surprises.</p><h3>Using it with Express (or anything else)</h3><p>The library is framework-agnostic, which means it works with Express, Fastify, NestJS, Koa, or whatever you’re using. Here’s a basic Express middleware:</p><pre>import { RateLimiterFactory, InMemoryStorage } from &#39;@zeitar/throttle&#39;;</pre><pre>const factory = new RateLimiterFactory(<br>  {<br>    policy: &#39;token_bucket&#39;,<br>    id: &#39;api&#39;,<br>    limit: 100,<br>    rate: { interval: &#39;1 minute&#39;, amount: 100 }<br>  },<br>  new InMemoryStorage()<br>);<br>app.use(async (req, res, next) =&gt; {<br>  const limiter = factory.create(req.ip);<br>  const result = await limiter.consume();<br>  res.setHeader(&#39;X-RateLimit-Remaining&#39;, result.getRemainingTokens().toString());<br>  if (!result.isAccepted()) {<br>    res.setHeader(&#39;Retry-After&#39;, result.getRetryAfter().toString());<br>    return res.status(429).json({<br>      error: &#39;Too many requests&#39;,<br>      retryAfter: result.getRetryAfter()<br>    });<br>  }<br>  next();<br>});</pre><p>Those headers are important. X-RateLimit-Remaining tells clients how many requests they have left. Retry-After tells them exactly when to try again. Good client libraries will respect these automatically.</p><h3>The architecture underneath</h3><p>I took heavy inspiration from Symfony’s Rate Limiter component, which has been battle-tested in PHP land for years. The core patterns are solid:</p><ul><li>Strategy pattern for different algorithms (they all implement the same interface)</li><li>Factory pattern for creating pre-configured limiters</li><li>Dependency injection for storage backends (start with in-memory, swap to Redis when you need it)</li><li>Composite pattern for combining multiple limiters</li></ul><p>The result is that the code is clean enough that you can actually read it and understand what’s happening. No magic, no surprises.</p><p>All algorithms run in O(1) time — constant performance regardless of how much traffic you have. Memory usage is roughly 100 bytes per active limiter, so even with millions of users you’re talking about hundreds of megabytes, not gigabytes.</p><h3>What if that 3 AM incident had rate limiting?</h3><p>With rate limiting in place, here’s what would have happened instead:</p><p>The mobile app with the infinite retry loop would have hit its rate limit within seconds — maybe after the 100th request instead of the 2.3 millionth. Each subsequent request would return a 429 response with a Retry-After header. The buggy clients would back off (or keep getting rejected, harmlessly). Database connections would stay healthy. Response times would remain under 200ms. Other users wouldn&#39;t have noticed anything wrong.</p><p>Instead of an emergency wake-up call at 3:47 AM, the on-call engineer would check their monitoring dashboard Monday morning, notice a spike in 429 responses from a single IP, and send a polite email to the developer: “Hey, looks like your client is retrying too aggressively. Here’s how to implement exponential backoff.”</p><p>That’s the whole point. Rate limiting turns emergencies into non-events.</p><h3>Getting started</h3><pre>npm install @zeitar/throttle</pre><p>The repository is at <a href="https://github.com/kzeitar/throttle">https://github.com/kzeitar/throttle</a> with full documentation and examples. In the next article I’ll walk through a complete production implementation with testing, monitoring, and all the details you need to actually deploy this.</p><p>Part 3 covers advanced patterns like multi-tier limiting (free vs paid users), compound limiters (enforcing multiple limits at once), and distributed deployments with Redis.</p><h3>One more thing</h3><p>Rate limiting isn’t optional for production APIs. I learned that the expensive way. You can learn it the easy way instead — spend 10 minutes adding this to your application now, before you need it.</p><p>Because you will need it. The only question is whether you add it proactively or reactively at 3am on a weekend.</p><p>Links:</p><ul><li>GitHub: <a href="https://github.com/kzeitar/throttle">https://github.com/kzeitar/throttle</a></li><li>npm: <a href="https://www.npmjs.com/package/@zeitar/throttle">https://www.npmjs.com/package/@zeitar/throttle</a></li><li>Docs: <a href="https://github.com/kzeitar/throttle#documentation">https://github.com/kzeitar/throttle#documentation</a></li></ul><p><a href="https://medium.com/@khaledzeitar/from-zero-to-production-implementing-rate-limiting-in-node-js-51b4408a876d"><em>Next: Part 2 — From Zero to Production: Implementing Rate Limiting in Node.js</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc49b4abcf6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in Go]]></title>
            <link>https://medium.com/@khaledzeitar/concurrency-in-go-380611406fe4?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/380611406fe4</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Sun, 28 May 2023 15:22:04 GMT</pubDate>
            <atom:updated>2023-05-28T15:22:04.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4qz8suDIZBGJ_BGcbdBvw.png" /></figure><p>Concurrency is a crucial aspect of modern software development, enabling programs to effectively utilize the computational resources of modern hardware. Go, the popular programming language developed at Google, has built-in support for concurrency through its goroutines and channels.</p><p>In this article, we will explore the core concepts of Go’s concurrency model, including Goroutines as lightweight threads and Channels for communication and synchronization. We’ll also cover essential Go components like the sync package, context package, atomic package, and select statement.</p><p>Discovering common concurrency patterns such as fan-out/fan-in, worker pool, and pipeline, you’ll learn how to structure and coordinate concurrent operations effectively. Additionally, we’ll discuss error-handling strategies, best practices for writing concurrent code, and techniques for logging and monitoring.</p><p>By the end of this article, you’ll be equipped with the knowledge and tools to build robust and efficient concurrent applications using Go. Let’s embark on this journey and unleash the full potential of Go’s concurrency features!</p><h3>Understanding Goroutines</h3><p>Goroutines are lightweight, independently executing functions that allow us to achieve concurrency in Go. They provide a simple and efficient way to perform concurrent tasks without the need for managing low-level threads manually. Creating a goroutine is as simple as prefixing a function call with the go keyword.</p><pre>func main() {<br>    go myFunction() // Start a goroutine<br>    // Rest of the program<br>}<br><br>func myFunction() {<br>    // Function body<br>}</pre><p>By using goroutines, multiple functions can execute concurrently, and Go’s scheduler manages the execution of these goroutines automatically. The Go scheduler uses a technique called “<a href="https://en.wikipedia.org/wiki/Work_stealing"><strong>work-stealing</strong></a>” to distribute goroutines among available threads, maximizing CPU utilization.</p><h3>Working with Channels</h3><p>Channels provide a safe and efficient way to communicate and synchronize data between goroutines. They act as conduits for passing values between goroutines and help prevent race conditions by enforcing synchronization. Channels can be used for both data transmission and signaling purposes.</p><p>Creating a channel in Go involves using the make function:</p><pre>myChannel := make(chan int) // Create an unbuffered channel of integers</pre><p>There are two types of channels in Go: <strong>unbuffered </strong>and <strong>buffered </strong>channels. <strong>Unbuffered channels</strong> are synchronous, meaning they block the sender until the receiver is ready to receive the value. On the other hand, <strong>buffered channels</strong> have a capacity and allow a certain number of values to be sent without blocking.</p><pre>myBufferedChannel := make(chan int, 10) // Create a buffered channel of integers with capacity 10</pre><p>Channels can be used with the send (&lt;-) and receive (&lt;-) operations to transmit and receive data, respectively.</p><pre>myChannel &lt;- 42 // Sending a value to a channel<br>value := &lt;-myChannel // Receiving a value from a channel</pre><h3>Go Components Used in Concurrency</h3><p>Go’s standard library offers several components that enhance concurrent programming capabilities. Let’s explore some of these components along with code examples showcasing their usage:</p><h4>sync Package:</h4><p>The sync package provides synchronization primitives for coordinating access and synchronization between goroutines. Here&#39;s an example using the Mutex and WaitGroup:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>)<br><br>func main() {<br>    var mutex sync.Mutex<br>    var wg sync.WaitGroup<br><br>    counter := 0<br><br>    // Increment the counter concurrently<br>    for i := 0; i &lt; 10; i++ {<br>        wg.Add(1)<br>        go func() {<br>            defer wg.Done()<br>            mutex.Lock()<br>            counter++<br>            mutex.Unlock()<br>        }()<br>    }<br><br>    wg.Wait()<br><br>    fmt.Println(&quot;Counter:&quot;, counter)<br>}</pre><h4>context Package:</h4><p>The context package provides a flexible framework for managing the lifecycle of concurrent operations, including cancellation, timeouts, and deadline propagation. Here&#39;s an example demonstrating cancellation using context:</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    ctx, cancel := context.WithCancel(context.Background())<br><br>    go func() {<br>        // Simulating a long-running operation<br>        time.Sleep(2 * time.Second)<br>        cancel() // Cancel the operation<br>    }()<br><br>    select {<br>    case &lt;-ctx.Done():<br>        fmt.Println(&quot;Operation cancelled&quot;)<br>    }<br>}</pre><h4>atomic Package:</h4><p>The atomic package contains functions for performing atomic operations on primitive types, allowing safe access to shared memory without explicit locking. Here&#39;s an example using atomic to increment a counter:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync/atomic&quot;<br>)<br><br>func main() {<br>    var counter int64<br><br>    // Increment the counter concurrently<br>    for i := 0; i &lt; 10; i++ {<br>        go func() {<br>            atomic.AddInt64(&amp;counter, 1)<br>        }()<br>    }<br><br>    // Wait for goroutines to complete<br>    // (not required in this specific example)<br><br>    fmt.Println(&quot;Counter:&quot;, atomic.LoadInt64(&amp;counter))<br>}</pre><h4>select Statement:</h4><p>The select statement allows for multiplex multiple channel operations within a single control structure, enabling non-blocking communication and synchronization. Here&#39;s an example using select to receive from multiple channels:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    channel1 := make(chan string)<br>    channel2 := make(chan string)<br><br>    go func() {<br>        time.Sleep(2 * time.Second)<br>        channel1 &lt;- &quot;Message from Channel 1&quot;<br>    }()<br><br>    go func() {<br>        time.Sleep(1 * time.Second)<br>        channel2 &lt;- &quot;Message from Channel 2&quot;<br>    }()<br><br>    select {<br>    case msg := &lt;-channel1:<br>        fmt.Println(&quot;Received from Channel 1:&quot;, msg)<br>    case msg := &lt;-channel2:<br>        fmt.Println(&quot;Received from Channel 2:&quot;, msg)<br>    }<br>}</pre><p>By utilizing these components from Go’s standard library, developers can effectively manage concurrency, synchronization, and communication between goroutines, ensuring the development of efficient and robust concurrent code.</p><h3>Concurrency Patterns in Go</h3><p>Go provides a rich set of concurrency patterns that help developers tackle common challenges and design robust concurrent applications. These patterns, built on top of goroutines and channels, offer effective solutions for managing concurrency. Let’s explore some widely used concurrency patterns in Go:</p><h4>Fan-out/Fan-in:</h4><p>The fan-out/fan-in pattern involves distributing work among multiple goroutines (<strong>fan-out</strong>) and collecting the results from those goroutines (<strong>fan-in</strong>). This pattern is useful when dealing with a large amount of independent work that can be processed concurrently. It improves throughput and parallelism. Here’s an example:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>)<br><br>func main() {<br>    tasks := []int{1, 2, 3, 4, 5}<br><br>    input := make(chan int)<br>    output := make(chan int)<br><br>    // Fan-out<br>    go func() {<br>        for _, task := range tasks {<br>            input &lt;- task<br>        }<br>        close(input)<br>    }()<br><br>    // Worker goroutines<br>    var wg sync.WaitGroup<br>    numWorkers := 3<br><br>    for i := 0; i &lt; numWorkers; i++ {<br>        wg.Add(1)<br>        go func() {<br>            defer wg.Done()<br>            for task := range input {<br>                result := processTask(task)<br>                output &lt;- result<br>            }<br>        }()<br>    }<br><br>    // Fan-in<br>    go func() {<br>        wg.Wait()<br>        close(output)<br>    }()<br><br>    // Collect results<br>    for result := range output {<br>        fmt.Println(&quot;Processed result:&quot;, result)<br>    }<br>}<br><br>func processTask(task int) int {<br>    // Perform task processing<br>    return task * task<br>}</pre><h4>Worker Pool:</h4><p>The worker pool pattern involves creating a fixed number of goroutines (workers) to process a queue of tasks. This pattern is useful when the number of concurrent tasks needs to be limited, such as when interacting with external resources. Here’s an example:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>)<br><br>func main() {<br>    tasks := []int{1, 2, 3, 4, 5}<br><br>    tasksChan := make(chan int)<br>    resultsChan := make(chan int)<br><br>    numWorkers := 3<br><br>    var wg sync.WaitGroup<br><br>    // Create worker goroutines<br>    for i := 0; i &lt; numWorkers; i++ {<br>        wg.Add(1)<br>        go func() {<br>            defer wg.Done()<br>            for task := range tasksChan {<br>                result := processTask(task)<br>                resultsChan &lt;- result<br>            }<br>        }()<br>    }<br><br>    // Enqueue tasks<br>    go func() {<br>        for _, task := range tasks {<br>            tasksChan &lt;- task<br>        }<br>        close(tasksChan)<br>    }()<br><br>    // Collect results<br>    go func() {<br>        wg.Wait()<br>        close(resultsChan)<br>    }()<br><br>    // Process results<br>    for result := range resultsChan {<br>        fmt.Println(&quot;Processed result:&quot;, result)<br>    }<br>}<br><br>func processTask(task int) int {<br>    // Perform task processing<br>    return task * task<br>}</pre><h4>Pipeline:</h4><p>The pipeline pattern involves chaining multiple stages of processing together using channels. Each stage performs a specific operation on the input and passes the modified data to the next stage. This pattern is suitable for tasks that can be divided into sequential steps. Here’s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    tasks := []int{1, 2, 3, 4, 5}<br><br>    // Stage 1: Generate tasks<br>    taskChan := make(chan int)<br>    go func() {<br>        for _, task := range tasks {<br>            taskChan &lt;- task<br>        }<br>        close(taskChan)<br>    }()<br><br>    // Stage 2: Process tasks<br>    resultChan := make(chan int)<br>    go func() {<br>        for task := range taskChan {<br>            result := processTask(task)<br>            resultChan &lt;- result<br>        }<br>        close(resultChan)<br>    }()<br><br>    // Stage 3: Consume results<br>    for result := range resultChan {<br>        fmt.Println(&quot;Processed result:&quot;, result)<br>    }<br>}<br><br>func processTask(task int) int {<br>    // Perform task processing<br>    return task * task<br>}</pre><p>These concurrency patterns provide powerful ways to structure and manage concurrent operations in Go. By leveraging these patterns, developers can build scalable, efficient, and maintainable concurrent applications.</p><h3>Error Handling in Concurrent Go Programs</h3><p>Concurrency introduces unique challenges to error handling in Go programs. It’s crucial to handle errors effectively to ensure the reliability and robustness of concurrent code. Here are some best practices for error handling in concurrent scenarios:</p><h4>Propagating Errors from Goroutines:</h4><p>When an error occurs in a goroutine, it’s essential to propagate it back to the main goroutine or an error-handling routine. One way to achieve this is by using channels to send errors. Here’s an example:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;errors&quot;<br>)<br><br>func main() {<br>    resultChan := make(chan int, 1)<br>    errorChan := make(chan error, 1)<br><br>    go func() {<br>        result, err := performTask()<br>        if err != nil {<br>            errorChan &lt;- err // Propagate the error<br>            return<br>        }<br>        resultChan &lt;- result<br>    }()<br><br>    select {<br>    case result := &lt;-resultChan:<br>        fmt.Println(&quot;Task result:&quot;, result)<br>    case err := &lt;-errorChan:<br>        fmt.Println(&quot;Error occurred:&quot;, err)<br>    }<br>}<br><br>func performTask() (int, error) {<br>    // Perform the task and handle errors<br>    return 42, errors.New(&quot;something went wrong&quot;)<br>}</pre><h4>Using Error Channels or Select Statements:</h4><p>Another approach is to use error channels or select statements with error cases for error handling. This allows handling errors from multiple goroutines simultaneously. Here’s an example:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;errors&quot;<br>)<br><br>func main() {<br>    resultChan := make(chan int, 1)<br>    errorChan := make(chan error, 1)<br><br>    go func() {<br>        result, err := performTask()<br>        if err != nil {<br>            errorChan &lt;- err // Propagate the error<br>            return<br>        }<br>        resultChan &lt;- result<br>    }()<br><br>    for {<br>        select {<br>        case result := &lt;-resultChan:<br>            fmt.Println(&quot;Task result:&quot;, result)<br>            return<br>        case err := &lt;-errorChan:<br>            fmt.Println(&quot;Error occurred:&quot;, err)<br>            return<br>        }<br>    }<br>}<br><br>func performTask() (int, error) {<br>    // Perform the task and handle errors<br>    return 42, errors.New(&quot;something went wrong&quot;)<br>}</pre><h4>Error Retries and Backoff Strategies:</h4><p>In concurrent scenarios, it may be beneficial to implement error retries with back-off strategies. This helps handle temporary failures or network glitches. Here’s an example using the exponential backoff strategy:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;errors&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    result, err := performTaskWithRetries()<br>    if err != nil {<br>        fmt.Println(&quot;Task failed:&quot;, err)<br>    } else {<br>        fmt.Println(&quot;Task result:&quot;, result)<br>    }<br>}<br><br>func performTaskWithRetries() (int, error) {<br>    maxRetries := 3<br>    retryInterval := time.Second<br><br>    for retry := 1; retry &lt;= maxRetries; retry++ {<br>        result, err := performTask()<br>        if err == nil {<br>            return result, nil<br>        }<br>        fmt.Printf(&quot;Attempt %d failed: %v\n&quot;, retry, err)<br>        time.Sleep(retryInterval * time.Duration(retry))<br>    }<br><br>    return 0, errors.New(&quot;maximum retries exceeded&quot;)<br>}<br><br>func performTask() (int, error) {<br>    // Perform the task and handle errors<br>    return 42, errors.New(&quot;something went wrong&quot;)<br>}</pre><h4>Handling Panics and Recovery in Goroutines:</h4><p>Panics in goroutines can lead to program termination if not handled properly. To recover from panics in goroutines, use the recover() function within a deferred function. Here&#39;s an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    go func() {<br>        defer func() {<br>            if r := recover(); r != nil {<br>                fmt.Println(&quot;Recovered from panic:&quot;, r)<br>            }<br>        }()<br>        performTask()<br>    }()<br><br>    // Perform other operations<br>}<br><br>func performTask() {<br>    defer func() {<br>        if r := recover(); r != nil {<br>            panic(&quot;Panic handled in performTask&quot;)<br>        }<br>    }()<br>    // Perform the task that may cause a panic<br>    panic(&quot;Something went wrong&quot;)<br>}</pre><h4>Logging and Monitoring Techniques:</h4><p>Logging and monitoring are crucial for concurrent programs to track errors and troubleshoot issues. Utilize logging libraries, such as Go’s standard log package, or external libraries like logrus, to log errors and relevant information. Additionally, integrate monitoring solutions, such as Prometheus or Datadog, to collect metrics and monitor the health of concurrent applications.</p><p>By applying these error-handling practices, developers can improve the stability and resilience of their concurrent Go programs, ensuring proper handling of errors and enabling effective debugging and troubleshooting.</p><h3>Concurrency Best Practices in Go</h3><p>Writing concurrent code requires careful consideration to ensure correctness and efficiency. Here are some best practices to follow when working with concurrency in Go:</p><ol><li><strong>Avoid sharing data by communicating:</strong> Instead of sharing memory between goroutines, prefer communicating through channels. This promotes clear ownership and reduces the chances of race conditions.</li><li><strong>Use sync primitives:</strong> Go provides several synchronization primitives, such as sync.Mutex and sync.WaitGroup, to coordinate access to shared resources and synchronize goroutines.</li><li><strong>Avoid excessive goroutine spawning:</strong> Creating too many goroutines can lead to excessive memory consumption and hinder performance. Use techniques like worker pools or limiting the maximum number of concurrent goroutines to avoid overwhelming the system.</li><li><strong>Use </strong><strong>context for cancellation:</strong> The context package in Go provides a powerful mechanism for canceling long-running operations and propagating cancellation signals to goroutines. Utilize context to manage the lifecycle of concurrent operations gracefully.</li><li><strong>Profile and benchmark:</strong> Measure the performance of your concurrent code to identify bottlenecks and optimize where necessary. Go provides excellent profiling and benchmarking tools like pprof and go test to aid in this process.</li></ol><h3>Conclusion</h3><p>Go’s support for concurrency through goroutines and channels makes it a powerful language for building concurrent and highly scalable applications. By leveraging goroutines and channels, developers can achieve efficient and safe concurrency without the complexities associated with manual thread management. Adhering to best practices and utilizing the various components provided by Go’s standard library ensures the development of robust and performant concurrent code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=380611406fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Event-Driven Architecture in PHP]]></title>
            <link>https://medium.com/@khaledzeitar/getting-started-with-event-driven-architecture-in-php-b0b048701ec1?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b048701ec1</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Wed, 10 May 2023 05:28:24 GMT</pubDate>
            <atom:updated>2023-05-10T05:28:24.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ez_Q4oBuK3cOLGBOmGwQ2w.jpeg" /></figure><p>In recent years, <strong>event-driven architecture (EDA)</strong> has emerged as a powerful approach to building scalable and responsive systems. EDA is a software architecture that promotes the production, detection, consumption, and reaction to events. Events can be thought of as anything that happens in a system, such as a user action, sensor reading, or message arrival. EDA systems are built around events, and they use events to drive their behavior.</p><h3>What is Event-Driven Architecture?</h3><p>Event-driven architecture (EDA) is a style of software architecture that focuses on the production, detection, consumption, and reaction to events. Events are discrete occurrences that happen in a system, and they can be used to trigger actions or reactions. In an EDA system, events are the primary means of communication between different components or services.</p><p>EDA is based on the publish-subscribe model, where producers publish events to a messaging system, and consumers subscribe to events they are interested in. The messaging system acts as an intermediary between producers and consumers, and it ensures that events are delivered reliably and in the order they were produced.</p><p>In an EDA system, components are loosely coupled, which means that they are independent and do not depend on each other. This makes EDA systems highly scalable and adaptable, as components can be added or removed without affecting the system as a whole.</p><h3>Components of Event-Driven Architecture</h3><h4><strong>1. Producers</strong></h4><p>Producers are responsible for producing events and publishing them to a messaging system. Producers can be any component in a system that generates events, such as <strong>user interfaces</strong>, <strong>sensors</strong>, or <strong>other services</strong>.</p><h4><strong>2. Consumers</strong></h4><p>Consumers are responsible for consuming events from the messaging system and taking action based on the events they receive. Consumers can be any component in a system that needs to react to events, such as business logic or user interfaces.</p><h4><strong>3. Message Broker</strong></h4><p>The message broker is the intermediary between producers and consumers. It receives events from producers and delivers them to consumers. The message broker ensures that events are delivered reliably and in the order they were produced. Message brokers can be implemented using various technologies, such as <strong>Apache Kafka</strong>, <strong>RabbitMQ</strong>, or <strong>Amazon Simple Queue Service (SQS)</strong>.</p><h4><strong>4. Event Processor</strong></h4><p>The event processor is responsible for processing events that are consumed by the message broker. The event processor can be any component in a system that performs some kind of computation or processing on the events it receives.</p><h3>Benefits of Event-Driven Architecture</h3><h4><strong>1. Scalability</strong></h4><p>EDA systems are highly scalable because components are loosely coupled. This means that components can be added or removed without affecting the system as a whole. As a result, EDA systems can easily scale up or down to handle changes in traffic or load.</p><h4><strong>2. Resilience</strong></h4><p>EDA systems are more resilient to failures than traditional systems because they are designed to handle events that are produced or consumed asynchronously. This means that if one component fails, other components can continue to function normally without being affected by the failure.</p><h4><strong>3. Flexibility</strong></h4><p>EDA systems are flexible because they can adapt to changes in the environment or business requirements. For example, if a new service is added to the system, it can be easily integrated by producing and consuming events.</p><h4><strong>4. Responsiveness</strong></h4><p>EDA systems are highly responsive because they can react to events in real time. This means that when an event is produced, consumers can immediately react to it and take action.</p><h3>Challenges of Event-Driven Architecture</h3><h4><strong>1. Event Ordering</strong></h4><p>Event ordering is a challenge in EDA systems because events can be produced and consumed asynchronously. This means that events may not be delivered in the order they were produced, which can affect the behavior of the system.</p><h4><strong>2. Event Consistency</strong></h4><p>Event consistency is a challenge in EDA systems because events may be produced or consumed multiple times. This means that consumers may need to check the state of the system to ensure that events are processed only once and that the system remains consistent.</p><h4><strong>3. Event Duplication</strong></h4><p>Event duplication can be a challenge in EDA systems because events may be produced and consumed multiple times. This can cause duplicate processing of events, which can affect the behavior of the system.</p><h4><strong>4. Event Schemas</strong></h4><p>Event schemas can be a challenge in EDA systems because events may have different formats and structures. This means that consumers may need to handle different types of events and may need to perform schema validation to ensure that events are processed correctly.</p><h3>Best Practices for Event-Driven Architecture</h3><h4><strong>1. Use a message broker</strong></h4><p>Using a message broker is essential in EDA systems because it provides reliable and scalable message delivery. A message broker can ensure that events are delivered reliably and in the order they were produced.</p><h4><strong>2. Use event schemas</strong></h4><p>Using event schemas is important in EDA systems because it helps ensure that events are processed correctly. Event schemas define the format and structure of events, and they can be used to perform schema validation and enforce consistency.</p><h4><strong>3. Design for failure</strong></h4><p>Designing for failure is important in EDA systems because failures are inevitable. EDA systems should be designed to handle failures gracefully and to ensure that the system remains responsive and resilient.</p><h4><strong>4. Use idempotent processing</strong></h4><p>Using idempotent processing is important in EDA systems because it helps ensure that events are processed only once. Idempotent processing means that processing the same event multiple times has the same effect as processing it once.</p><h3>Implementing Event-driven Architecture in PHP</h3><p>Implementing event-driven architecture in <strong>PHP </strong>requires a few steps, but it can be done easily with the right tools and libraries. Here’s a step-by-step guide to implementing <strong>EDA </strong>in <strong>PHP </strong>from scratch.</p><h4><strong>Step 1: Choose a Messaging System</strong></h4><p>The first step in implementing EDA in PHP is to choose a messaging system that supports pub/sub messaging. Popular choices include <strong>RabbitMQ</strong>, <strong>Apache Kafka</strong>, and <strong>Apache ActiveMQ</strong>. For the purpose of this article, we will use <strong>RabbitMQ</strong>.</p><h4><strong>Step 2: Set up a RabbitMQ instance</strong></h4><p>Before you can start publishing and consuming events, you need to set up a <strong>RabbitMQ </strong>instance. You can install <strong>RabbitMQ </strong>locally or use a cloud services provider like <strong>Amazon Web Services</strong> or <strong>Google Cloud Platform</strong>. Once you have <strong>RabbitMQ </strong>set up, you can create a queue and a topic exchange.</p><h4><strong>Step 3: Implement the Publisher</strong></h4><p>To publish events, you need to create a <strong>PHP </strong>script that will connect to <strong>RabbitMQ </strong>and publish messages to the exchange. Here’s some sample code to get you started:</p><pre>// include the RabbitMQ library<br>require_once __DIR__ . &#39;/vendor/autoload.php&#39;;<br><br>// create a connection to RabbitMQ<br>$connection = new \PhpAmqpLib\Connection\AMQPStreamConnection(<br>    &#39;localhost&#39;,  // RabbitMQ host<br>    5672,         // RabbitMQ port<br>    &#39;guest&#39;,      // RabbitMQ username<br>    &#39;guest&#39;       // RabbitMQ password<br>);<br><br>// create a channel<br>$channel = $connection-&gt;channel();<br><br>// create a message<br>$message = &#39;Hello, world!&#39;;<br><br>// publish the message to the exchange<br>$channel-&gt;basic_publish(<br>    new \PhpAmqpLib\Message\AMQPMessage($message),<br>    &#39;my_topic_exchange&#39;, // exchange name<br>    &#39;my_routing_key&#39;     // routing key<br>);<br><br>// close the channel and the connection<br>$channel-&gt;close();<br>$connection-&gt;close();</pre><p>In this example, we use the <strong>PhpAmqpLib</strong> library to connect to <strong>RabbitMQ </strong>and publish a message to the my_topic_exchange exchange using the my_routing_key routing key.</p><h4><strong>Step 4: Implement the Consumer</strong></h4><p>To consume events, you need to create a <strong>PHP </strong>script that will connect to <strong>RabbitMQ </strong>and subscribe to messages from the queue. Here’s some sample code to get you started:</p><pre>// include the RabbitMQ library<br>require_once __DIR__ . &#39;/vendor/autoload.php&#39;;<br><br>// create a connection to RabbitMQ<br>$connection = new \PhpAmqpLib\Connection\AMQPStreamConnection(<br>    &#39;localhost&#39;,  // RabbitMQ host<br>    5672,         // RabbitMQ port<br>    &#39;guest&#39;,      // RabbitMQ username<br>    &#39;guest&#39;       // RabbitMQ password<br>);<br><br>// create a channel<br>$channel = $connection-&gt;channel();<br><br>// create a queue<br>$channel-&gt;queue_declare(&#39;my_queue&#39;, false, false, false, false);<br><br>// bind the queue to the exchange<br>$channel-&gt;queue_bind(&#39;my_queue&#39;, &#39;my_topic_exchange&#39;, &#39;my_routing_key&#39;);<br><br>// create a callback function to handle messages<br>$callback = function (\PhpAmqpLib\Message\AMQPMessage $message) {<br>    echo &#39;Received message: &#39; . $message-&gt;body . &quot;\n&quot;;<br>};<br><br>// start consuming messages from the queue<br>$channel-&gt;basic_consume(&#39;my_queue&#39;, &#39;&#39;, false, true, false, false, $callback);<br><br>// wait for messages<br>while (count($channel-&gt;callbacks)) {<br>    $channel-&gt;wait();<br>}<br><br>// close the channel and the connection<br>$channel-&gt;close();<br>$connection-&gt;close();</pre><p>In this example, we connect to a local <strong>RabbitMQ </strong>server using the AMQPStreamConnection class from the <strong>RabbitMQ PHP Client library</strong>. We then declare a queue named my_queue and bind a callback function to it using the basic_consume method. The callback function receives an AMQPMessage object and handles the message by echoing the message body to the console.</p><p>Finally, we start consuming messages using the wait method in a loop until the consumer is manually stopped.</p><h4><strong>Step 5: Choose an Event-Driven Framework</strong></h4><p>While you can implement the event-driven architecture in PHP without a framework, using a framework can make it easier to manage events and event handlers. Some popular event-driven frameworks for PHP include <strong>ReactPHP</strong>, <strong>Amp</strong>, and <strong>Symfony Messenger</strong>.</p><p><strong>Symfony Messenger</strong> is a great choice if you’re already using the Symfony framework, as it integrates seamlessly with Symfony components.</p><h4><strong>Step 6: Implement the Event Handler</strong></h4><p>To handle events in your <strong>PHP </strong>application, you need to create an event handler. This can be done using the event-driven framework of your choice. Here’s an example using <strong>Symfony Messenger</strong>:</p><pre>// create a message handler<br>class MyMessageHandler implements \Symfony\Component\Messenger\Handler\MessageHandlerInterface<br>{<br>    public function __invoke(MyMessage $message)<br>    {<br>        // handle the message<br>        echo &#39;Received message: &#39; . $message-&gt;getText() . &quot;\n&quot;;<br>    }<br>}<br><br>// create a message<br>$message = new MyMessage(&#39;Hello, world!&#39;);<br><br>// dispatch the message<br>$bus-&gt;dispatch($message);</pre><p>In this example, we create a message handler that implements the MessageHandlerInterface from the <strong>Symfony Messenger</strong> component. The handler receives a MyMessage object and handles it by echoing the message text to the console.</p><h4><strong>Step 7: </strong>Streamline It with Well-Tested Packages</h4><p>Here are some recommended packages for implementing event-driven architecture in PHP:</p><ol><li><strong>RabbitMQ</strong>: A robust messaging system that supports pub/sub messaging and is widely used in event-driven architectures.</li><li><strong>Symfony Messenger</strong>: An event-driven framework for PHP that integrates seamlessly with the Symfony framework and provides powerful features for managing events and event handlers.</li><li><strong>ReactPHP</strong>: A low-level event-driven framework for PHP that allows you to build high-performance, non-blocking applications.</li><li><strong>Amp</strong>: Another low-level event-driven framework for PHP that provides tools for building scalable, concurrent applications.</li></ol><h3>Conclusion</h3><p><strong>Event-driven architecture</strong> provides a powerful approach to building scalable, responsive, and decoupled systems in <strong>PHP</strong>. By leveraging the publish-subscribe model and using tools like <strong>RabbitMQ </strong>and <strong>Symfony Messenger</strong>, <strong>EDA </strong>can be easily implemented in <strong>PHP </strong>applications and reap the benefits it provides.</p><p>However, it is important to keep in mind that <strong>EDA </strong>systems also pose some challenges, such as <strong>event ordering</strong> and <strong>consistency</strong>, <strong>duplication</strong>, and <strong>schema management</strong>. To overcome these challenges, it is crucial to follow best practices, including using a <strong>message broker</strong>, <strong>designing for failure</strong>, and <strong>using idempotent processing</strong>.</p><p>Overall, event-driven architecture is a valuable tool for building modern, complex systems that can handle a wide range of requirements and challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b048701ec1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Debugging Techniques in PHP]]></title>
            <link>https://medium.com/@khaledzeitar/basic-debugging-techniques-in-php-f1e937b89121?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e937b89121</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bugs]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Sat, 06 May 2023 20:50:35 GMT</pubDate>
            <atom:updated>2023-05-06T20:50:35.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*sH-eU6tPAFQx-9S9" /><figcaption>Credit: <a href="https://unsplash.com/photos/LhqLdDPcSV8">https://unsplash.com/photos/LhqLdDPcSV8</a></figcaption></figure><p><strong>Debugging </strong>is a crucial part of the software development process. It involves identifying and fixing errors or bugs in the code to ensure that the application works as intended. <strong>PHP</strong>, as a popular server-side scripting language, also requires debugging to ensure that it functions correctly. In this article, we’ll explore different debugging techniques in PHP, including their advantages and how to implement them in your code.</p><h3>Syntax Checking</h3><p>Syntax checking is the first step in debugging PHP code. It involves verifying that the code is free from syntax errors that can cause the application to crash. To perform syntax checking, you can use the PHP interpreter or an Integrated Development Environment (IDE) that supports syntax highlighting and error highlighting. The PHP interpreter checks the code for syntax errors before executing it.</p><p><strong>Example:</strong></p><pre>php -l example.php</pre><p>This command will check the syntax of the “example.php” file and report any errors found. Using an IDE that supports syntax highlighting is a more convenient way of checking for syntax errors as it highlights any syntax errors in the code while you are editing it.</p><h3>Debugging with var_dump()</h3><p>The var_dump() function is another useful tool for debugging PHP code. It displays the data type and value of a variable or expression. This is especially useful when trying to debug complex data structures such as arrays or objects.</p><p><strong>Example:</strong></p><pre>&lt;?php<br>    $person = array(&quot;name&quot; =&gt; &quot;John&quot;, &quot;age&quot; =&gt; 30, &quot;address&quot; =&gt; &quot;123 Main St&quot;);<br>    <br>    var_dump($person);<br>?&gt;</pre><p><strong>Output:</strong></p><pre>array(3) {<br>  [&quot;name&quot;]=&gt;<br>  string(4) &quot;John&quot;<br>  [&quot;age&quot;]=&gt;<br>  int(30)<br>  [&quot;address&quot;]=&gt;<br>  string(11) &quot;123 Main St&quot;<br>}</pre><h3>Debugging with print_r() function</h3><p>The print_r() function is used to display the content of an array, object, or variable in a human-readable format. This technique is useful when developers want to see the contents of an array or object to help identify errors or unexpected behavior.</p><p><strong>Example:</strong></p><pre>&lt;?php<br>    $array = array(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);<br>    print_r($array);<br>?&gt;</pre><p><strong>Output:</strong></p><pre>Array<br>(<br>    [0] =&gt; a<br>    [1] =&gt; b<br>    [2] =&gt; c<br>)</pre><h3>Debugging with error_reporting()</h3><p>The error_reporting() function is a useful tool for debugging PHP code. It allows you to specify which types of errors should be reported and how they should be handled. This can be useful when you’re working on a large codebase and want to focus on specific types of errors.</p><p><strong>Example:</strong></p><pre>&lt;?php<br>    error_reporting(E_ALL);<br>?&gt;</pre><h3>Debugging with display_errors() function</h3><p>The display_errors() function is used to display errors generated by PHP. By setting the value of the display_errors() function to On, developers can see errors, warnings, and notices on the web page. This technique is useful when developers want to see errors on the web page while they are developing the code.</p><pre>&lt;?php<br>    ini_set(&#39;display_errors&#39;, &#39;On&#39;);<br>?&gt;</pre><h3>Debugging with debug_backtrace() function</h3><p>The debug_backtrace() function is used to display the call stack of a PHP script. This technique is useful when developers want to see the function call stack to help identify errors or unexpected behavior.</p><p><strong>Example:</strong></p><pre>&lt;?php<br>    function a() {<br>        b();<br>    }<br>    <br>    function b() {<br>        c();<br>    }<br>    <br>    function c() {<br>        debug_print_backtrace();<br>    }<br>    <br>    a();<br>?&gt;</pre><p><strong>Output:</strong></p><pre>#0  c() called at [test.php:9]<br>#1  b() called at [test.php:5]<br>#2  a() called at [test.php:13]</pre><h3>Debugging with Xdebug</h3><p>Xdebug is a powerful debugging tool for PHP that allows developers to debug their code in real time. Xdebug provides a wide range of debugging features, including stack traces, variable inspection, and code coverage analysis. This technique is useful when developers want to debug their code more efficiently and effectively.</p><p><strong>Here’s an example of how to enable Xdebug in the PHP configuration file:</strong></p><pre>[Xdebug]<br>zend_extension = /path/to/xdebug.so<br>xdebug.remote_enable = 1<br>xdebug.remote_autostart = 1<br>xdebug.remote_connect_back = 1</pre><p>To use Xdebug, developers need to install the Xdebug extension for PHP and configure their PHP environment. Once installed and configured, developers can use their preferred IDE to connect to the Xdebug debugger and start debugging their code.</p><h3>Debugging with logging</h3><p>Logging is a common technique for debugging PHP code. It involves writing messages to a log file at specific points in your code to help you understand how the code is executing. You can use logging to record the value of variables, track the flow of your code, and identify errors and exceptions.</p><p>To use logging into your PHP code, you’ll need to use a logging library such as <strong>Monolog </strong>or <strong>Log4php</strong>. These libraries provide a simple and flexible API for writing log messages to various destinations, including files, databases, and remote servers.</p><p>Here’s an example of how to use Monolog to write log messages to a file:</p><pre>&lt;?php<br>    require_once __DIR__.&#39;/vendor/autoload.php&#39;;<br>    <br>    use Monolog\Logger;<br>    use Monolog\Handler\StreamHandler;<br>    <br>    // Create a logger<br>    $log = new Logger(&#39;my_logger&#39;);<br>    <br>    // Add a log handler<br>    $log-&gt;pushHandler(new StreamHandler(&#39;path/to/logfile.log&#39;, Logger::DEBUG));<br>    <br>    // Log a message<br>    $log-&gt;debug(&#39;This is a debug message&#39;);<br>?&gt;</pre><p>In this example, we create a new Monolog logger and add a stream handler to write log messages to a file. We then log a debug message using the logger.</p><h3>Debugging with PHPUnit</h3><p>PHPUnit is a popular unit testing framework for PHP. It allows you to write automated tests for your PHP code and run them as part of your build process. In addition to testing your code, PHPUnit can be used for debugging by providing detailed error messages and stack traces.</p><p>To use PHPUnit for debugging, you’ll need to write test cases that exercise the code you want to debug. You can then use PHPUnit’s debugging features to examine the state of your code and identify errors and exceptions.</p><p><strong>Example:</strong></p><pre>&lt;?php<br>    use PHPUnit\Framework\TestCase;<br>    <br>    class MyTest extends TestCase {<br>      public function testAddition() {<br>        $x = 5;<br>        $y = 7;<br>        $z = $x + $y;<br>        $this-&gt;assertEquals(12, $z);<br>      }<br>    }<br>?&gt;</pre><p>In this example, we define a test case that checks the addition of two numbers. We then use the assertEquals() method to compare the result of the addition with the expected value. If the test fails, PHPUnit will provide a detailed error message and stack trace to help you identify the cause of the failure.</p><h3>Conclusion</h3><p>Debugging is an essential part of the software development process, and PHP is no exception. By using a combination of syntax checking, var_dump(), print_r(), error_reporting(), display_errors(), XDebug, logging, and PHPUnit, you can quickly identify and fix errors in your PHP code.</p><p>It’s important to remember that different debugging techniques may be more or less effective depending on the complexity of your code and the nature of the errors you’re trying to identify. As you gain experience with PHP development, you’ll develop a sense of which techniques are most useful for different types of debugging tasks.</p><p>In addition to the techniques discussed in this article, there are many other tools and libraries available for debugging PHP code. Some examples include <strong>Xdebug</strong>, <strong>Kint</strong>, and <strong>PHP Debug Bar</strong>. By exploring these and other tools, you can further enhance your ability to debug PHP code and become a more effective developer.</p><p>Debugging can be a time-consuming and frustrating process, but it’s an essential part of building high-quality software. By taking a systematic approach to debugging and using a range of techniques and tools, you can minimize the time and effort required to identify and fix errors in your PHP code. With practice and experience, you’ll become more efficient and effective at debugging, helping you to deliver better software faster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e937b89121" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP & OWASP Top 10: Essential Steps for Keeping Your Web Application Safe and Secure]]></title>
            <link>https://medium.com/@khaledzeitar/php-owasp-top-10-essential-steps-for-keeping-your-web-application-safe-and-secure-72b5e7e55523?source=rss-a35308db09bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/72b5e7e55523</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Khaled Zeitar]]></dc:creator>
            <pubDate>Wed, 03 May 2023 23:08:09 GMT</pubDate>
            <atom:updated>2023-05-03T23:08:09.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*84AHOco0lkjS_lfG" /><figcaption>Credit: <a href="https://unsplash.com/photos/67L18R4tW_w">https://unsplash.com/photos/67L18R4tW_w</a></figcaption></figure><p>PHP is a popular server-side scripting language used to develop web applications. However, like any other web application, PHP applications are also susceptible to various security risks. The Open Web Application Security Project (OWASP) has identified the <a href="https://owasp.org/www-project-top-ten/">top 10 most critical web application security risks</a>. In this article, we will discuss how to secure a PHP application against these risks.</p><h3>Injection</h3><p>Injection vulnerabilities occur when an attacker is able to inject malicious code into a web application. This can happen when user input is not properly sanitized and validated. Injection attacks can lead to data loss, data corruption, or even full system compromise.</p><p>To prevent injection attacks in PHP applications, you should use prepared statements or parameterized queries when interacting with a database. Prepared statements ensure that user input is treated as data rather than code. Here is an example of using prepared statements to prevent SQL injection in PHP:</p><pre>$stmt = $pdo-&gt;prepare(&#39;SELECT * FROM users WHERE username = :username&#39;);<br>$stmt-&gt;bindParam(&#39;:username&#39;, $username);<br>$stmt-&gt;execute();</pre><p>You should also sanitize and validate all user input before using it in your application. Use PHP’s filter_var() function to validate input and remove any unwanted characters.</p><h3>Broken Authentication and Session Management</h3><p>Broken authentication and session management vulnerabilities occur when an attacker is able to compromise user accounts or session tokens. This can happen when authentication and session management mechanisms are not implemented correctly or are easily bypassed.</p><p>To prevent broken authentication and session management vulnerabilities in PHP applications, you should:</p><ul><li>Use secure session management techniques such as using secure session cookies, generating strong session IDs, and expiring sessions after a short period of inactivity.</li><li>Use strong password policies and implement multi-factor authentication to prevent brute force attacks and credential stuffing attacks.</li><li>Use encryption to protect sensitive data such as passwords and session tokens.</li></ul><p>Here is an example of how to implement secure session management in PHP:</p><pre>session_set_cookie_params([<br>  &#39;lifetime&#39; =&gt; 86400,<br>  &#39;samesite&#39; =&gt; &#39;Lax&#39;,<br>  &#39;secure&#39; =&gt; true,<br>  &#39;httponly&#39; =&gt; true<br>]);<br><br>session_start();</pre><h3>Cross-Site Scripting (XSS)</h3><p>Cross-site scripting (XSS) vulnerabilities occur when an attacker is able to inject malicious scripts into a web application. This can happen when user input is not properly sanitized and validated. XSS attacks can lead to data theft, cookie stealing, or even full system compromise.</p><p>To prevent XSS attacks in PHP applications, you should:</p><ul><li>Use PHP’s htmlspecialchars() function to encode user input and prevent the execution of scripts.</li><li>Use Content Security Policy (CSP) headers to limit the types of scripts that can be executed in your application.</li><li>Use HTTP-only cookies to prevent cookie theft.</li></ul><p>Here is an example of how to use PHP’s htmlspecialchars() function to prevent XSS attacks:</p><pre>echo &#39;Hello &#39; . htmlspecialchars($_GET[&quot;name&quot;]) . &#39;!&#39;;</pre><h3>Broken Access Control</h3><p>Broken access control vulnerabilities occur when an attacker is able to access resources or perform actions that they should not be able to. This can happen when access control mechanisms are not implemented correctly or are easily bypassed.</p><p>To prevent broken access control vulnerabilities in PHP applications, you should:</p><ul><li>Implement access control mechanisms that are based on the principle of least privilege.</li><li>Use strong authentication and authorization mechanisms to prevent unauthorized access.</li><li>Use secure session management techniques to prevent session hijacking attacks.</li></ul><p>Here is an example of how to implement access control in PHP using role-based access control:</p><pre>// Define user roles and their permissions<br>$roles = [<br>    &#39;admin&#39; =&gt; [&#39;create&#39;, &#39;read&#39;, &#39;update&#39;, &#39;delete&#39;],<br>    &#39;user&#39; =&gt; [&#39;read&#39;, &#39;update&#39;]<br>];<br><br>// Check if the current user has the required role to perform the action<br>function hasPermission($role, $permission) {<br>    global $roles;<br><br>    return in_array($permission, $roles[$role]);<br>}<br><br>// Example usage<br>if (hasPermission(&#39;admin&#39;, &#39;create&#39;)) {<br>    // Allow the user to create a new resource<br>} else {<br>    // Deny access<br>}</pre><h3>Security Misconfiguration</h3><p>Security misconfiguration vulnerabilities occur when security settings are not configured correctly. This can happen when default settings are used or when security settings are not updated or maintained properly.</p><p>To prevent security misconfiguration vulnerabilities in PHP applications, you should:</p><ul><li>Keep your PHP version and web server up to date with the latest security patches.</li><li>Use secure configuration settings for your PHP environment and web server.</li><li>Remove default accounts, passwords, and settings from your application.</li></ul><h3>Insecure Cryptographic Storage</h3><p>Insecure cryptographic storage vulnerabilities occur when sensitive data such as passwords or session tokens are not stored securely. This can happen when passwords are stored in plain text or weak encryption algorithms are used.</p><p>To prevent insecure cryptographic storage vulnerabilities in PHP applications, you should:</p><ul><li>Use strong encryption algorithms such as AES-256 to encrypt sensitive data.</li><li>Use secure hashing algorithms such as bcrypt or Argon2 to hash passwords.</li><li>Store cryptographic keys and secrets securely.</li></ul><h3>Insufficient Transport Layer Protection</h3><p>Insufficient transport layer protection vulnerabilities occur when data is transmitted over an insecure channel. This can happen when data is transmitted over HTTP instead of HTTPS.</p><p>To prevent insufficient transport layer protection vulnerabilities in PHP applications, you should:</p><ul><li>Use HTTPS to encrypt all data transmitted between the client and server.</li><li>Use HTTP Strict Transport Security (HSTS) headers to enforce HTTPS.</li></ul><p>Here is an example of how to enforce HTTPS in PHP using HSTS headers:</p><pre>header(&#39;Strict-Transport-Security: max-age=31536000; includeSubDomains&#39;);</pre><h3>Unvalidated and Unsanitized Input</h3><p>Unvalidated and unsanitized input vulnerabilities occur when user input is not properly validated and sanitized. This can happen when input validation is not implemented or is easily bypassed.</p><p>To prevent unvalidated and unsanitized input vulnerabilities in PHP applications, you should:</p><ul><li>Use PHP’s filter_var() function to validate input and remove any unwanted characters.</li><li>Use prepared statements or parameterized queries when interacting with a database to prevent SQL injection.</li><li>Use PHP’s htmlspecialchars() function to encode user input and prevent XSS attacks.</li></ul><h3>Insufficient Authentication and Authorization</h3><p>Insufficient authentication and authorization vulnerabilities occur when authentication and authorization mechanisms are not implemented correctly or are easily bypassed. This can happen when weak passwords are used or when access control mechanisms are not enforced properly.</p><p>To prevent insufficient authentication and authorization vulnerabilities in PHP applications, you should:</p><ul><li>Use strong password policies and implement multi-factor authentication to prevent brute force attacks and credential stuffing attacks.</li><li>Implement access control mechanisms that are based on the principle of least privilege.</li><li>Use secure session management techniques to prevent session hijacking attacks.</li></ul><h3>Using Components with Known Vulnerabilities</h3><p>Using components with known vulnerabilities occur when outdated or vulnerable third-party libraries or components are used in a web application. This can happen when updates or patches are not applied in a timely manner.</p><p>To prevent using components with known vulnerabilities in PHP applications, you should:</p><ul><li>Keep all third-party libraries and components updated with the latest security patches and updates.</li><li>Regularly check for vulnerabilities and security advisories in third-party libraries and components and take appropriate action to address them.</li><li>Use a package manager such as Composer to manage dependencies and ensure that only secure and up-to-date components are used in your PHP application.</li></ul><h3>Conclusion</h3><p>Securing a PHP application requires a comprehensive approach that includes implementing secure coding practices, securing sensitive data, enforcing access control, and keeping all components up to date. By following the best practices outlined in the OWASP Top 10 and implementing them in your PHP application, you can reduce the risk of security vulnerabilities and protect your application and its users from malicious attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b5e7e55523" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>