<?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 Anu madhav on Medium]]></title>
        <description><![CDATA[Stories by Anu madhav on Medium]]></description>
        <link>https://medium.com/@anumadhavan7?source=rss-d4d1d05d03b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EfLwup7cqR-_98E44WUABg.png</url>
            <title>Stories by Anu madhav on Medium</title>
            <link>https://medium.com/@anumadhavan7?source=rss-d4d1d05d03b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:34:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anumadhavan7/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[Step-by-Step Beginner-Friendly Guide to Building an In-Memory Cache in Go]]></title>
            <link>https://medium.com/@anumadhavan7/step-by-step-beginner-friendly-guide-to-building-an-in-memory-cache-in-go-1ff45f915e7a?source=rss-d4d1d05d03b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ff45f915e7a</guid>
            <category><![CDATA[inmemory-cache]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Anu madhav]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 12:04:56 GMT</pubDate>
            <atom:updated>2025-10-04T12:04:56.073Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we’ll build a simple yet practical in-memory cache from scratch in Go. Along the way, you’ll learn about Go structs, concurrency control with mutexes, and how to add TTL (time-to-live) expiration for cache entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laUPx7CjLx9f8_x4yKP9oQ.png" /></figure><h4>1. Creating a Basic Cache Struct</h4><p>Let’s start by creating a struct named Cache that will hold our cached data. We&#39;ll store key-value pairs using a Go map:</p><pre>// Cache stores cached data in a map<br>// Keys and values are strings for simplicity<br><br>type Cache struct {<br>    data map[string]string<br>}</pre><blockquote>This struct provides the skeleton to hold our cached values.</blockquote><h4>2. Initializing the Cache</h4><pre>func NewCache() *Cache {<br>    return &amp;Cache{<br>        data: make(map[string]string),<br>    }<br>}</pre><blockquote>Using NewCache(), we get a new cache ready to store data.</blockquote><h4>3. Implementing Set and Get Methods</h4><p>To store and retrieve values, we implement two simple methods:</p><pre>func (c *Cache) Set(key, value string) {<br>    c.data[key] = value<br>}<br><br>func (c *Cache) Get(key string) (string, bool) {<br>    val, ok := c.data[key]<br>    return val, ok<br>}</pre><blockquote>Set saves a value for a given key.</blockquote><blockquote>Get retrieves the value and returns a boolean indicating if it was found.</blockquote><h4>4. Making the Cache Safe for Concurrent Access</h4><p>Go programs often run concurrent goroutines. Without safeguards, multiple goroutines accessing data can cause <em>race conditions</em> and crashes.</p><p>To avoid this, we’ll add a mutex to safely lock the cache while reading or writing:</p><pre>import &quot;sync&quot;<br><br>type Cache struct {<br>    data  map[string]string<br>    mutex sync.RWMutex<br>}<br><br>func (c *Cache) Set(key, value string) {<br>    c.mutex.Lock()           // Lock for writing<br>    defer c.mutex.Unlock()<br><br>    c.data[key] = value<br>}<br><br>func (c *Cache) Get(key string) (string, bool) {<br>    c.mutex.RLock()          // Lock for reading<br>    defer c.mutex.RUnlock()<br><br>    val, ok := c.data[key]<br>    return val, ok<br>}</pre><p>Now, the cache supports safe concurrent access!</p><h4>5. Adding TTL Expiration</h4><p>A useful feature in caches is a TTL — a time after which cached data expires automatically.</p><p><strong>We’ll do this by:</strong></p><ul><li>Storing expiration timestamps with each cached item.</li><li>Checking expiration when accessing items.</li><li>Cleaning up expired entries periodically.</li></ul><h4>Define CacheItem with expiration:</h4><pre>type CacheItem struct {<br>    value      string<br>    expiration int64  // Unix nano timestamp<br>}<br><br>// Update Cache to store CacheItems<br><br>type Cache struct {<br>    data  map[string]CacheItem<br>    mutex sync.RWMutex<br>}</pre><h4>Update Set method to accept TTL:</h4><pre>import &quot;time&quot;<br><br>func (c *Cache) Set(key, value string, ttl time.Duration) {<br>    c.mutex.Lock()<br>    defer c.mutex.Unlock()<br><br>    c.data[key] = CacheItem{<br>        value:      value,<br>        expiration: time.Now().Add(ttl).UnixNano(),<br>    }<br>}</pre><h4>Update Get to check expiration:</h4><pre>func (c *Cache) Get(key string) (string, bool) {<br>    c.mutex.RLock()<br>    item, ok := c.data[key]<br>    c.mutex.RUnlock()<br><br>    if !ok {<br>        return &quot;&quot;, false<br>    }<br><br>    if time.Now().UnixNano() &gt; item.expiration {<br>        // Item expired, remove it<br>        c.mutex.Lock()<br>        delete(c.data, key)<br>        c.mutex.Unlock()<br>        return &quot;&quot;, false<br>    }<br><br>    return item.value, true<br>}</pre><h4>Optional: Background Cleanup</h4><p>Run a goroutine that periodically removes expired entries:</p><pre>func (c *Cache) CleanUp() {<br>    ticker := time.NewTicker(5 * time.Second)<br>    defer ticker.Stop()<br><br>    for range ticker.C {<br>        c.mutex.Lock()<br>        now := time.Now().UnixNano()<br><br>        for key, item := range c.data {<br>            if now &gt; item.expiration {<br>                delete(c.data, key)<br>            }<br>        }<br><br>        c.mutex.Unlock()<br>    }<br>}</pre><p><strong>Start this in </strong><strong>NewCache:</strong></p><pre>func NewCache() *Cache {<br>    c := &amp;Cache{<br>        data: make(map[string]CacheItem),<br>    }<br>    go c.CleanUp()<br>    return c<br>}</pre><h3>Summary</h3><p><strong>You have built:</strong></p><ul><li>A basic struct to hold cache data.</li><li>Set &amp; Get methods for memory storage and retrieval.</li><li>Added mutex locking for thread safety.</li><li>Implemented TTL-based expiration with cleanup.</li></ul><p>This simple in-memory cache is a solid foundation to build on for Go applications.</p><p>Try it yourself, experiment with TTL values, add methods like Delete or Clear, and explore more advanced cache techniques!</p><p>Happy coding! 🚀</p><h3>About the Author</h3><p>Anu Madhav is a passionate software developer based in Kerala, India, specializing in backend development with Go. With a keen interest in building efficient, scalable systems and exploring practical programming patterns, Anu enjoys sharing knowledge and helping others grow in their coding journey. When not coding, Anu is an avid learner of new technologies and an enthusiast of option trading and digital marketing. Connect with Anu on <a href="https://www.linkedin.com/in/anu-madhav-7158621a6">LinkedIn</a> to follow along with more technical insights and updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ff45f915e7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Microservices: A Complete Guide to HMAC-Based Service-to-Service Communication in Go]]></title>
            <link>https://medium.com/@anumadhavan7/securing-microservices-a-complete-guide-to-hmac-based-service-to-service-communication-in-go-38e410753dda?source=rss-d4d1d05d03b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/38e410753dda</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[hmac]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Anu madhav]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 13:17:51 GMT</pubDate>
            <atom:updated>2025-09-29T13:17:51.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3yBjSEsAwXF-gIVJsovEw.png" /></figure><p>In the world of distributed systems and microservices, ensuring secure communication between services is paramount. While HTTPS provides transport-layer security, we often need additional application-layer authentication to verify that requests are coming from trusted services. This is where HMAC (Hash-based Message Authentication Code) shines as a powerful solution for service-to-service authentication.</p><h3>Understanding the Foundation: What is MAC?</h3><p><strong>Message Authentication Code (MAC)</strong> is a cryptographic technique that provides both data integrity and authenticity. Think of it as a digital signature that proves two things:</p><ul><li>The message hasn’t been tampered with (integrity)</li><li>The message comes from someone who knows the secret key (authenticity)</li></ul><p><strong>MAC</strong> was introduced to solve a critical problem in distributed systems: how do you verify that a message is authentic and hasn’t been modified during transmission? Traditional methods like simple checksums or hashes can detect accidental corruption but not intentional tampering.</p><h4>The Problem with Simple Hashing</h4><p><strong><em>Consider this scenario:</em></strong></p><pre>// Vulnerable approach - simple hash<br>message := &quot;transfer $100 to account 12345&quot;<br>hash := sha256.Sum256([]byte(message))<br>// An attacker can easily change the message and recalculate the hash</pre><blockquote>An attacker could intercept the message, change it to “transfer $10000 to account 67890”, recalculate the hash, and forward the modified request. The receiving service would have no way to detect this tampering.</blockquote><h4>How MAC Solves This</h4><p><strong><em>MAC introduces a shared secret key that both sender and receiver know, but attackers don’t:</em></strong></p><pre>// Secure approach with MAC<br>message := &quot;transfer $100 to account 12345&quot;<br>secretKey := &quot;shared-secret-between-services&quot;<br>mac := calculateMAC(message, secretKey)<br>// Attacker can&#39;t forge this without knowing the secret key</pre><h3>MAC vs HMAC: Understanding the Difference</h3><p>While MAC is the general concept, HMAC is a specific implementation of MAC using hash functions. Here’s the key difference:</p><h4>MAC (General Concept)</h4><ul><li>Definition: Any algorithm that produces an authentication code using a secret key</li><li>Examples: HMAC, CMAC, GMAC, Poly1305</li><li>Flexibility: Can be based on hash functions, block ciphers, or other primitives</li></ul><h4>HMAC (Specific Implementation)</h4><ul><li>Definition: MAC specifically using hash functions (SHA-256, SHA-512, etc.)</li><li>Formula: HMAC(K, m) = H((K ⊕ opad) || H((K ⊕ ipad) || m))</li><li>Advantages: Proven security, widely supported, efficient</li></ul><p><strong>HMAC is the most popular MAC variant because:</strong></p><ul><li>It’s standardized (RFC 2104)</li><li>It’s cryptographically secure</li><li>It’s available in most programming languages</li><li>It performs well</li></ul><h3>Benefits for Service-to-Service Communication</h3><h4>Authentication Without Credentials Exchange</h4><p><strong><em>Unlike token-based systems, HMAC doesn’t require real-time credential validation:</em></strong></p><pre>// No need for database lookups or external auth services<br>func authenticateRequest(r *http.Request) bool {<br>    receivedSignature := r.Header.Get(&quot;X-Signature&quot;)<br>    expectedSignature := generateHMAC(requestBody, sharedSecret)<br>    return hmac.Equal(receivedSignature, expectedSignature)<br>}</pre><h4>Stateless Security</h4><p><em>Each request is independently verifiable without maintaining session state:</em></p><pre>// Each request carries its own authentication proof<br>type AuthenticatedRequest struct {<br> Payload []byte<br> Timestamp int64<br> Signature string<br>}</pre><h4>Protection Against Replay Attacks</h4><p><strong><em>By including timestamps, you can prevent replay attacks:</em></strong></p><pre>func validateTimestamp(timestamp int64) bool {<br>    now := time.Now().Unix()<br>    return abs(now - timestamp) &lt;= 300 // 5 minutes tolerance<br>}</pre><h4>Performance Benefits</h4><ul><li>No network calls to authentication services</li><li>Minimal computational overhead</li><li>Scales horizontally without bottlenecks</li></ul><h4>Complete Go Implementation</h4><p><strong><em>Here’s a production-ready HMAC service implementation:</em></strong></p><pre>package hmac<br><br>import (<br>    &quot;crypto/hmac&quot;<br>    &quot;crypto/sha256&quot;<br>    &quot;encoding/hex&quot;<br>    &quot;fmt&quot;<br>    &quot;net/http&quot;<br>    &quot;strconv&quot;<br>    &quot;time&quot;<br>)<br><br>type HMACService struct {<br>    secretKey []byte<br>    tolerance time.Duration<br>}<br><br>func NewHMACService(secret string, tolerance time.Duration) *HMACService {<br>    return &amp;HMACService{<br>        secretKey: []byte(secret),<br>        tolerance: tolerance,<br>    }<br>}<br><br>// Generate HMAC signature for outgoing requests<br>func (h *HMACService) SignRequest(payload []byte, timestamp int64) string {<br>    message := fmt.Sprintf(&quot;%s.%d&quot;, string(payload), timestamp)<br>    mac := hmac.New(sha256.New, h.secretKey)<br>    mac.Write([]byte(message))<br>    return hex.EncodeToString(mac.Sum(nil))<br>}<br><br>// Middleware for incoming request validation<br>func (h *HMACService) AuthenticateMiddleware(next http.HandlerFunc) http.HandlerFunc {<br>    return func(w http.ResponseWriter, r *http.Request) {<br>        signature := r.Header.Get(&quot;X-Signature&quot;)<br>        timestampStr := r.Header.Get(&quot;X-Timestamp&quot;)<br>        <br>        if signature == &quot;&quot; || timestampStr == &quot;&quot; {<br>            http.Error(w, &quot;Missing authentication headers&quot;, http.StatusUnauthorized)<br>            return<br>        }<br>        <br>        timestamp, err := strconv.ParseInt(timestampStr, 10, 64)<br>        if err != nil {<br>            http.Error(w, &quot;Invalid timestamp&quot;, http.StatusBadRequest)<br>            return<br>        }<br>        <br>        // Read request body<br>        body, err := io.ReadAll(r.Body)<br>        if err != nil {<br>            http.Error(w, &quot;Failed to read request body&quot;, http.StatusBadRequest)<br>            return<br>        }<br>        r.Body = io.NopCloser(bytes.NewReader(body))<br>        <br>        if !h.validateRequest(body, timestamp, signature) {<br>            http.Error(w, &quot;Invalid signature&quot;, http.StatusUnauthorized)<br>            return<br>        }<br>        <br>        next(w, r)<br>    }<br>}<br><br>// Validate incoming request<br>func (h *HMACService) validateRequest(payload []byte, timestamp int64, receivedSignature string) bool {<br>    // Check timestamp to prevent replay attacks<br>    if !h.isValidTimestamp(timestamp) {<br>        return false<br>    }<br>    <br>    expectedSignature := h.SignRequest(payload, timestamp)<br>    expectedBytes, _ := hex.DecodeString(expectedSignature)<br>    receivedBytes, _ := hex.DecodeString(receivedSignature)<br>    <br>    return hmac.Equal(expectedBytes, receivedBytes)<br>}<br><br>func (h *HMACService) isValidTimestamp(timestamp int64) bool {<br>    now := time.Now().Unix()<br>    diff := time.Duration(abs(now-timestamp)) * time.Second<br>    return diff &lt;= h.tolerance<br>}<br><br>func abs(x int64) int64 {<br>    if x &lt; 0 {<br>        return -x<br>    }<br>    return x<br>}</pre><h4>Client Implementation</h4><pre>type AuthenticatedClient struct {<br>    httpClient  *http.Client<br>    hmacService *HMACService<br>    baseURL     string<br>}<br><br>func (c *AuthenticatedClient) Post(endpoint string, payload []byte) (*http.Response, error) {<br>    timestamp := time.Now().Unix()<br>    signature := c.hmacService.SignRequest(payload, timestamp)<br>    <br>    req, err := http.NewRequest(&quot;POST&quot;, c.baseURL+endpoint, bytes.NewReader(payload))<br>    if err != nil {<br>        return nil, err<br>    }<br>    <br>    req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    req.Header.Set(&quot;X-Signature&quot;, signature)<br>    req.Header.Set(&quot;X-Timestamp&quot;, strconv.FormatInt(timestamp, 10))<br>    <br>    return c.httpClient.Do(req)<br>}</pre><h4>Usage Example</h4><pre>func main() {<br>    // Server setup<br>    hmacService := NewHMACService(&quot;your-shared-secret&quot;, 5*time.Minute)<br>    <br>    http.HandleFunc(&quot;/api/transfer&quot;, hmacService.AuthenticateMiddleware(handleTransfer))<br>    http.ListenAndServe(&quot;:8080&quot;, nil)<br>}<br><br>func handleTransfer(w http.ResponseWriter, r *http.Request) {<br>    // Request is already authenticated by middleware<br>    // Process the transfer safely<br>    fmt.Fprintf(w, &quot;Transfer processed successfully&quot;)<br>}</pre><h3>Real-World Implementation Tips</h3><h4>Service Discovery Integration</h4><pre>type ServiceRegistry struct {<br>    services map[string]ServiceConfig<br>}<br><br>type ServiceConfig struct {<br>    URL       string<br>    SecretKey string<br>}<br><br>func (sr *ServiceRegistry) GetAuthenticatedClient(serviceName string) *AuthenticatedClient {<br>    config := sr.services[serviceName]<br>    hmacService := NewHMACService(config.SecretKey, 5*time.Minute)<br>    return &amp;AuthenticatedClient{<br>        httpClient:  &amp;http.Client{Timeout: 30 * time.Second},<br>        hmacService: hmacService,<br>        baseURL:     config.URL,<br>    }<br>}</pre><h4>Health Check Endpoints</h4><pre>// Exclude health checks from HMAC authentication<br>func (h *HMACService) AuthenticateMiddleware(next http.HandlerFunc) http.HandlerFunc {<br>    return func(w http.ResponseWriter, r *http.Request) {<br>        // Skip authentication for health checks<br>        if r.URL.Path == &quot;/health&quot; {<br>            next(w, r)<br>            return<br>        }<br>        <br>        // Apply HMAC authentication for other endpoints<br>        // ... rest of authentication logic<br>    }<br>}</pre><h4>Conclusion</h4><p>HMAC-based service-to-service communication provides a robust, stateless, and performant solution for authenticating microservices. By implementing HMAC correctly, you can:</p><ul><li>Eliminate the need for complex token management systems</li><li>Achieve better performance through stateless authentication</li><li>Protect against tampering and replay attacks</li><li>Scale your authentication horizontally without bottlenecks</li></ul><p>The Go implementation shown above provides a production-ready foundation that you can adapt to your specific microservices architecture. Remember to follow security best practices around key management, implement proper logging, and consider key rotation strategies for long-term security.</p><p>Start securing your service-to-service communication today with HMAC — your distributed system will thank you for the added security and performance benefits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38e410753dda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your API Will Crash Without Rate Limiting (And How to Build One That Actually Works)]]></title>
            <link>https://medium.com/@anumadhavan7/why-your-api-will-crash-without-rate-limiting-and-how-to-build-one-that-actually-works-0329568328e4?source=rss-d4d1d05d03b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0329568328e4</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Anu madhav]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 05:29:51 GMT</pubDate>
            <atom:updated>2025-09-28T05:29:51.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dpbx4nvgxzMi4wmkvxS-Q.png" /><figcaption>You wake up to 500 error notifications. Your API is down. Your users are angry. And the culprit? One rogue client hammering your servers with thousands of requests per second.</figcaption></figure><p>Sound familiar? You’re not alone.</p><p>Rate limiting isn’t just a “nice-to-have” feature — it’s the invisible shield protecting your application from chaos. Yet most developers either skip it entirely or implement it poorly, leaving their systems vulnerable to traffic spikes, malicious attacks, and angry customers.</p><p>Today, we’ll build a bulletproof rate limiter from scratch using the token bucket algorithm. By the end, you’ll have production-ready code and understand exactly why companies like Twitter, GitHub, and Stripe rely on this approach.</p><h3>The Hidden Cost of No Rate Limiting</h3><h4>Your Server Dies a Slow Death</h4><p>Without rate limiting, even legitimate traffic can kill your application. That viral blog post mentioning your API? Great for business, terrible for your servers when thousands hit your endpoints simultaneously.</p><h4>Your Wall Takes a Hit</h4><p>Cloud bills skyrocket when traffic spikes overwhelm your auto-scaling. One client can literally cost you hundreds of dollars in a single hour.</p><h4>Hackers Love Unprotected APIs</h4><p>Brute force attacks, credential stuffing, data scraping — all become trivially easy when there’s no rate limiting standing guard.</p><h4>The “Noisy Neighbor” Problem</h4><p>In multi-tenant systems, one heavy user can degrade performance for everyone else. Fair resource allocation becomes impossible without proper controls.</p><h3>The Rate Limiting Algorithm Showdown</h3><p><em>Not all rate limiting algorithms are created equal. Here’s what you need to know:</em></p><h4>Fixed Window Counter</h4><p>✅ Pros: Simple to implement, low memory usage<br>❌ Cons: Traffic bursts at window boundaries can overwhelm servers</p><h4>Sliding Window Log</h4><p>✅ Pros: Precise control, no boundary issues<br>❌ Cons: Memory hungry, complex cleanup required</p><h4>Token Bucket</h4><p>✅ Pros: Handles bursts gracefully, memory efficient, intuitive<br>❌ Cons: Slightly more complex than fixed window</p><h4>Leaky Bucket</h4><p>✅ Pros: Smooth traffic flow, predictable resource usage<br>❌ Cons: Can increase latency, less flexible</p><blockquote>Why Token Bucket Wins: It’s the goldilocks of rate limiting — not too simple, not too complex, just right for most real-world scenarios.</blockquote><h3>Token Bucket: The Algorithm That Powers the Internet</h3><p><em>Imagine a bucket that drips tokens at a steady rate. Each request needs a token. No tokens? No service.</em></p><p>Here’s the beautiful simplicity:</p><ul><li>Bucket holds tokens (your burst capacity)</li><li>Tokens refill constantly (your sustained rate)</li><li>Requests consume tokens (your protection mechanism)</li><li>Empty bucket blocks requests (your safety net)</li></ul><p>This allows legitimate bursts while preventing sustained abuse — exactly what you want in production</p><h4>The Core Algorithm Components</h4><p><em>Every token bucket implementation needs these fundamental elements :</em></p><pre>TokenBucket:<br> - currentTokens: number of tokens available right now<br> - maxCapacity: maximum tokens the bucket can hold<br> - refillRate: tokens added per unit time<br> - lastRefillTime: when we last calculated token refill</pre><h4>The Mathematical Foundation</h4><p><em>The math behind token bucket is elegantly simple :</em></p><pre>tokensToAdd = (currentTime - lastRefillTime) × refillRate<br>currentTokens = min(maxCapacity, currentTokens + tokensToAdd)</pre><p><strong>When a request arrives:</strong></p><pre>If currentTokens &gt; 0 → Allow request and currentTokens -= 1<br>If currentTokens = 0 → Reject request</pre><h3>Building Our Token Bucket: Step by Step</h3><p><em>Let’s build this algorithm in a language-agnostic way that you can implement in any programming language.</em></p><h4>Step 1: Initialize the Bucket</h4><pre>function createTokenBucket(capacity, refillRate):<br>    return {<br>        tokens: capacity,           // Start with full bucket<br>        maxTokens: capacity,        // Maximum burst size<br>        refillRate: refillRate,     // Tokens per second<br>        lastUpdate: currentTime()   // Track last refill time<br>    }</pre><blockquote>Key insight: Starting with a full bucket allows immediate burst traffic for new users.</blockquote><h4>Step 2: Implement Token Refilling</h4><pre>function refillTokens(bucket):<br>    now = currentTime()<br>    timePassed = now - bucket.lastUpdate<br>    tokensToAdd = timePassed * bucket.refillRate<br>    <br>    bucket.tokens = min(bucket.maxTokens, bucket.tokens + tokensToAdd)<br>    bucket.lastUpdate = now</pre><blockquote>Why time-based refilling works: Instead of running background timers, we calculate tokens on-demand, making the system more efficient and accurate.</blockquote><h4>Step 3: The Request Decision Engine</h4><pre>function allowRequest(bucket):<br>    refillTokens(bucket)  // Always refill first<br>    <br>    if bucket.tokens &gt;= 1:<br>        bucket.tokens = bucket.tokens - 1<br>        return true  // Request approved<br>    else:<br>        return false  // Request denied</pre><blockquote>Thread safety note: In concurrent environments, ensure atomic operations when checking and decrementing token counts</blockquote><h4>Step 4: Multi-User Rate Limiting</h4><pre>RateLimiterManager:<br>    - buckets: map[userIdentifier -&gt; TokenBucket]<br>    <br>function getRateLimiter(userID):<br>    if userID not in buckets:<br>        buckets[userID] = createTokenBucket(capacity, refillRate)<br>    return buckets[userID]<br><br>function processRequest(userID):<br>    limiter = getRateLimiter(userID)<br>    return allowRequest(limiter)</pre><blockquote>Scaling consideration: Each user gets their own bucket, ensuring fair resource allocation.</blockquote><h3>Configuration Patterns That Work</h3><h4>Conservative Settings (Resource-Intensive Operations)</h4><pre>capacity = 2 tokens<br>refillRate = 0.017 tokens/second  // 1 token per minute</pre><h4>Moderate Settings (Standard API Endpoints)</h4><pre>capacity = 10 tokens  <br>refillRate = 0.1 tokens/second    // 1 token per 10 seconds</pre><h4>Generous Settings (Lightweight Operations)</h4><pre>capacity = 100 tokens<br>refillRate = 1.0 tokens/second    // 1 token per second</pre><blockquote>Tuning tip: Start conservative and gradually increase based on system capacity and user behavior patterns.</blockquote><h3>Advanced Implementation Considerations</h3><h4>Memory Management</h4><pre>function cleanupInactiveUsers():<br>    cutoffTime = currentTime() - inactivityThreshold<br>    <br>    for each userID in buckets:<br>        if buckets[userID].lastUpdate &lt; cutoffTime:<br>            remove buckets[userID]</pre><h4>Distributed Systems</h4><p><strong>For multi-server deployments:</strong></p><ul><li>Use shared storage (Redis) for token state</li><li>Implement consistent hashing for user-to-server mapping</li><li>Consider eventual consistency trade-offs</li></ul><h4>Request Response Headers</h4><pre>HTTP Response Headers:<br>X-RateLimit-Limit: 100           // Requests per time window  <br>X-RateLimit-Remaining: 42        // Remaining requests<br>X-RateLimit-Reset: 1640995200    // When limit resets</pre><h3>Production-Ready Go Implementation</h3><p><em>Now let’s see this algorithm implemented in Go, ready for production use:</em></p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;net&quot;<br>    &quot;net/http&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)<br><br>// TokenRateLimiter implements the token bucket algorithm<br>type TokenRateLimiter struct {<br>    token          float64<br>    maxToken       float64<br>    refillToken    float64<br>    lastRefillTime time.Time<br>    mutex          sync.Mutex<br>}<br><br>func NewTokenRateLimiter(maxToken float64, refillToken float64) *TokenRateLimiter {<br>    return &amp;TokenRateLimiter{<br>        token:          maxToken,<br>        maxToken:       maxToken,<br>        refillToken:    refillToken,<br>        lastRefillTime: time.Now(),<br>    }<br>}<br><br>func (t *TokenRateLimiter) refill() {<br>    now := time.Now()<br>    duration := now.Sub(t.lastRefillTime).Seconds()<br>    tokensToAdd := duration * t.refillToken<br><br>    t.token += tokensToAdd<br>    if t.token &gt;= t.maxToken {<br>        t.token = t.maxToken<br>    }<br><br>    t.lastRefillTime = now<br>}<br><br>func (t *TokenRateLimiter) Allow() bool {<br>    t.mutex.Lock()<br>    defer t.mutex.Unlock()<br><br>    t.refill()<br><br>    if t.token &gt; 0 {<br>        t.token--<br>        return true<br>    }<br>    return false<br>}<br><br>type IPRateLimiter struct {<br>    limiters map[string]*TokenRateLimiter<br>    mutex    sync.Mutex<br>}<br><br>func NewIPRateLimiter() *IPRateLimiter {<br>    return &amp;IPRateLimiter{<br>        limiters: make(map[string]*TokenRateLimiter),<br>    }<br>}<br><br>func (i *IPRateLimiter) GetLimiter(ip string) *TokenRateLimiter {<br>    i.mutex.Lock()<br>    defer i.mutex.Unlock()<br><br>    limiter, exists := i.limiters[ip]<br>    if !exists {<br>        // Configure: 5 tokens burst, 1 token every 20 seconds<br>        limiter = NewTokenRateLimiter(5, 0.05)<br>        i.limiters[ip] = limiter<br>    }<br>    return limiter<br>}<br><br>func RateMiddleware(limiter *IPRateLimiter, next http.HandlerFunc) http.HandlerFunc {<br>    return func(w http.ResponseWriter, r *http.Request) {<br>        ip, _, err := net.SplitHostPort(r.RemoteAddr)<br>        if err != nil {<br>            fmt.Printf(&quot;Error parsing IP: %v\n&quot;, err)<br>        }<br><br>        if limiter.GetLimiter(ip).Allow() {<br>            next(w, r)<br>        } else {<br>            http.Error(w, &quot;Rate limit exceeded&quot;, http.StatusTooManyRequests)<br>        }<br>    }<br>}<br><br>func HealthCheck(w http.ResponseWriter, r *http.Request) {<br>    w.Write([]byte(&quot;🚀 Request successful! Rate limiter is working.&quot;))<br>}<br><br>func main() {<br>    limiter := NewIPRateLimiter()<br>    mux := http.NewServeMux()<br><br>    mux.HandleFunc(&quot;/&quot;, RateMiddleware(limiter, HealthCheck))<br><br>    fmt.Println(&quot;🔥 Server starting on port 8080&quot;)<br>    fmt.Println(&quot;⚡ Rate limit: 5 requests burst, then 1 every 20 seconds&quot;)<br>    fmt.Println(&quot;🧪 Test it: curl -X GET http://localhost:8080&quot;)<br><br>    if err := http.ListenAndServe(&quot;:8080&quot;, mux); err != nil {<br>        fmt.Printf(&quot;💥 Server failed: %v\n&quot;, err)<br>    }<br>}</pre><h4>Testing Your Rate Limiter</h4><p><em>Want to see it in action? Try this:</em></p><pre># Start your server<br>go run main.go<br><br># Test rapid requests (watch the magic happen)<br>for i in {1..10}; do <br>    curl http://localhost:8080 &amp;&amp; echo &quot; - Request $i&quot;<br>done</pre><p><strong>What you’ll see:</strong></p><ul><li>First 5 requests succeed immediately (burst capacity)</li><li>Subsequent requests get blocked with 429 Too Many Requests</li><li>Wait 20 seconds, try again — you’ll get one more request through</li></ul><h3>The Bottom Line</h3><blockquote>Rate limiting isn’t optional in modern applications — it’s essential infrastructure. The token bucket algorithm gives you the perfect balance of burst handling and sustained protection.</blockquote><p><strong>Your homework:</strong></p><ol><li>Implement this algorithm in your preferred language</li><li>Experiment with different token configurations</li><li>Add distributed storage for production scale</li><li>Implement different limits for different endpoints</li></ol><p>Your future self (and your server bills) will thank you.</p><p><strong>What rate limiting challenges are you facing? Drop a comment and let’s solve them together.</strong></p><p>Building robust backend systems? Follow me for more deep dives into distributed systems, API design, and scalable architectures.</p><p>#programming #systemdesign #ratelimiting #apidevelopment #backendenginering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0329568328e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Great Framework Showdown: Laravel vs Express.js vs Go Chi Router]]></title>
            <link>https://medium.com/@anumadhavan7/the-great-framework-showdown-laravel-vs-express-js-vs-go-chi-router-57016a3ff474?source=rss-d4d1d05d03b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/57016a3ff474</guid>
            <dc:creator><![CDATA[Anu madhav]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 15:10:56 GMT</pubDate>
            <atom:updated>2025-09-26T15:10:56.859Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Performance Testing Journey That Revealed Surprising Truths</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfrCeEpxo5wmDjWP8ctWoA.png" /></figure><p>As a GoLang backend developer with experience in microservices , I’ve always been curious about the real-world performance differences between popular web frameworks. Sure, we’ve all seen the TechEmpower benchmarks, but how do these frameworks actually perform in a controlled, realistic testing environment?</p><p><strong>I decided to find out by conducting a comprehensive load testing comparison between:</strong></p><ul><li>Laravel (PHP) — The beloved full-stack framework</li><li>Express.js (Node.js) — The JavaScript powerhouse</li><li>Go Chi Router (Golang) — The lightweight, composable router</li></ul><p>What started as a simple benchmark turned into a fascinating journey that taught me valuable lessons about performance testing, artificial bottlenecks, and the surprising capabilities of modern web frameworks.</p><h3>The Setup: Simple APIs, Serious Testing</h3><p>I created identical APIs across all three frameworks with two endpoints:</p><ul><li>/health - Initially with a 2-second delay (more on this later!)</li><li>/check - Simple &quot;hello world&quot; response</li></ul><p><strong>The testing setup used k6 with the following configuration:</strong></p><ul><li>Target: 1000 requests per second</li><li>Duration: 10 seconds</li><li>Max VUs: 50–100</li><li>Scenario: Constant arrival rate</li></ul><pre>export let options = {<br>  scenarios: {<br>    high_rps_test: {<br>      executor: &#39;constant-arrival-rate&#39;,<br>      rate: 1000,<br>      timeUnit: &#39;1s&#39;,<br>      duration: &#39;10s&#39;,<br>      preAllocatedVUs: 50,<br>      maxVUs: 100,<br>    },<br>  },<br>};</pre><h3>Round 1: The Confusing Results</h3><h4>Laravel’s Struggle</h4><blockquote>My first Laravel test was… concerning:</blockquote><ul><li>Throughput: 0.47 RPS</li><li>Response Time: 20.29 seconds average</li><li>Dropped Iterations: 99% of requests failed</li><li>Error Rate: 0% (but only 19 requests completed!)</li></ul><h4>Express.js Shows Promise</h4><blockquote>Express.js performed significantly better:</blockquote><ul><li>Throughput: 98.47 RPS</li><li>Response Time: 1 second average</li><li>Dropped Iterations: 95%</li><li>Error Rate: 0%</li></ul><h4>Go Chi Router — Identical to Express?</h4><blockquote>Here’s where things got weird. Go Chi router performed… exactly like Express.js:</blockquote><ul><li>Throughput: 98.47 RPS</li><li>Response Time: 1 second average</li><li>Dropped Iterations: 95%</li><li>Error Rate: 0%</li></ul><p>Something was clearly wrong. Go should significantly outperform Node.js, especially in a simple HTTP response scenario.</p><h3>The Plot Twist: Artificial Bottlenecks</h3><p>After staring at the results in disbelief, I examined my code more carefully. That’s when I spotted the smoking gun:</p><p><strong>Go Implementation:</strong></p><pre>func HealthCheck(w http.ResponseWriter, r *http.Request) {<br>    time.Sleep(2 * time.Second)  // 🚨 The culprit!<br>    w.Write([]byte(&quot;welcome&quot;))<br>}</pre><p><strong>Express.js Implementation:</strong></p><pre>app.get(&quot;/health&quot;, (req, res) =&gt; {<br>  setTimeout(() =&gt; {<br>    res.send(&quot;welcome&quot;);<br>  }, 2000);  // 🚨 Same bottleneck!<br>});</pre><blockquote><strong>I had accidentally introduced identical 2-second delays in both frameworks! This artificial bottleneck was masking the true performance characteristics of each framework.</strong></blockquote><blockquote><strong>Key Insight: When load testing, artificial delays create identical bottlenecks regardless of framework performance. The mathematical maximum with a 2-second delay is 0.5 RPS per virtual user.</strong></blockquote><h3>Round 2: The True Performance Revealed</h3><p>After removing the artificial delays and testing the /check endpoints, the results were dramatically different:</p><h4>Go Chi Router — Unleashed</h4><p><strong><em>Throughput: 1,999.94 RPS ⚡<br>Response Time: 0.244ms average<br>Error Rate: 0.00%<br>Resource Usage: 1 active VU<br>Target Achievement: 199.9%</em></strong></p><h4>Express.js — Surprisingly Competitive</h4><p><strong><em>Throughput: 2,000.08 RPS ⚡<br>Response Time: 0.225ms average <br>Error Rate: 0.00%<br>Resource Usage: 1 active VU<br>Target Achievement: 200.0%</em></strong></p><h4>Laravel — The Reality Check</h4><p><strong><em>Throughput: 220.85 RPS<br>Response Time: 442.58ms average<br>Error Rate: 0.00%<br>Resource Usage: 100 VUs<br>Dropped Iterations: 86.2%</em></strong></p><h4>The Surprising Revelation</h4><p>Go and Express.js performed virtually identically! This was unexpected but makes sense when you consider:</p><h4>Why Express.js Matched Go Performance</h4><ol><li>Ultra-Simple Workload: Just returning “hello world” doesn’t stress language differences</li><li>V8 Engine Optimization: Modern JavaScript engines are incredibly fast for simple operations</li><li>No I/O Operations: Eliminates Go’s typical concurrency advantages</li><li>System Bottlenecks: Both frameworks hitting identical resource limits</li></ol><h4>Industry Context</h4><p>In TechEmpower benchmarks:</p><ul><li>Go frameworks: 100,000–300,000+ RPS</li><li>Express.js: ~78,000 RPS</li><li>Laravel: ~16,800 RPS</li></ul><p>Our results show similar ratios but at lower absolute numbers, indicating system-level constraints rather than framework limitations.</p><h4>Performance Analysis: The Final Verdict</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vy9s54Mva4HzAWRwvKrnpQ.png" /></figure><h4>Key Insights</h4><blockquote>Express.js vs Laravel: 9x throughput advantage, 1,967x latency advantage</blockquote><blockquote>Go vs Laravel: 9x throughput advantage, 1,807x latency advantage</blockquote><blockquote>Go vs Express.js: Virtually identical for simple workloads</blockquote><h3>When Each Framework Shines</h3><h4>Choose Go Chi When:</h4><ul><li>High-concurrency APIs: 10,000+ simultaneous connections</li><li>Microservices: Service-to-service communication</li><li>CPU-intensive processing: Mathematical calculations, data transformations</li><li>Resource constraints: Lower memory footprint requirements</li></ul><h4>Choose Express.js When:</h4><ul><li>Rapid development: Quick prototyping and MVPs</li><li>JSON APIs: Lightweight REST services</li><li>Real-time applications: WebSocket and event-driven apps</li><li>JavaScript ecosystem: Team expertise and tooling</li></ul><h4>Choose Laravel When:</h4><ul><li>Full-stack applications: Complete web applications with UI</li><li>Complex business logic: Rapid development of business rules</li><li>Team familiarity: PHP-experienced development teams</li><li>Moderate performance needs: &lt;1000 RPS requirements</li></ul><h3>The Lessons Learned</h3><h4>1. Artificial Delays Mask True Performance</h4><p>Always ensure your test scenarios reflect real-world usage. Artificial delays create identical bottlenecks across all frameworks.</p><h4>2. Simple Workloads Minimize Framework Differences</h4><p>For basic HTTP responses, modern frameworks perform surprisingly similarly. Performance gaps emerge in complex, I/O-heavy scenarios.</p><h4>3. System Bottlenecks Affect All Frameworks Equally</h4><p>File descriptor limits, connection pools, and resource constraints impact all frameworks identically.</p><h4>4. Context Matters More Than Raw Performance</h4><p>Framework choice should consider team expertise, ecosystem, development speed, and maintenance requirements alongside performance.</p><h3>Optimization Recommendations</h3><h4>Laravel Performance Tuning:</h4><ul><li>Enable OPcache (2–3x improvement)</li><li>Implement Redis caching</li><li>Optimize database queries</li><li>Use route caching</li></ul><h4>Express.js Optimization:</h4><ul><li>Set NODE_ENV=production (3x improvement)</li><li>Enable gzip compression</li><li>Implement clustering</li><li>Use connection pooling</li></ul><h4>Go Chi Optimization:</h4><ul><li>Implement middleware selectively</li><li>Use sync.Pool for object pooling</li><li>Optimize database connections</li><li>Leverage goroutines effectively</li></ul><h4>Conclusion: Performance is Nuanced</h4><p>This testing journey taught me that performance comparisons are more nuanced than simple RPS numbers. While Go and Express.js dominated in our simple response test, the real differentiators emerge in complex, production scenarios with database operations, concurrent processing, and resource management.</p><blockquote>The key takeaway? Choose your framework based on your specific use case, team expertise, and performance requirements. Don’t let benchmarks alone drive your decisions — but do ensure you’re testing realistic scenarios without artificial bottlenecks.</blockquote><p>As a backend developer, this exercise reinforced why I appreciate Go’s design philosophy and performance characteristics, while also gaining newfound respect for the optimizations in modern JavaScript engines.</p><p><em>What frameworks have you load tested? Share your surprising discoveries in the comments below! And if you found this comparison valuable, follow me for more backend development insights and performance deep-dives.</em></p><p>Tags: #Performance #LoadTesting #Golang #Nodejs #Laravel #WebDevelopment #API #Backend</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57016a3ff474" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>