<?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 Allan Njoroge on Medium]]></title>
        <description><![CDATA[Stories by Allan Njoroge on Medium]]></description>
        <link>https://medium.com/@justallan?source=rss-fcedd6813a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qi3sfPAruYlNATV8Yn__UQ.jpeg</url>
            <title>Stories by Allan Njoroge on Medium</title>
            <link>https://medium.com/@justallan?source=rss-fcedd6813a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:31:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@justallan/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[Identity Verification Beyond KYC]]></title>
            <link>https://justallan.medium.com/identity-verification-beyond-kyc-b46e6d81b4f1?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46e6d81b4f1</guid>
            <category><![CDATA[device-intelligence]]></category>
            <category><![CDATA[identity-verification]]></category>
            <category><![CDATA[kyc]]></category>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 18:34:14 GMT</pubDate>
            <atom:updated>2026-07-28T19:07:39.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hlZPh1FtLVylH8LfsPB9Q.png" /></figure><p>Know Your Customer compliance has served as the foundational gatekeeper for digital finance, commerce, and regulated platforms. The standard workflow is familiar across the tech industry: collect Personally Identifiable Information, verify a government-issued document, and perform a facial liveness check. While this process satisfies regulatory mandates, the modern threat landscape has exposed a critical limitation in this paradigm. Traditional Know Your Customer frameworks function primarily as legal compliance checklists rather than robust operational security architectures.</p><p>Relying on static data and point-in-time document verification during onboarding leaves platforms vulnerable to post-onboarding compromise, synthetic identity rings, and sophisticated automated abuse. Today, static identity data is effectively public data. The proliferation of generative artificial intelligence, combined with decades of global data breaches, means that possessing a valid name, national ID number, and matching biometric image no longer proves authentic human ownership. To build resilient platforms, engineering and security teams must expand their focus beyond initial onboarding and implement systems that verify identity continuously across the entire user lifecycle.</p><h3>The Point-in-Time Vulnerability</h3><p>The primary structural weakness of traditional identity verification is its reliance on point-in-time execution. Once a user passes the initial onboarding checks, the application typically assigns a static boolean attribute to their database profile, marking the account as verified. From that exact moment forward, the system implicitly trusts the credentials associated with that account.</p><p>Attackers actively exploit this binary trust model. A common vulnerability vector involves account aging, where sophisticated threat actors successfully pass onboarding using synthetic identities or recruited human proxies. Once verified, these accounts sit dormant or execute automated, low-value transactions to build a positive reputation score within the platform’s relational database. Because the verification gate only exists at the entrance, the platform lacks the architectural mechanics to re-evaluate the account’s legitimacy when it eventually pivots to malicious behavior months later.</p><p>Furthermore, point-in-time verification provides zero defense against Account Takeover attacks. If a legitimate user’s session tokens or authentication credentials are compromised through malware or social engineering, an attacker inherits the verified status of the account without ever encountering an identity checkpoint. Treating identity as a static milestone rather than an ongoing operational state creates a massive blind spot within application security.</p><h3>The Shift to Continuous Identity Assessment</h3><p>To mitigate the vulnerabilities of static verification, modern architectures are transitioning toward Continuous Identity Assessment. This framework treats digital identity as a dynamic, fluctuating risk score that is recalculated during every significant system interaction, rather than a permanent badge awarded at registration.</p><p>Under a continuous assessment model, the authentication layer evaluates session state, behavioral changes, and transactional context in real time. When an authenticated user attempts an action, the system processes a multi-dimensional array of telemetry to determine if the current actor matches the historical profile of the account owner.</p><p>If the calculated risk score remains below a defined operational threshold, the user experiences zero friction. If the risk engine detects anomalous patterns that deviate from the established baseline, the system dynamically invokes step-up verification protocols or temporarily throttles API access. This dynamic escalation ensures that security interventions occur precisely when risk elevates, without degrading the general user experience during routine operations.</p><h3>Device Provenance and Hardware Telemetry</h3><p>A critical pillar of identity verification beyond onboarding is deep device provenance. Historically, security systems relied on basic network attributes like IP addresses and User-Agent headers to validate the client environment. Today, these metrics are easily spoofed. Attackers routinely route automated scripts through residential proxy networks, utilizing compromised consumer routers and Internet of Things devices to distribute traffic across legitimate domestic IP ranges.</p><p>To counteract proxy routing and emulation, client-side security SDKs must collect granular hardware telemetry to establish an immutable device fingerprint. Rather than asking who the user is, the system evaluates what physical hardware is executing the request. High-confidence device provenance relies on analyzing complex hardware and browser capabilities:</p><ul><li><strong>Rendering Engine Metrics:</strong> Evaluating WebGL execution and HTML5 canvas rendering outputs to detect subtle cryptographic differences in how specific graphics processing units render two-dimensional and three-dimensional shapes.</li><li><strong>Audio Context Telemetry:</strong> Measuring the exact mathematical variance in how a device’s audio stack generates and processes acoustic oscillators, which varies distinctively across physical hardware configurations.</li><li><strong>Hardware Concurrency and Memory:</strong> Cross-referencing reported central processing unit core counts and device memory against known physical hardware specifications to identify virtual machines and cloud-based emulators.</li><li><strong>Sensor Calibration:</strong> On mobile platforms, analyzing accelerometer, gyroscope, and magnetometer data to verify physical device handling, separating physical human users from automated server farms.</li></ul><p>When an application tracks device provenance over time, it can instantly flag when a verified account suddenly begins executing requests from a headless browser or a hardware environment that exhibits programmatic anomalies.</p><h3>Behavioral Biometrics and Interaction Mechanics</h3><p>While hardware telemetry validates the physical machine, behavioral biometrics validate the human operator behind the screen. Human beings interact with software through unique, subconscious biomechanical patterns that are exceptionally difficult for automated scripts or unauthorized human actors to replicate.</p><p>Behavioral engines monitor application interaction mechanics in the background, building a mathematical model of the user’s operational cadence. Key vectors analyzed within this layer include:</p><ul><li><strong>Keystroke Dynamics:</strong> Measuring the precise timing between key presses, including flight time (the duration between releasing one key and pressing the next) and dwell time (the duration a single key is held down).</li><li><strong>Cursor Trajectories:</strong> Analyzing mouse movement velocity, acceleration, and curvature. Human cursor navigation exhibits natural micro-tremors and curved trajectories, whereas programmatic automation typically moves in deterministic, linear vectors or artificial mathematical curves.</li><li><strong>Touch Surface Cadence:</strong> On mobile touchscreens, evaluating swipe velocity, touch pressure, contact surface area, and tap coordinates relative to UI interactive elements.</li><li><strong>Navigation Sequencing:</strong> Mapping the speed and path taken through application menus and API endpoints. Automated attacks typically attempt to access high-value endpoints directly with minimal latency, bypassing standard UI navigation flows.</li></ul><p>By integrating behavioral biometrics into the authorization middleware, platforms establish a continuous passive biometric layer. Even if an attacker successfully acquires a legitimate user’s device and session cookies, their distinct motor skills and navigation cadence will fail to match the biometric profile of the account owner, triggering immediate protective mitigations.</p><h3>Network Analysis via Graph Structures</h3><p>Traditional fraud detection systems rely heavily on relational SQL databases, querying tabular rows to identify duplicate phone numbers, email addresses, or tax identifiers. While effective for simple deduplication, relational databases struggle to detect complex synthetic identity networks. When fraudsters construct synthetic identities, they intentionally randomize primary surface-level attributes to evade relational database queries.</p><p>To detect organized fraud networks post-onboarding, organizations must implement graph database architectures. Graph analytics shift the analytical focus from isolated user records to the relationships and connections between data points. Within a graph database, entities such as user accounts, physical devices, payment instruments, and network subnets are stored as nodes, while the interactions between them are mapped as edges.</p><p>Advanced graph algorithms traverse these edges to uncover hidden clusters and organized abuse patterns that operate below the threshold of individual account alerts:</p><ul><li><strong>Connected Component Analysis:</strong> Identifying isolated subgraphs where seemingly independent accounts share latent technical variables, such as a localized browser configuration or a specific withdrawal destination.</li><li><strong>PageRank and Centrality Metrics:</strong> Evaluating the relative importance and influence of specific technical identifiers within the broader network, isolating infrastructure nodes that act as hubs for malicious activity.</li><li><strong>Deep Link Traversal:</strong> Discovering indirect relationships across three or four degrees of separation, such as twenty distinct accounts that never share an IP address but routinely send funds to different wallets funded by the same origin source.</li></ul><h3>Comparative Architecture Overview</h3><p>The transition from onboarding-only verification to a continuous, multi-layered identity architecture requires fundamental changes in data engineering, telemetry collection, and system evaluation.</p><p><strong>Architectural DimensionTraditional KYC ParadigmContinuous Identity ArchitectureVerification Timing</strong>Point-in-time during initial onboardingContinuous execution across the session lifecycle<strong>Primary Data Sources</strong>Government documents, static PII, facial selfiesHardware telemetry, behavioral biometrics, network graphs<strong>Trust Model</strong>Binary trust established post-verificationDynamic risk scoring with zero implicit trust<strong>Threat Coverage</strong>Identity theft, simple application fraudAccount takeover, synthetic rings, programmatic automation<strong>User Friction</strong>High initial friction, zero subsequent frictionZero baseline friction, dynamic escalation upon risk variance<strong>Data Structure</strong>Tabular and relational SQL schemasMulti-dimensional graph structures and time-series telemetry</p><h3>Aligning Identity with Zero-Trust Security</h3><p>True digital security requires decoupling identity verification from regulatory onboarding compliance. While collecting legal identification documents remains a necessary requirement for financial and regulatory compliance, it cannot serve as the sole mechanism for establishing trust within modern software systems.</p><p>By extending identity verification beyond KYC, engineering teams align customer identity management with the foundational principles of zero-trust architecture: never trust, always verify. Through the synthesis of continuous risk scoring, deep hardware provenance, passive behavioral biometrics, and relational graph analytics, organizations can neutralize automated abuse and synthetic identity networks without impacting the performance or accessibility of legitimate end users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46e6d81b4f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combating Fraud and Forging Identity in the AI Era]]></title>
            <link>https://justallan.medium.com/combating-fraud-and-forging-identity-in-the-ai-era-f96085248d92?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f96085248d92</guid>
            <category><![CDATA[ai-fraud-prevention]]></category>
            <category><![CDATA[synthetic-fraud]]></category>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Tue, 26 May 2026 17:17:05 GMT</pubDate>
            <atom:updated>2026-05-26T17:17:05.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*slj98TIblnnsrkSNDLoYQg.png" /></figure><p>For the last two decades, digital identity was built on a simple, static premise: if you know the secret (a password) or hold the artifact (an ID card), you are who you say you are.</p><p>Generative AI has completely shattered this premise.</p><p>Today, the internet is flooded with synthetic identities, voice clones generated from three-second audio samples and hyper-realistic video deepfakes that can bypass standard KYC (Know Your Customer) checks. The barrier to entry for enterprise-grade fraud has dropped to near zero.</p><p>If you are engineering financial systems, compliance tools or any platform that handles digital assets, building a robust backend is no longer just about moving data efficiently. It is about building <strong>Trust-Tech</strong>. You have to architect systems assuming that every piece of incoming data might be a highly sophisticated fabrication.</p><p>Here is a deep dive into the modern landscape of AI-driven fraud and the architectural patterns required to defend your platforms.</p><h3>1. How AI Scales Fraud</h3><p>To build effective defenses, you must first understand the attack vectors. AI has not necessarily created new <em>types</em> of fraud; it has industrialized the existing ones.</p><h3>Synthetic Identity Fraud</h3><p>In the past, identity theft involved stealing a real person’s complete profile. Today, fraudsters use generative AI to piece together synthetic identities , that is combining a real National ID or a Social Security Number with a fabricated name, an AI-generated face and a fake credit history.</p><p>Because the identity does not belong to a single real person, there is no victim to report the theft. These “ghost users” can sit inside a financial system for months, slowly building credit or transaction limits before orchestrating a massive, coordinated default.</p><h3>Deepfakes and Injection Attacks</h3><p>Modern onboarding often requires a selfie video to prove liveness. However, attackers bypass the camera entirely using injection attacks. By intercepting the data stream between the web camera and the browser, they can inject an AI-generated deepfake video directly into your application’s data flow. If your backend relies solely on visual inspection of the final file, it will pass the check.</p><h3>Automated Phishing and Social Engineering</h3><p>LLMs (Large Language Models) allow attackers to generate perfectly localized, grammatically flawless phishing campaigns at scale. They can scrape a target’s social media and instantly generate context-aware communications. When combined with voice cloning, attackers can automate phone calls to customer support, flawlessly impersonating a user to reset passwords or alter account routing details.</p><h3>2. Engineering for Non-Repudiation</h3><p>You cannot solve AI fraud purely with more AI. If you rely entirely on AI to detect AI, you enter an endless arms race that the attackers will eventually win.</p><p>Instead, you must rely on hard engineering principles, cryptographic validation and defensive architecture.</p><h3>Defense Layer 1: Defensive SDKs and Payload Sanitization</h3><p>If your platform collects biometric data or identity documents, you cannot trust data submitted via standard HTTP forms. Attackers will simply upload manipulated files.</p><p>Identity verification must be handled by robust, defensive SDKs that run on the client side. A secure SDK does not just capture the image; it captures the telemetry of <em>how</em> the image was taken. It looks for virtual cameras, detects screen recording software and cryptographically signs the payload before it leaves the device.</p><p>On the backend, your ingestion layer must aggressively sanitize these inputs. Defensive URL sanitization, strict type checking and rejecting any payload with a malformed signature are the first steps to dropping fraudulent requests before they ever hit your core business logic.</p><h3>Defense Layer 2: Continuous Verification and Behavioral Telemetry</h3><p>Identity is no longer an onboarding event; it is a continuous lifecycle.</p><p>Just because a user passed a biometric check on Monday does not mean the user authorizing a massive withdrawal on Friday is the same person. Modern systems must track behavioral telemetry:</p><ul><li><strong>Device Fingerprinting:</strong> Is this request coming from a device the user has historically used?</li><li><strong>Velocity Checks:</strong> Is this account attempting 50 high-value actions in one hour, when its historical average is two per month?</li><li><strong>Network Analysis:</strong> Is the IP address bouncing between different continents in a mathematically impossible timeframe?</li></ul><p>When behavioral anomalies trigger a flag, the system should automatically step up authentication, perhaps requiring a live cryptographic signature or a hardware key.</p><h3>Defense Layer 3: Structural Friction</h3><p>In transactional systems, speed is often the enemy of security. Fraudsters rely on instant settlement to extract value before the fraud is detected.</p><p>Introducing structural friction neutralizes this advantage. If a user acts as a seller in an informal market or initiates a high-risk transaction, holding the funds in a managed logic layer for a predefined window allows time for behavioral analytics to process and gives the true account owner time to report a potential takeover.</p><h3>3. Immutable Audit Logs</h3><p>When fraud does occur, your ability to recover, patch the vulnerability and comply with regulatory investigations depends entirely on your system’s observability.</p><p>Standard database logs are insufficient. If an attacker compromises an admin account, they can simply delete the records of their actions. You need <strong>Immutable Audit Logs</strong>.</p><h3>The Anatomy of a Secure Audit Log</h3><p>An audit log is a chronological, tamper-evident record of every significant state change within your application.</p><p><strong>1. Event Sourcing</strong> Instead of just updating a database row (e.g., changing an account status from PENDING to VERIFIED), your system should write an event to the log: <em>AccountVerifiedEvent</em>. The current state of the database is merely a projection of all these historical events.</p><p><strong>2. WORM Storage (Write Once, Read Many)</strong> Audit logs must be written to specialized storage configurations where data can be appended, but never modified or deleted, even by system administrators.</p><p><strong>3. Cryptographic Chaining</strong> To guarantee that logs have not been tampered with, you can use cryptographic chaining. When a new log entry is created, it includes the cryptographic hash of the <em>previous</em> log entry.</p><p>If a sophisticated internal actor manages to alter a log entry from a month ago, the hash of that entry will change. Because the next entry relies on that hash, the entire chain breaks. This mathematical proof immediately alerts your security team to the tampering.</p><h3>What Should You Log?</h3><p>A high-quality audit log captures the <em>Context</em>, not just the <em>Action</em>. Every entry should answer:</p><ul><li><strong>Who:</strong> The precise user ID or API key.</li><li><strong>What:</strong> The exact mutation that occurred (including the payload before and after the change).</li><li><strong>When:</strong> A highly accurate UTC timestamp.</li><li><strong>Where:</strong> The IP address, device fingerprint and User-Agent.</li><li><strong>Why:</strong> The authorization context (e.g., “Role: Admin, Scope: write:users”).</li></ul><p>When dealing with AI identity fraud, these logs become your forensic goldmine. By analyzing the audit logs of a compromised account, you can trace the exact sequence of API calls the automated bot made, identify the specific IP ranges used and build pattern-matching rules to block the next synthetic identity before it even finishes onboarding.</p><h3>Identity as a Dynamic System</h3><p>In the era of Generative AI, static credentials are dead. You can no longer trust an image, a voice or a string of text implicitly.</p><p>Securing the modern web requires a shift in engineering philosophy. We must build trust-tech infrastructures that validate intent through continuous behavioral analysis, defensive client-side SDKs and airtight backend sanitation. Most importantly, we must record every step of that journey in cryptographic, immutable audit logs.</p><p>The front door might be under heavy assault from automated AI, but with the right architectural foundations, the vault remains entirely secure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96085248d92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Webhooks with IP Whitelisting and Signature Validation]]></title>
            <link>https://justallan.medium.com/securing-webhooks-with-ip-whitelisting-and-signature-validation-41850f445290?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/41850f445290</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[signature-validation]]></category>
            <category><![CDATA[ip-whitelist]]></category>
            <category><![CDATA[webhook-security]]></category>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Thu, 21 May 2026 19:57:06 GMT</pubDate>
            <atom:updated>2026-05-21T19:57:06.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwJAFSAys71z5O4E1xMMQg.png" /></figure><p>Webhooks are the nervous system of the modern web. When a customer pays an invoice, a payment provider fires a webhook. When a developer merges code, a version control system fires a webhook. They are real-time, event-driven and highly efficient.</p><p>But structurally, a webhook is just a public, unprotected `<strong><em>POST`</em></strong> endpoint sitting on your server.</p><p>If a legitimate billing service can send a request to `<em>api.yourdomain.com/webhooks/payments`</em> telling your system to upgrade a user’s account to premium, a malicious actor can send that exact same request. If your server blindly trusts whatever payload hits that endpoint, you have essentially handed the keys to your database to the public internet.</p><p>To build secure, production-grade webhooks, you cannot rely on obscurity. You need cryptographic proof of identity. Here is the definitive guide to securing your webhook endpoints using <strong>IP Whitelisting</strong> and <strong>Signature Validation</strong>.</p><h3>IP Whitelisting</h3><p>IP Whitelisting is a network-level security measure. It operates on a very simple premise: your server maintains a strict list of approved IP addresses. If a request arrives from an IP not on that list, the connection is instantly rejected.</p><h3>The Architectural Advantage</h3><p>IP Whitelisting is incredibly lightweight. Because you can reject the request at the network layer, often before your application even attempts to parse the headers or the body. It uses almost zero compute resources. It is an excellent defense against brute-force attacks, random internet scanners and denial-of-service attempts.</p><p>Many major API providers publish a static list of CIDR blocks (IP address ranges) that their webhooks will originate from. By configuring your firewalls or reverse proxies to only accept traffic on your webhook paths from these specific blocks, you immediately eliminate the vast majority of malicious traffic.</p><h3>The Vulnerabilities</h3><p>However, IP Whitelisting should never be your only line of defense. Relying solely on network-origin checks leaves your system exposed to several edge cases:</p><ul><li><strong>Dynamic Infrastructure:</strong> In the era of modern cloud computing, many providers route their webhooks through highly dynamic, serverless infrastructure. Their outbound IP addresses might change daily or scale up and down dynamically, making it a nightmare for your engineering team to maintain an accurate whitelist.</li><li><strong>Internal Threats:</strong> If an attacker compromises another server hosted on the same massive cloud provider network that your API provider uses, they might share an IP range that is already whitelisted, allowing them to bypass this defense entirely.</li><li><strong>IP Spoofing:</strong> Sophisticated attackers can sometimes spoof source IP addresses in certain network configurations, tricking your server into thinking the request originated from a trusted source.</li></ul><h3>Example</h3><p>While often handled at the load balancer, here is how you might implement a simple IP whitelist middleware at the application layer using an Express.js server:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>// A predefined list of approved IP addresses provided by your API partner<br>const ALLOWED_IPS = [<br>  &#39;198.51.100.14&#39;,<br>  &#39;198.51.100.15&#39;,<br>  &#39;203.0.113.50&#39;<br>];<br><br>const ipWhitelistMiddleware = (req, res, next) =&gt; {<br>  // Extract the client IP. <br>  // Ensure your proxy trust settings are configured correctly if behind a load balancer.<br>  const clientIp = req.headers[&#39;x-forwarded-for&#39;] || req.socket.remoteAddress;<br><br>  if (!ALLOWED_IPS.includes(clientIp)) {<br>    console.warn(`Blocked unauthorized webhook attempt from IP: ${clientIp}`);<br>    return res.status(403).json({ error: &#39;Forbidden: Unrecognized IP Address&#39; });<br>  }<br><br>  next();<br>};<br><br>app.post(&#39;/webhooks/provider&#39;, ipWhitelistMiddleware, (req, res) =&gt; {<br>  // Process the webhook safely knowing it came from a trusted IP<br>  res.status(200).send(&#39;Webhook received&#39;);<br>});</pre><h3>Signature Validation</h3><p>While IP whitelisting checks <em>where</em> the message came from, Signature Validation proves exactly <em>who</em> sent it and guarantees that the message was not altered in transit.</p><p>This is the gold standard of webhook security. If you implement only one security measure in your architecture, it must be this.</p><h3>How Cryptographic Signatures Work</h3><p>Signature validation relies on a symmetric key system, usually utilizing a Hash-based Message Authentication Code (HMAC). The process follows a strict mathematical handshake:</p><ul><li><strong>The Shared Secret:</strong> When you configure a webhook with a provider, they generate a long, random string called a “Signing Secret”. Only you and the provider know this secret. It must be kept entirely out of your version control and stored safely in your environment variables.</li><li><strong>The Provider’s Hash:</strong> Before the provider sends the webhook, they take the entire JSON payload and mix it with the Signing Secret using a cryptographic hashing algorithm (such as SHA-256). They attach this resulting string to the HTTP headers of the request.</li><li><strong>The Receiver’s Hash:</strong> When your server receives the request, it takes the incoming payload, retrieves your secure copy of the Signing Secret and runs the exact same hashing algorithm on your end.</li><li><strong>The Comparison:</strong> Your server compares the hash it generated against the hash the provider sent in the header.</li></ul><p>If an attacker intercepts the request and changes a billing payload from “amount”: 100 to “amount”: 10000, the payload is fundamentally altered. When your server hashes that modified payload, the resulting signature will look entirely different from the one in the header. The request is immediately rejected.</p><h3>Parsed Objects vs. Raw Buffers</h3><p>There is a massive architectural caveat when implementing signature validation across modern web frameworks.</p><p>To generate a perfectly matching cryptographic hash, you must hash the <strong>exact, byte-for-byte raw string</strong> that the provider sent over the wire.</p><p>Most modern web frameworks automatically intercept incoming requests and parse the JSON string into a native language object (like a dictionary or an object map) for developer convenience.</p><p>If you attempt to convert that parsed object back into a string to run your hash, the operation will fail. The serialization process inherently removes whitespace, alters carriage returns and changes the byte-level formatting. The hashes will never match and your webhooks will mysteriously fail validation 100% of the time.</p><p>To successfully validate a signature, you must configure your web server to capture the raw byte stream of the request <em>before</em> the framework attempts to parse it into JSON.</p><h3>The Implementation Example</h3><p>Here is a complete, production-ready implementation of signature validation in Express.js. Notice how it specifically bypasses the standard JSON parser to access the raw buffer.</p><pre>const express = require(&#39;express&#39;);<br>const crypto = require(&#39;crypto&#39;);<br>const app = express();<br><br>const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || &#39;whsec_super_secret_key_123&#39;;<br><br>// 1. Capture the raw body buffer<br>// We bypass standard parsing middleware for this specific route to maintain byte-for-byte accuracy<br>app.post(&#39;/webhooks/secure&#39;, express.raw({ type: &#39;application/json&#39; }), (req, res) =&gt; {<br>  <br>  // 2. Extract the signature from the headers<br>  const signatureHeader = req.headers[&#39;x-provider-signature&#39;];<br>  <br>  if (!signatureHeader) {<br>    return res.status(401).json({ error: &#39;Missing signature header&#39; });<br>  }<br><br>  try {<br>    // 3. Generate our own signature using the raw body buffer and our secret<br>    const expectedSignature = crypto<br>      .createHmac(&#39;sha256&#39;, WEBHOOK_SECRET)<br>      .update(req.body) // req.body is a raw buffer here, preserving exact formatting<br>      .digest(&#39;hex&#39;);<br>    <br>    // 4. Safely compare the signatures<br>    const signatureBuffer = Buffer.from(signatureHeader);<br>    const expectedBuffer = Buffer.from(expectedSignature);<br><br>    // We use timingSafeEqual to prevent timing attacks<br>    if (signatureBuffer.length !== expectedBuffer.length || <br>        !crypto.timingSafeEqual(signatureBuffer, expectedBuffer)) {<br>      console.error(&#39;Webhook signature mismatch. Potential tampering detected.&#39;);<br>      return res.status(401).json({ error: &#39;Invalid signature&#39; });<br>    }<br><br>    // 5. If we reach here, the webhook is cryptographically proven to be authentic.<br>    // Now we can safely parse the raw buffer into a usable native object.<br>    const payload = JSON.parse(req.body.toString());<br>    console.log(&#39;Secure webhook received for event:&#39;, payload.event_type);<br>    <br>    // Process business logic securely...<br>    return res.status(200).send(&#39;Webhook verified and processed&#39;);<br><br>  } catch (error) {<br>    console.error(&#39;Error processing webhook:&#39;, error);<br>    return res.status(500).send(&#39;Internal Server Error&#39;);<br>  }<br>});</pre><h3>Mitigating Timing Attacks</h3><p>Notice the use of <em>crypto.timingSafeEqual()</em> in the code above instead of a standard === operator. This is a critical cryptographic concept.</p><p>Standard string comparisons evaluate characters sequentially and abort the process as soon as they find a mismatch. This means a string that is completely wrong fails slightly faster than a string that is 90% correct.</p><p>Sophisticated attackers can monitor your endpoint and use these microscopic time differences that are measured in fractions of a millisecond to guess your signature character by character. By analyzing how long it takes your server to reject the request, they can iteratively rebuild the correct hash.</p><p>A constant-time comparison function forces the CPU to take the exact same amount of time to compare the strings, regardless of where the mismatch occurs. This completely neutralizes the timing attack, ensuring that an invalid signature is rejected safely without leaking any information about the validation process.</p><h3>Conclusion (Defense in Depth)</h3><p>Securing a webhook architecture is not about choosing between IP Whitelisting or Signature Validation. A robust system uses <strong>Defense in Depth</strong>, combining multiple layers of security.</p><p>If your API partner offers static IP addresses, implement an IP whitelist at your network’s edge (such as a load balancer or a reverse proxy). This acts as a highly efficient filter, dropping junk traffic and unauthorized scanners before they ever consume compute resources on your application servers.</p><p>However, you must always pair that network filter with Signature Validation at the application layer. It is the final, definitive check, the only cryptographic guarantee that the data you are about to save to your database is legitimate, unaltered and securely authored by the trusted provider.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41850f445290" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Blocking Your API: A Guide to Message Queues]]></title>
            <link>https://justallan.medium.com/stop-blocking-your-api-a-guide-to-message-queues-14f1eb6383f5?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/14f1eb6383f5</guid>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Tue, 19 May 2026 09:35:35 GMT</pubDate>
            <atom:updated>2026-05-19T09:35:35.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rj2HRhlODdGOA7N46Oz5Lg.png" /></figure><p>If you have ever stared at a loading spinner on a website for ten seconds only to be greeted by a 502 Bad Gateway error, you have witnessed the silent killer of scalable software: synchronous execution.</p><p>When you build a new feature, it is incredibly tempting to handle everything synchronously. A user triggers an action, your backend receives the request, processes the business logic, interacts with a database, communicates with third-party networks and finally returns a 200 OK to the client.</p><p>At low traffic, this works flawlessly. It is easy to write, easy to trace and easy to test. But at scale, synchronous execution becomes a massive structural liability.</p><p>If your application needs to trigger processes that rely on external servers (like an email gateway or a payment processor), your API must hold the client’s HTTP connection open while it waits for those tasks to finish. If a sudden traffic spike hits, your system will rapidly run out of open connections, exhaust its memory pool and crash.</p><p>To build a resilient system that can absorb massive traffic spikes without dropping a single request, you must fundamentally change how you view your API. You must separate <strong>ingestion</strong> from <strong>execution</strong>.</p><p>You need a <strong>Message Queue</strong>.</p><h3>1. The Anatomy of a System Bottleneck</h3><p>To understand why queues are necessary, we have to look at how APIs fail under load.</p><p>Imagine you are running an e-commerce platform. Your API has a /api/checkout endpoint. When called, it validates the cart, updates the database, charges the credit card and finally sends a confirmation email.</p><p>Let’s assume sending the email via an external SMTP server takes 2 seconds.</p><p>If one user checks out, your server is busy for 2 seconds. If 100 users check out at the exact same time, your server attempts to open 100 concurrent connections to the email provider. But what if a marketing campaign goes viral and 10,000 users check out simultaneously?</p><p>Your server attempts to hold 10,000 HTTP connections open for 2 seconds. Most web frameworks and database connection pools are not configured to handle this. The server will freeze, subsequent requests will time out and your entire application will go offline , all because it was waiting for an email to send.</p><p>Your API is acting as a processing plant, when it should be acting as a mailbox.</p><h3>2. Producers, Brokers and Consumers</h3><p>A message queue transforms your architecture from a single, blocking pipeline into a decoupled, asynchronous system. Instead of processing data immediately at the edge of your app, you drop the task into a secure buffer and handle it on your own terms.</p><p>A robust queue architecture splits your system into three distinct roles:</p><p><strong>1. The Producer (The Mailbox)</strong> This is your API layer. When a request comes in, the Producer’s <em>only</em> job is to validate the payload, package the data into a “job”, push that job into the queue and immediately return a 202 Accepted response to the client. The Producer never communicates with an external mail server or waits for a network handshake. It does its job in milliseconds and moves on to the next request.</p><p><strong>2. The Message Broker (The Sorting Facility)</strong> This is the temporary storage layer. Typically, this is an in-memory data store like Redis, or a dedicated broker like RabbitMQ or Apache Kafka. It acts as a highly resilient buffer, holding the jobs safely in memory or on disk until your downstream systems are ready to process them.</p><p><strong>3. The Consumer (The Mail Carrier)</strong> This is an isolated background worker running on a completely separate thread or server. It continuously polls the message broker, pulls down jobs one by one and executes the actual network-bound task (such as connecting to an SMTP server and delivering the email).</p><h3>3. Mastering Backpressure</h3><p>The greatest advantage of this decoupled architecture is the ability to handle <strong>Backpressure</strong>.</p><p>Let’s revisit our 10,000-user traffic spike. With a message queue in place, your API controllers don’t slow down. They can ingest thousands of requests per second because dropping a job into a Redis broker is nearly instantaneous.</p><p>Meanwhile, your Consumer workers are configured to only pull a safe number of jobs at a time (say 50 concurrent jobs).</p><p>The API absorbs the massive spike instantly. The queue safely expands to hold the 10,000 pending jobs and your background workers hum along at a steady, manageable pace of 50 jobs at a time, completely shielding your downstream database and third-party email provider from being overwhelmed.</p><p>Your infrastructure bends, but it never breaks.</p><h3>4. Why You Need Priority Queues</h3><p>If you implement a standard queue, you will quickly discover a new problem. By default, message queues operate on a strict <strong>FIFO</strong> (First-In, First-Out) basis. Whichever message arrives first is the first one handed to a worker.</p><p>While this sounds fair, FIFO ordering creates severe user experience issues in a production environment due to the “noisy neighbor” effect. Let’s look at our email delivery system across three different application events:</p><ol><li><strong>Authentication Events:</strong> A user requests a One-Time Password (OTP) or a password reset link to log into their accoun</li><li><strong>Payment Events:</strong> A customer completes a purchase and expects an instant receipt or invoice.</li></ol><p>3.<strong> Campaign Events:</strong> A marketing admin schedules a weekly promotional newsletter to be sent to 250,000 subscribers.</p><p>If you are using a standard FIFO queue and the marketing admin clicks “Send” on that campaign, the broker is instantly flooded with 250,000 jobs.</p><p>If a separate user tries to log in and requests an authentication OTP exactly two seconds later, that critical login email becomes job #250,001. That user will be stuck staring at their inbox for hours just to log into your platform, simply because an automated marketing blast is hogging all the worker resources.</p><h3>Bypassing the Line</h3><p>To solve this, we cannot treat all messages equally. We must implement a <strong>Priority Queue</strong>. Instead of appending every job to the back of a single line, we assign numerical weights or urgency levels to the payloads as they enter the broker:</p><ul><li><strong>Priority 1 (Critical — OTPs &amp; Resets):</strong> These bypass the entire queue and jump to the absolute front of the line. The next available worker will always take a Priority 1 job over anything else.</li><li><strong>Priority 2 (High — Payments &amp; Receipts):</strong> These are processed immediately after any outstanding critical tasks are cleared, ensuring buyers aren’t left wondering if their transaction succeeded.</li><li><strong>Priority 3 (Low — Bulk Campaigns):</strong> These are pushed to the back. They are only processed when the higher-priority pools are entirely empty.</li></ul><p>By introducing priorities, your background workers will actively drain the high-urgency pools first. Time-sensitive transactional actions are never bottlenecked by low-urgency background operations.</p><h3>5. Designing for Failure: Retries and Dead Letters</h3><p>The “happy path” is a lie. Networks drop packets, third-party APIs enforce rate limits and databases occasionally deadlock.</p><p>If your queue architecture assumes that a worker will always succeed on the first try, you will silently lose user data. But if you blindly retry every failed job in a tight, infinite loop, you will eventually accidentally DDoS your own infrastructure.</p><p>A resilient queue system expects failure and handles it using two core mechanisms:</p><h3>Exponential Backoff</h3><p>If a worker picks up a job to send an email, but the external mail provider drops the connection, the job shouldn’t vanish. The worker must return the job to the broker to be retried.</p><p>However, retrying the job immediately is an amateur mistake. If an external network is down, hammering it again one millisecond later will only worsen the outage. Instead, the broker uses an <strong>Exponential Backoff</strong> schedule. It waits 2 seconds before the first retry, then 4 seconds, then 8, 16, 32, and so on. This gives the failing downstream service the breathing room it needs to recover.</p><h3>The Dead Letter Queue (DLQ)</h3><p>What happens if a job fails continuously and exhausts its maximum retry limit? Perhaps a developer introduced a bug in the payload, or the recipient’s email address is fundamentally malformed.</p><p>It cannot be allowed to clog the queue and waste worker resources forever. The broker isolates this toxic message and banishes it to a specialized sidebar queue called a <strong>Dead Letter Queue (DLQ)</strong>.</p><p>The DLQ is a graveyard for unprocessable messages. The main queue stays clean and keeps moving, while the DLQ safely stores the broken payloads. This allows your engineering team to set up monitoring alerts, manually inspect the broken data, patch the underlying bug and replay the jobs without losing any user data.</p><h3>6. The Golden Rule: Idempotency</h3><p>There is one final architectural hazard you must account for when designing asynchronous systems. Message brokers (like Redis or RabbitMQ) generally guarantee “At-Least-Once” delivery, but they rarely guarantee “Exactly-Once” delivery.</p><p>Imagine your worker successfully processes a payment receipt and sends the email. But right before the worker can send the final ACK (acknowledgment) back to the broker to say &quot;I&#39;m done, delete this job,&quot; a brief network partition occurs.</p><p>The broker never gets the ACK. It assumes the worker crashed mid-job. To ensure the job isn&#39;t lost, the broker places the <em>exact same job</em> back into the queue and hands it to a second worker.</p><p>If your code is not designed to handle this, you will email the user the same receipt twice. (Or worse, if this was a billing queue, you would charge their credit card twice).</p><p>To prevent this, your queue workers must be <strong>Idempotent</strong>. Idempotency means that processing the same job multiple times yields the exact same result as processing it once. You achieve this by passing a unique transaction_id inside the job payload, and having the worker check your database (<em>&quot;Have I already processed this ID?&quot;</em>) before executing the action.</p><h3>Stop Blocking Your API</h3><p>Synchronous architectures are inherently fragile. By treating your API as an ingestion engine rather than an execution engine, you unlock massive scalability. Message queues provide the backpressure needed to survive traffic spikes, the priority routing required to protect critical user experiences and the error-handling mechanisms to ensure data is never lost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14f1eb6383f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Query Params vs. Request Payload: The Definitive Guide for API Design]]></title>
            <link>https://justallan.medium.com/query-params-vs-request-payload-the-definitive-guide-for-api-design-8d4981d40e83?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d4981d40e83</guid>
            <category><![CDATA[restful-api]]></category>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Mon, 18 May 2026 07:05:43 GMT</pubDate>
            <atom:updated>2026-05-18T07:05:43.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAGZ4iJwk3bz2fhxyT5rGg.png" /></figure><p>If you are building or consuming APIs, you’ve likely stared at an endpoint and asked yourself: <em>“Should I send this data in the URL or should I pack it into the request body?”</em></p><p>It’s a rite of passage for every developer. While both methods successfully transfer data from the client to the server, mixing them up can lead to security vulnerabilities, broken caching and APIs that are a nightmare to maintain.</p><p>In this guide, we are going to break down the architectural differences between Query Parameters and Request Payloads (the body), compare them head-to-head and establish concrete rules for when to use which.</p><h3>Part 1: The Query Parameter</h3><p>Query parameters are key-value pairs attached directly to the end of a URL. They sit behind the question mark (?) and are separated by ampersands (&amp;).</p><p><strong>Example</strong></p><pre>GET [https://api.store.com/products?category=shoes&amp;sort=price_asc&amp;limit=20](https://api.store.com/products?category=shoes&amp;sort=price_asc&amp;limit=20)ExampleGET [https://api.store.com/products?category=shoes&amp;sort=price_asc&amp;limit=20](https://api.store.com/products?category=shoes&amp;sort=price_asc&amp;limit=20)</pre><p>In this HTTP request category, sort and limit are the query parameters.</p><h4>Core Characteristics</h4><ul><li><strong>Highly Visible:</strong> The data is right there in the URL bar. This means the state of the request can be bookmarked, copied and shared.</li><li><strong>Limited Capacity:</strong> URLs cannot be infinitely long. While the exact limit depends on the browser and server (historically around 2,048 characters), you cannot use query params to send massive blocks of text.</li><li><strong>Flat Structure:</strong> Query parameters are inherently strings. While you can hack together arrays (e.g., ?tags=tech,news or ?tag=tech&amp;tag=news), they do not natively support complex, nested data structures.</li><li><strong>Cache-Friendly:</strong> CDNs and browsers use the URL as the primary cache key. A request to ?page=1 can be cached easily, ensuring subsequent identical requests don&#39;t hit your database.</li></ul><h3>Part 2: The Request Payload</h3><p>The Request Payload (often called the Request Body) is the data sent hidden “under the hood” of the HTTP request. It travels alongside the request headers, separate from the URL.</p><p><strong>Example:</strong></p><pre>POST /api/users HTTP/1.1<br>Host: api.store.com<br>Content-Type: application/json<br><br>{<br>  &quot;username&quot;: &quot;johndoe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;preferences&quot;: {<br>    &quot;notifications&quot;: true,<br>    &quot;theme&quot;: &quot;dark&quot;<br>  }<br>}</pre><h4>Core Characteristics</h4><ul><li><strong>Hidden from the URL:</strong> The data is not visible in the browser’s address bar, nor does it typically show up in server access logs.</li><li><strong>Massive Capacity:</strong> The payload can handle megabytes or even gigabytes of data. If you are uploading a 4K video or a massive CSV file, it goes in the payload.</li><li><strong>Complex Data Structures:</strong> Because you specify a Content-Type (like application/json or multipart/form-data), the payload can hold deeply nested objects, arrays, booleans and binary files.</li><li><strong>Modifies State:</strong> Payloads are almost exclusively used when you want the server to do some heavy lifting, creating a new record, updating a database or processing a file.</li></ul><h3>Part 3: The Head-to-Head Breakdown</h3><p>Instead of a dry table, let’s look at exactly how these two methods clash across the seven most critical API design categories.</p><p><strong>1. The HTTP Methods</strong></p><ul><li><strong>Query Parameters</strong> are the domain of GET and DELETE requests, where you are asking the server to locate something specific.</li><li><strong>Request Payloads</strong> are the heavy lifters used in POST, PUT and PATCH requests, where you are handing the server new data to process or save.</li></ul><p><strong>2. Visibility &amp; Footprint</strong></p><ul><li><strong>Query Parameters</strong> live in plain sight. They are plastered in the browser’s address bar, saved in browser history and permanently etched into server access logs.</li><li><strong>Request Payloads</strong> are discreet. They fly under the radar, hidden from the URL and completely omitted from standard server routing logs.</li></ul><p><strong>3. Size Constraints</strong></p><ul><li><strong>Query Parameters</strong> have a hard ceiling. While the exact limit depends on the browser and server, you generally start hitting brick walls around the 2KB (2,048 character) mark.</li><li><strong>Request Payloads</strong> are practically unlimited. Need to upload a 4GB 4K video? It goes in the payload. Your only limit is how you configure your server (like Nginx’s client_max_body_size).</li></ul><p><strong>4. Data Complexity</strong></p><ul><li><strong>Query Parameters</strong> are flat and simple. Everything is a string. If you want to send arrays or nested objects, you have to resort to ugly bracket hacks (e.g., ?user[address][zip]=90210).</li><li><strong>Request Payloads</strong> thrive on complexity. Because you define a Content-Type, you can cleanly send deeply nested JSON, XML or binary Multipart Form-Data.</li></ul><p><strong>5. Security &amp; Logging (The Danger Zone)</strong></p><ul><li><strong>Query Parameters</strong> are a security hazard for sensitive data. Even over HTTPS, query strings are logged in plain text by intermediate proxies, load balancers and analytics tools. Never put a password here.</li><li><strong>Request Payloads</strong> are the secure choice. Assuming you are using HTTPS (which encrypts the entire body in transit), payload data is protected from network snoopers and kept safely out of system logs.</li></ul><p><strong>6. Caching Behavior</strong></p><ul><li><strong>Query Parameters</strong> are a CDN’s best friend. Browsers and edge caches use the URL as the primary cache key. A request to ?page=2 can be cached seamlessly to save database hits.</li><li><strong>Request Payloads</strong> intentionally bypass caching. You generally do not want to cache a POST request because it implies a state change on the server.</li></ul><p><strong>7. Shareability</strong></p><ul><li><strong>Query Parameters</strong> are built to be shared. If a user sets up the perfect dashboard filters, they can copy the URL and Slack it to a coworker. The state survives.</li><li><strong>Request Payloads</strong> are ephemeral to the user. You cannot bookmark a payload or send it in a link.</li></ul><h3>Part 4: Use Cases</h3><p>Designing a clean RESTful API means following the semantics of HTTP. Here are the golden rules for when to use each method.</p><h4>When to use Query Parameters</h4><p><strong>1. Filtering and Searching</strong></p><p>If a user is looking for a specific subset of data, use query params.</p><ul><li><em>Example:</em> GET /users?role=admin&amp;active=true</li></ul><p><strong>2. Pagination</strong></p><p>When you need to chunk data into readable pages.</p><ul><li><em>Example:</em> GET /articles?page=3&amp;limit=50</li></ul><p><strong>3. Sorting</strong></p><p>When you want to alter the order of the returned data.</p><ul><li><em>Example:</em> GET /flights?sort=-departure_time</li></ul><p><strong>4. Shareable States</strong></p><p>If a user applies a bunch of filters on your dashboard and wants to Slack that exact view to a coworker, those filters <em>must</em> be in the URL.</p><h4>When to use the Request Payload</h4><p><strong>1. Creating New Resources</strong></p><p>If you are adding a new row to a database, send a POST request with the entity&#39;s details in the payload.</p><p><strong>2. Updating Existing Resources</strong></p><p>If you are modifying data, use PUT (replace the whole resource) or PATCH (update specific fields) with the changes in the payload.</p><p><strong>3. Sending Sensitive Information</strong></p><p>Never put passwords, API keys, or personally identifiable information (PII) in a query parameter. Even if you use HTTPS (which encrypts the traffic), the URL is still saved in browser histories, proxy server logs and analytics tools. Send sensitive data in the payload.</p><ul><li><em>Example:</em> A login request should be a POST with the username and password in the body.</li></ul><p><strong>4. Complex or Massive Data</strong></p><p>If your data is deeply nested JSON or includes files/images, it physically cannot function as a query parameter.</p><h3>Part 5: Common Pitfalls to Avoid</h3><p>As you build out your APIs, watch out for these frequent mistakes:</p><ul><li><strong>GET Requests with Payloads:</strong> Technically, the HTTP specification doesn’t outright forbid sending a payload with a GET request. However, it is widely considered a bad practice. Many servers, proxies and caching layers will actively strip the body out of a GET request or reject it entirely. If you need to send a payload, upgrade your request to a POST.</li><li><strong>URL Length Limits:</strong> If you are building a complex advanced search feature and your query parameters are getting so long that you hit the 2,048 character limit, you have a design problem. In these rare edge cases, it is acceptable to convert the search endpoint to a POST request and pass the complex search criteria via a JSON payload.</li><li><strong>Payload Security:</strong> Moving a password from the query parameter to the payload does <em>not</em> encrypt it. It simply keeps it out of the server logs. To protect data in transit, your API must be served over HTTPS.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4981d40e83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Process 10,000 Webhooks per Second Without Melting Your Database (Surviving the spike)]]></title>
            <link>https://justallan.medium.com/how-to-process-10-000-webhooks-per-second-without-melting-your-database-surviving-the-spike-9b842ad980a1?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b842ad980a1</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 20:43:55 GMT</pubDate>
            <atom:updated>2026-02-27T20:43:55.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sUKO96n3eZB6Nd1QqXMTGA.png" /></figure><p>When you build a webhook receiver, testing it with a single Postman request makes you feel invincible. The payload comes in, your Express.js controller parses it, queries the database, updates a user’s balance, triggers a welcome email, and returns a 200 OK. It takes 150 milliseconds. Beautiful.</p><p>But what happens when your payment provider executes a batch job at exactly midnight, sending 10,000 transaction webhooks to your server in the span of two seconds?</p><p>If your architecture relies on synchronous processing, your server doesn’t just slow down, it melts. Your Node.js Event Loop blocks. Your PostgreSQL connection pool maxes out. Queries start timing out. The payment provider assumes the webhooks failed and starts aggressively retrying them, effectively launching a DDoS attack on your own infrastructure.</p><p>To survive the spike, you need to stop processing data at the edge. You need to build a <strong>Shock Absorber</strong>.</p><h3>Synchronous Processing</h3><p>The most common mistake scaling developers make is treating a webhook endpoint like a standard CRUD operation.</p><p>Here is the naive approach that kills the product:</p><pre>// THE ANTI-PATTERN: Synchronous processing at the edge<br>app.post(&#39;/api/webhooks/payments&#39;, async (req, res) =&gt; {<br>  try {<br>    const payload = req.body;<br>    <br>    // 1. Heavy database transaction (Locks rows, burns connection pool)<br>    await db.transaction(async (trx) =&gt; {<br>      await updateLedger(payload.amount, trx);<br>      await updateUserBalance(payload.userId, trx);<br>    });<br><br>    // 2. Third-party API call (What if SendGrid takes 3 seconds to respond?)<br>    await sendReceiptEmail(payload.userId);<br>    <br>    // 3. Finally returning the response<br>    res.status(200).send(&#39;Processed&#39;);<br>  } catch (error) {<br>    res.status(500).send(&#39;Failed&#39;);<br>  }<br>});</pre><p>In this model, the HTTP connection is held hostage while your server does the heavy lifting. If 10,000 requests hit this route, Express tries to open 10,000 concurrent database connections and 10,000 outbound API calls. PostgreSQL will start dropping connections, and your memory usage will spike until the container crashes.</p><h3>The Architecture Shift</h3><p>To handle massive concurrency, you must completely decouple <strong>ingestion</strong> from <strong>processing</strong>.</p><p>The goal of your webhook endpoint is not to process the data. Its <em>only</em> job is to catch the data, drop it into a secure bucket and immediately close the HTTP connection.</p><p>Instead of returning a 200 OK (meaning &quot;I have processed this&quot;), you return a 202 Accepted (meaning &quot;I have received this and will process it later&quot;).</p><p>Here is how you build the Shock Absorber using Express.js and a Redis queue (using a library like BullMQ).</p><h4>Step 1: The Ingestion Layer (Lightning Fast)</h4><p>Your Express route should do exactly three things: authenticate the webhook, validate the payload shape and push it to the queue.</p><pre>import { Queue } from &#39;bullmq&#39;;<br><br>// Initialize the Redis queue<br>const paymentQueue = new Queue(&#39;payment-webhooks&#39;, {<br>  connection: { host: &#39;localhost&#39;, port: 6379 }<br>});<br><br>app.post(&#39;/api/webhooks/payments&#39;, async (req, res) =&gt; {<br>  // 1. Quick Auth &amp; Validation (Keep it under 5ms)<br>  if (!isValidSignature(req.headers[&#39;x-signature&#39;])) {<br>    return res.status(401).send(&#39;Unauthorized&#39;);<br>  }<br><br>  // 2. Dump the raw payload into the queue<br>  await paymentQueue.add(&#39;process-payment&#39;, req.body, {<br>    attempts: 3, <br>    backoff: { type: &#39;exponential&#39;, delay: 2000 }<br>  });<br><br>  // 3. Immediately release the connection<br>  res.status(202).send(&#39;Accepted&#39;);<br>});</pre><p>By removing the database transactions and third-party API calls from the route, the response time drops from 200ms to ~10ms. A single Node.js instance can now easily absorb thousands of requests per second because the Event Loop is never blocked.</p><h4>Step 2: The Worker Layer (Controlled Concurrency)</h4><p>Now that the data is safely resting in Redis, you process it on your own terms.</p><p>You spin up a separate background worker process. This worker pulls jobs from the queue at a rate your database can actually handle. If PostgreSQL is tuned to handle 50 concurrent connections, you tell your worker to only process 50 jobs at a time.</p><pre>import { Worker } from &#39;bullmq&#39;;<br><br>// The Worker processes jobs in the background, completely separate from the API<br>const worker = new Worker(&#39;payment-webhooks&#39;, async job =&gt; {<br>  const payload = job.data;<br>  <br>  // Now we do the heavy lifting safely<br>  await db.transaction(async (trx) =&gt; {<br>    await updateLedger(payload.amount, trx);<br>    await updateUserBalance(payload.userId, trx);<br>  });<br><br>  await sendReceiptEmail(payload.userId);<br>}, {<br>  connection: { host: &#39;localhost&#39;, port: 6379 },<br>  concurrency: 50 // The magic number: protects Postgres from melting<br>});<br><br>worker.on(&#39;completed&#39;, job =&gt; console.log(`Job ${job.id} done!`));<br>worker.on(&#39;failed&#39;, (job, err) =&gt; console.error(`Job ${job.id} failed:`, err));</pre><h3>The Alternative: Append-Only PostgreSQL</h3><p>If you don’t want to introduce Redis to your infrastructure, you can build the Shock Absorber entirely in PostgreSQL.</p><p>Instead of writing to a queue, your Express endpoint performs a single, ultra-fast INSERT into an append-only webhook_events table (e.g., INSERT INTO webhook_events (payload, status) VALUES ($1, &#39;pending&#39;)). A background cron job or a dedicated worker then polls this table, processes the rows in batches, and marks them as &#39;completed&#39;. Because it&#39;s a simple append-only operation, postgres handles the writes incredibly fast without dealing with complex row locks.</p><h3>Conclusion</h3><p>Engineering at scale is rarely about writing clever business logic; it is about managing constraints.</p><p>When you build integrations, you cannot control the volume or velocity of the data being pushed to you. But you can control how your system absorbs the impact. Decoupling ingestion from processing isn’t just a performance optimization, it is the difference between an infrastructure that bends and an infrastructure that breaks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b842ad980a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles and How I Apply Them in React]]></title>
            <link>https://justallan.medium.com/solid-principles-and-how-i-apply-them-in-react-52168c0c5b98?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/52168c0c5b98</guid>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 17:53:38 GMT</pubDate>
            <atom:updated>2026-01-17T17:53:38.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bF9O9RTXZyn2_FmBvRwDBw.png" /><figcaption>SOLID Principles and How I Apply Them in React</figcaption></figure><p>I recently made the mistake of opening a React repository I wrote sometimes back.</p><p>You know that feeling? You look at the code and think, <em>“Who wrote this spaghetti?”</em> Then you check the git blame and realize... it was you.</p><p>“Younger Me” was enthusiastic. He shipped features fast. But he also treated software architecture like a suggestion rather than a rule. His components were fragile, untestable, and impossible to extend without breaking five other things.</p><p>Instead of just deleting the repo and pretending it never happened, I decided to use it as a learning opportunity. I refactored one specific “God Component” using <strong>SOLID principles</strong>.</p><p>If you’ve ever wondered how these “old school” OOP rules apply to modern React, this guide is for you. We’ll walk through the five principles by fixing my old code, step-by-step.</p><p><em>Note: The code below is a simplified example, not the exact production code, but it perfectly captures the structural mess I was dealing with.</em></p><h3>The Problem: The “God Component”</h3><p>This was the component I found. I called it UserProfile, but I should have called it TheKitchenSink.</p><p>It tried to do everything: fetch data, manage state, handle business logic, and render UI.</p><pre>// UserProfile.js (The &quot;Before&quot; Mess)<br>import { useState, useEffect } from &#39;react&#39;;<br><br>function UserProfile() {<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(true);<br><br>  // Mistake 1: Hardcoded Fetching Logic inside the view<br>  useEffect(() =&gt; {<br>    fetch(&#39;/api/user&#39;)<br>      .then(res =&gt; res.json())<br>      .then(data =&gt; {<br>        setUser(data);<br>        setLoading(false);<br>      });<br>  }, []);<br><br>  // Mistake 2: Mixing UI and Business Logic controls<br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br><br>  return (<br>    &lt;div className=&quot;card&quot;&gt;<br>      &lt;h2&gt;{user.name}&lt;/h2&gt;<br>      &lt;p&gt;{user.email}&lt;/p&gt;<br>      {/* Mistake 3: Business logic buried in JSX */}<br>      &lt;button onClick={() =&gt; alert(&#39;Logged out&#39;)}&gt;Logout&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>At the time, I thought this was fine. But I had violated almost every principle in the book. Let’s fix it.</p><h3>1. S — Single Responsibility Principle (SRP)</h3><p><strong>“A component should have one reason to change.”</strong></p><p>My old component had about four reasons to change. It was an HR manager (data), a designer (UI), and a database admin (fetching) all at once.</p><p>If the API changed? I broke the UI. If the design changed? I risked breaking the fetch logic.</p><p>To fix this, I stopped forcing the component to multitask. I separated the <strong>Brain</strong> (Logic) from the <strong>Face</strong> (UI).</p><p>First, I extracted the logic into a custom hook. This is the “Brain.”</p><pre>// useUser.js (The Brain)<br>function useUser() {<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  <br>  useEffect(() =&gt; {<br>    fetch(&#39;/api/user&#39;)<br>      .then(res =&gt; res.json())<br>      .then(data =&gt; {<br>        setUser(data);<br>        setLoading(false);<br>      });<br>  }, []);<br><br>  return { user, loading };<br>}</pre><p>Then, I made the component dumb and pure. This is the “Face.”</p><pre>// UserProfileView.jsx (The Face)<br>function UserProfileView({ user, onLogout }) {<br>  return (<br>    &lt;div className=&quot;card&quot;&gt;<br>      &lt;h2&gt;{user.name}&lt;/h2&gt;<br>      &lt;p&gt;{user.email}&lt;/p&gt;<br>      &lt;button onClick={onLogout}&gt;Logout&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, UserProfileView only changes if the <em>design</em> changes. useUser only changes if the <em>data</em> changes.</p><h3>2. O — Open/Closed Principle (OCP)</h3><p><strong>“Open for extension, closed for modification.”</strong></p><p>I vividly remember when I asked myself for an “Admin” version of this profile. Younger Me responded by adding a bunch of ugly if (isAdmin) checks directly inside the UserProfileView.</p><p>Every time I touched that file to add a feature, I risked breaking the existing features.</p><p>The adult way to handle this is <strong>Composition</strong>. Instead of hacking the file, I wrapped it.</p><pre>// AdminProfileView.jsx<br>function AdminProfileView({ user, onLogout }) {<br>  return (<br>    &lt;div className=&quot;admin-wrapper&quot; style={{ border: &#39;2px solid gold&#39; }}&gt;<br>      &lt;span className=&quot;badge&quot;&gt;ADMIN&lt;/span&gt;<br>      {/* I am reusing my old code without modifying it! */}<br>      &lt;UserProfileView user={user} onLogout={onLogout} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, the original UserProfileView is safe. I can create SuperAdminView, GuestView, or BannedView without ever touching the original source code.</p><h3>3. L — Liskov Substitution Principle (LSP)</h3><p><strong>“If it looks like a duck, it should quack like a duck.”</strong></p><p>This is where Younger Me caused the most bugs. I would build two components that <em>looked</em> interchangeable but weren’t.</p><p>I might have made AdminProfile accept a user prop, while UserProfile accepted userData. Then, I’d try to swap them in a list based on user roles, and the app would crash.</p><p>I learned that interchangeable components must sign the same contract.</p><pre>function ProfileList({ users }) {<br>  return users.map(user =&gt; {<br>    // This swap is safe because I forced both components<br>    // to accept the EXACT same props.<br>    const Component = user.isAdmin ? AdminProfileView : UserProfileView;<br>    <br>    return &lt;Component key={user.id} user={user} onLogout={handleLogout} /&gt;;<br>  });<br>}</pre><p>By enforcing that both components accept { user, onLogout }, I stopped the runtime crashes.</p><h3>4. I — Interface Segregation Principle (ISP)</h3><p><strong>“Don’t force components to take what they don’t need.”</strong></p><p>Younger Me was lazy. I loved passing the entire user object to every component because I didn&#39;t want to type out specific props.</p><pre>function UserCard({ user }) {<br>  // This component re-rendered when &#39;user.passwordHash&#39; changed. Why??<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>}</pre><p>This created performance “ghosts.” I would update a hidden setting in the user object (like user.lastLogin), and my UI would re-render for no reason because the prop changed.</p><p>I fixed it by being explicit:</p><pre>function UserCard({ name }) {<br>  return &lt;div&gt;{name}&lt;/div&gt;;<br>}</pre><p>It turns out, being specific isn’t just “boilerplate”, it’s strictness that saves you from performance hell later.</p><h3>5. D — Dependency Inversion Principle (DIP)</h3><p><strong>“Depend on abstractions, not concretions.”</strong></p><p>This was my biggest gripe back then: <em>“React testing is hard.”</em></p><p>It was hard because I made it hard. My useUser hook had fetch(&#39;/api/user&#39;) hardcoded inside it. To test it, I had to mock the global browser fetch, which is flaky and gross.</p><p>I was depending on a concrete implementation (the browser network stack). I should have depended on an abstraction (a function).</p><p>I refactored the hook to accept a fetcher function:</p><pre>function useUser(fetcher) {<br>  const [user, setUser] = useState(null);<br>  <br>  useEffect(() =&gt; {<br>    fetcher().then(setUser);<br>  }, [fetcher]);<br><br>  return user;<br>}</pre><p>Now, testing is trivial. I don’t need a browser. I just pass a fake function.</p><pre>// Tests are easy now<br>const mockFetcher = () =&gt; Promise.resolve({ name: &#39;Test User&#39; });<br>const user = useUser(mockFetcher);</pre><h3>Conclusion: Forgiving Younger Me</h3><p>Looking back, I can’t be too mad at Younger Me. He was trying to ship features. But he didn’t realize that <strong>code is read 10x more than it is written</strong>.</p><p>Refactoring with SOLID principles didn’t just make the code “cleaner”, it made it resilient. Now, when I open this file three years from now, I won’t have to ask “Who wrote this spaghetti?”</p><p>I’ll just say, “Nice.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52168c0c5b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why useEffect is the Wrong Place for API Calls]]></title>
            <link>https://justallan.medium.com/why-useeffect-is-the-wrong-place-for-api-calls-7e318e58d062?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e318e58d062</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[next]]></category>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 06:12:08 GMT</pubDate>
            <atom:updated>2025-11-20T09:18:02.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*DycsJ7kOWG0nNnK65ENsJg.png" /></figure><p>If you learned React in the last five years, this pattern is probably muscle memory for you:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>const UserProfile = () =&gt; {<br>  const [user, setUser] = useState(null);<br><br>  useEffect(() =&gt; {<br>      fetch(&#39;/api/user&#39;).then(data =&gt; setUser(data));<br>    }, []); // &lt;--- The classic &quot;componentDidMount&quot; hack<br>  <br>  if (!user) return &lt;div&gt;Loading...&lt;/div&gt;;<br><br>  return &lt;div&gt;&lt;h1&gt;{user.name}&lt;/h1&gt;&lt;/div&gt;;<br>};</pre><p>It looks innocent. It works. It’s in 90% of tutorials.</p><p><strong>It is also a performance disaster.</strong></p><p>When you build real-world applications with nested components, this pattern creates one of the most common performance bottlenecks in frontend development: <strong>The Network Waterfall.</strong></p><p>Here is why you need to stop doing it.</p><h3>The Waterfall Problem</h3><p>To understand why fetching inside useEffect is dangerous, you have to understand the React render cycle.</p><p>useEffect runs <strong>after</strong> the component renders. This means the browser has to download your JavaScript, parse it, render the component to the DOM, and <em>only then</em> does it kick off the network request.</p><p>This is fine for a single component. But what happens when you have children?</p><p>Imagine a &lt;Dashboard&gt; component that fetches userData. Inside it, there is a &lt;Feed&gt; component that fetches posts.</p><h3>The “Standard” (Bad) Approach:</h3><ul><li><strong>0ms:</strong> User visits page.</li><li><strong>100ms:</strong> &lt;Dashboard /&gt; mounts.</li><li><strong>150ms:</strong> &lt;Dashboard /&gt; fires useEffect to fetch user. <strong>(Network Start)</strong></li><li><strong>350ms:</strong> User data returns. &lt;Dashboard /&gt; re-renders.</li><li><strong>360ms:</strong> &lt;Feed /&gt; is finally allowed to mount.</li><li><strong>410ms:</strong> &lt;Feed /&gt; fires useEffect to fetch posts. <strong>(Network Start)</strong></li><li><strong>610ms:</strong> Posts return.</li></ul><p><strong>Do you see the gap?</strong></p><p>The &lt;Feed /&gt; component sat idle for <strong>360ms</strong> doing absolutely nothing, waiting for the parent to finish its business.</p><p>This is a <strong>Request Waterfall</strong>. Your application isn’t loading in parallel; it’s loading in steps. The deeper your component tree, the slower your app becomes.</p><h3>The “Spinner Hell” UX</h3><p>Performance isn’t just about milliseconds; it’s about <em>feel</em>.</p><p>When you chain useEffect fetches, you create &quot;Spinner Hell.&quot;</p><ul><li>User sees a big spinner (Parent loading).</li><li>Parent loads. Big spinner vanishes.</li><li>Suddenly, three smaller spinners appear (Children loading).</li><li>Children load.</li><li>One more spinner appears inside a child (Grandchild loading).</li></ul><p>The UI jumps around, content pops in drastically, and the app feels “janky” and slow, even if the API is fast.</p><h3>The Fix: Render-as-you-Fetch</h3><p>So, how do we fix this? We need to decouple <strong>fetching</strong> from <strong>rendering</strong>. We want the browser to start fetching <em>all</em> necessary data as soon as possible, without waiting for React to paint the screen first.</p><h3>Level 1: Hoisting (The “Good Enough” Fix)</h3><p>The simplest fix is to move the data fetching up to the highest common parent and fetch it all at once using Promise.all.</p><pre>// Dashboard.jsx<br>useEffect(() =&gt; {<br>  Promise.all([<br>    fetch(&#39;/api/user&#39;),<br>    fetch(&#39;/api/posts&#39;)<br>  ]).then(([user, posts]) =&gt; {<br>    setUser(user);<br>    setPosts(posts);<br>  });<br>}, []);</pre><p>Now, both requests start at <strong>150ms</strong>. You save the entire duration of the second request.</p><h3>Level 2: Data Fetching Libraries (The Professional Fix)</h3><p>Stop using raw useEffect for data fetching. Use libraries like <strong>TanStack Query (React Query)</strong> or <strong>SWR</strong>.</p><p>While they don’t inherently solve the waterfall problem if you nest them poorly, they make caching and state management so easy that you are more likely to structure your app correctly. Plus, they handle race conditions, deduplication, and revalidation — things useEffect struggles with.</p><h3>Level 3: Server Components (The Next.js/Modern Way)</h3><p>If you are using Next.js, this problem largely disappears with <strong>Server Components</strong>.</p><p>Since the code runs on the server, the “waterfall” happens between the server and the database (which usually have &lt;1ms latency), rather than between the client and the server (which has 50–200ms latency).</p><pre>// Dashboard (Server Component)<br>export default async function Dashboard() {<br>  // These start in parallel!<br>  const userData = getUser();<br>  const postsData = getPosts(); <br><br>  const [user, posts] = await Promise.all([userData, postsData]);<br><br>  return (<br>    &lt;&gt;<br>      &lt;UserProfile user={user} /&gt;<br>      &lt;Feed posts={posts} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Final Thoughts</h3><p>useEffect is a synchronization tool—it&#39;s meant to synchronize your component with an external system (like a subscription or the DOM). It was never really designed to be a data fetching orchestration layer.</p><p>When you write useEffect(() =&gt; fetch()..., you are telling React: <strong>&quot;Wait until you are done displaying the UI to start getting the data.&quot;</strong></p><p>For a fast, snappy application, you want the opposite: <strong>“Get the data as soon as possible, so we can display the UI.”</strong></p><p>Stop the waterfalls. Start fetching early.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e318e58d062" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keyset Pagination: The Smarter Way to Scroll]]></title>
            <link>https://justallan.medium.com/keyset-pagination-the-smarter-way-to-scroll-b4e09acab1a2?source=rss-fcedd6813a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4e09acab1a2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[database-design]]></category>
            <dc:creator><![CDATA[Allan Njoroge]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 08:45:49 GMT</pubDate>
            <atom:updated>2025-11-20T07:02:04.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2gFsBjBY4QB0SAUUFQnNKQ.png" /></figure><p>That OFFSET query is killing your database. Here’s the fix.</p><p>Most of us have written pagination the same way since the dawn of CRUD apps:</p><pre>SELECT * FROM products <br>ORDER BY created_at DESC <br>LIMIT 20 OFFSET 200;</pre><p>It looks innocent. It feels simple. Until your products table grows to a few million rows, and suddenly that API call feels like it’s powered by dial-up.</p><p>That’s because <strong>OFFSET is a trap</strong>.</p><p>Databases don’t magically “jump” 200 rows ahead. To fetch rows 201–220, your database has to <strong>read all 220 rows</strong> from disk, load them into memory, sort them… and then throw the first 200 away.</p><p>Multiply that by thousands of users scrolling, and your database starts sweating bullets.</p><h3>The Performance Time Bomb</h3><p>Imagine you’re running an e-commerce site. A customer is scrolling deep into your “All Products” category, triggering this query:</p><pre>SELECT * FROM products<br>ORDER BY price DESC<br>LIMIT 50 OFFSET 5000;</pre><p>At this point, your database isn’t returning 50 items. It’s <strong>reading 5,050 items</strong> from the disk, just to throw 5,000 of them in the trash. That’s over 100x more work than necessary.</p><p>The deeper the user scrolls, the slower it gets. Page 1 is fast. Page 500 is a coffee break. For any high-traffic feed, OFFSET is a performance disaster waiting to happen.</p><h3>Enter Keyset Pagination</h3><p>Instead of telling the database, “Skip the first 5,000 rows,” we tell it, “<strong>Start after this specific record.</strong>”</p><p>This method, also known as “cursor pagination,” uses a stable, indexed sort column (like created_at or price) as a &quot;cursor&quot;—a bookmark to remember where you left off.</p><p>Let’s rewrite that slow query the smart way.</p><p>Assume the last product on the previous page had a price of <strong>39.99</strong>. To get the next page, we just ask for products <em>cheaper</em> than that.</p><pre>SELECT * FROM products<br>WHERE price &lt; 39.99<br>ORDER BY price DESC<br>LIMIT 50;</pre><p>Look at that. No OFFSET. No scanning. The database uses its index on price to jump <em>directly</em> to that spot, grab the next 50 rows, and return them instantly.</p><p>It’s just as fast to fetch page 10,000 as it is to fetch page 1.</p><h3>The All-Important Tie-Breaker</h3><p>“But wait!” you say. “What if multiple products have the <em>same price</em>?”</p><p>You’re right. If you only sort by price, you might get unstable results or skip items. To solve this, you need a second, unique column to act as a <strong>tie-breaker</strong>—the id is perfect for this.</p><p>Your <em>real</em> cursor isn’t just the price; it&#39;s the (price, id) combination.</p><p>Let’s say the last item on our page was (price: 39.99, id: 10045). To get the next page, our query becomes slightly more complex, but infinitely more powerful. We use standard SQL row-value comparison:</p><pre>SELECT * FROM products<br>WHERE (price, id) &lt; (39.99, 10045)<br>ORDER BY price DESC, id DESC<br>LIMIT 50;</pre><blockquote><strong><em>How this works:</em></strong><em> The </em><em>(price, id) &lt; (39.99, 10045) tuple comparison checks for:</em></blockquote><ul><li>Rows where price &lt; 39.99</li><li><em>OR</em> rows where price = 39.99 AND id &lt; 10045</li></ul><blockquote><em>This guarantees a perfectly stable, gapless, and blazing-fast pagination, even if thousands of products share the same price. (Note: Make sure you have a composite index on </em><em>(price, id) for maximum speed!)</em></blockquote><h3>Real-World Example: Your Infinite Scroll Feed</h3><p>Let’s apply this to a blog’s infinite scroll feed. You want to sort by published_at (newest first), but two posts might have the exact same timestamp. The id will be our tie-breaker.</p><p>The last post a user sees has:</p><ul><li>published_at: &#39;2025-01-12 14:23:00&#39;</li><li>id: 558</li></ul><p>To get the next 10 posts, the query is simple:</p><pre>SELECT * FROM posts<br>WHERE (published_at, id) &lt; (&#39;2025-01-12 14:23:00&#39;, 558)<br>ORDER BY published_at DESC, id DESC<br>LIMIT 10;</pre><p>This lets users scroll for <em>hours</em>, and your database won’t even break a sweat.</p><h3>When OFFSET Isn’t (Completely) Evil</h3><p>OFFSET isn’t useless, it’s just misunderstood.</p><p>It’s perfectly fine for <strong>low-traffic admin dashboards</strong> or analytics pages where a user might <em>need</em> to jump directly to “Page 7” of 10. The load is low, and the “jump to page” feature is a hard requirement.</p><p>But for any <strong>public-facing, high-traffic feed</strong> — like an API, an infinite scroll, or a “load more” button — it’s a liability.</p><h3>Final Thought</h3><p>Good pagination is invisible , users shouldn’t notice it.</p><p><strong>But your database will.</strong></p><p>Next time your API starts gasping for air under load, don’t just reach for a bigger CPU. Reach for smarter SQL.</p><p>Keyset pagination isn’t a new trick; it’s the grown-up version of pagination.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4e09acab1a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>