<?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 Abhisikta on Medium]]></title>
        <description><![CDATA[Stories by Abhisikta on Medium]]></description>
        <link>https://medium.com/@acabhisikta?source=rss-82187ccb8f58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sNvET-XW0cA6ihHdhl-7XA.jpeg</url>
            <title>Stories by Abhisikta on Medium</title>
            <link>https://medium.com/@acabhisikta?source=rss-82187ccb8f58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:56:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@acabhisikta/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[Designing for Failure : Circuit Breakers, Retries, Timeouts and Bulkheads in Microservices]]></title>
            <link>https://medium.com/@acabhisikta/designing-for-failure-circuit-breakers-retries-timeouts-and-bulkheads-in-microservices-a2861b323c5f?source=rss-82187ccb8f58------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2861b323c5f</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Abhisikta]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 12:43:40 GMT</pubDate>
            <atom:updated>2026-07-12T12:43:40.738Z</atom:updated>
            <content:encoded><![CDATA[<p>Because in distributed systems, failure isn’t and edge case — it’s a design requirement</p><p>Here’s a gurantee : in a distributes system, things will fail. Services will go down. Networks partition. Databases will slow under load. Third-party APIs return 503s at the worst possible moment.</p><p>The question isn’t whether failure will happen. We should just assume it will. The question is whether your system was designed to handle it gracefully — or whether one slow downstream service can take down your entire platform.</p><p>This article covers 4 foundational resilience patterns : timeouts, retries, circuit breakers, and bulkheads. Each one solves a specific failure mode. Together, they form a defensive architecture that fails safely instead of catastrophically.</p><h3>Why Distributed Systems Fail Differently</h3><p>In a monolith, a method call either succeeds or throws an exception. You handle the exception and move on. The call is in-process, in-memory, and takes microseconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONc8tfb2xrOURSWK9TCrBg.jpeg" /></figure><p>In a microservices architecture, a “method call” is a network request. It crosses process boundaries, traverses networks, and can fail in ways that local calls never can:</p><ul><li>The request never arrives (network partition)</li><li>The request arrives but the response is lost</li><li>The service receives the request but hangs processing it (no response ever comes)</li><li>The service responds slowly — not down, just slow enough to exhaust your thread pool</li><li>The service returns an error intermittently under load</li></ul><p>Each of these failure modes requires a different defensive strategy.</p><h3>Pattern 1: Timeouts</h3><p>The most basic resilience pattern — and the most commonly forgotten.</p><p>If Service A calls Service B with no timeout configured, and Service B hangs indefinitely, Service A’s thread waits indefinitely. Under load, with hundreds of concurrent requests, those threads pile up. Service A runs out of threads. Service A stops responding entirely. Not because Service A has a bug, but because Service B is slow.</p><p><strong>Always set timeouts on every external call. Always.</strong></p><pre>// Without timeout — dangerous<br>response = httpClient.get(&quot;&lt;https://service-b/api/data&gt;&quot;)<br>// With timeout — safe<br>response = httpClient<br>    .withConnectTimeout(500ms)<br>    .withReadTimeout(2000ms)<br>    .get(&quot;&lt;https://service-b/api/data&gt;&quot;)</pre><p><strong>Two timeouts to set:</strong></p><ul><li><strong>Connection timeout:</strong> How long to wait to establish the connection. Should be short — typically 100–500ms. If you can’t connect in 500ms, something is wrong.</li><li><strong>Read timeout:</strong> How long to wait for the response after connecting. Depends on what the service does — a simple lookup might warrant 500ms, a complex computation might warrant 5 seconds.</li></ul><p><strong>How to pick the right timeout value:</strong></p><p>Look at your service’s p99 latency under normal conditions. Set your timeout at 2–3x that value. This gives legitimate slow requests room to complete while cutting off genuinely hung requests before they accumulate.</p><p>If you don’t know your p99 latency, instrument your services first, then set timeouts. Guessing produces timeouts that are either too tight (you start failing legitimate requests) or too loose (you’re not protecting yourself at all).</p><h3>Pattern 2: Retries</h3><p>Some failures are transient. A network hiccup, a brief database overload, a momentary restart of a downstream service. These failures are real but temporary — if you tried again a moment later, the request would succeed.</p><p>Retries handle transient failures automatically.</p><pre>function callServiceWithRetry(request, maxAttempts=3):<br>    for attempt in 1..maxAttempts:<br>        try:<br>            return httpClient.execute(request)<br>        catch TransientException as e:<br>            if attempt == maxAttempts:<br>                throw e<br>            wait(backoffDelay(attempt))<br>function backoffDelay(attempt):<br>    return baseDelay * (2 ^ attempt) + random(0, 100ms)  // exponential backoff with jitter</pre><p><strong>Exponential backoff:</strong> Don’t retry immediately. Wait a little, then a bit more, then more again. Immediate retries under a system already struggling just add more load. Exponential backoff gives the downstream system breathing room to recover.</p><p><strong>Jitter:</strong> Add randomness to the backoff delay. Without jitter, every client retries at the same intervals — you get synchronized retry storms. With jitter, retries are spread out.</p><p><strong>What to retry and what not to:</strong></p><p>Retry on: 500 (internal server error), 502 (bad gateway), 503 (service unavailable), 504 (gateway timeout), network errors, connection timeouts.</p><p>Do NOT retry on: 400 (bad request — retrying won’t fix a malformed payload), 401/403 (auth errors — retrying won’t fix missing credentials), 404 (not found — it won’t appear on retry).</p><p><strong>Idempotency is a prerequisite for retrying non-GET requests.</strong></p><p>Retrying a GET is safe — you’re just reading. Retrying a POST is dangerous if the first request actually succeeded but the response was lost. You might create duplicate records, charge a card twice, or send two emails.</p><p>Before adding retries to write operations, make them idempotent: design the endpoint so that calling it twice with the same data produces the same result as calling it once. Use idempotency keys — a unique identifier sent with the request that the server uses to detect and deduplicate retries.</p><h3>Pattern 3: Circuit Breakers</h3><p>Retries help with transient failures. But what about sustained failures — when a downstream service is genuinely down for minutes or hours?</p><p>Retrying a down service doesn’t help. It just adds load to a system that’s already struggling and wastes resources on requests that have no chance of succeeding.</p><p>The circuit breaker pattern is borrowed from electrical engineering. An electrical circuit breaker trips when it detects dangerous current — it opens the circuit, stopping current flow, protecting the system. It can be reset (closed) once the issue is resolved.</p><p>In software, a circuit breaker wraps calls to a downstream service and monitors for failures. When failures exceed a threshold, the circuit “opens” — subsequent calls fail immediately without even attempting the network request. After a timeout, the circuit enters a “half-open” state, allowing a test request through. If it succeeds, the circuit closes (normal operation resumes). If it fails, the circuit opens again.</p><pre>States:<br>CLOSED  ──(failure threshold exceeded)──►  OPEN<br>OPEN    ──(timeout elapsed)─────────────►  HALF-OPEN<br>HALF-OPEN ──(test request succeeds)──────►  CLOSED<br>HALF-OPEN ──(test request fails)─────────►  OPEN</pre><p><strong>In practice:</strong></p><pre>circuitBreaker = new CircuitBreaker(<br>    failureThreshold = 5,        // open after 5 failures<br>    successThreshold = 2,        // close after 2 successes in half-open<br>    timeout = 30 seconds         // wait 30s before trying half-open<br>)<br><br>function callService(request):<br>    if circuitBreaker.isOpen():<br>        return fallback()        // fail fast, don&#39;t even try<br>try:<br>        response = httpClient.execute(request)<br>        circuitBreaker.recordSuccess()<br>        return response<br>    catch Exception as e:<br>        circuitBreaker.recordFailure()<br>        throw e</pre><p><strong>The fallback is as important as the breaker.</strong></p><p>When the circuit is open, you need to decide what to return. Options:</p><ul><li>Return cached data (stale but better than nothing)</li><li>Return a degraded response (less information, but the page still loads)</li><li>Return a default value</li><li>Return an error to the user with a clear message</li></ul><p>The right fallback depends on the business impact. A recommendation engine being down shouldn’t take down your product page — return an empty recommendations list and move on.</p><p><strong>Resilience4j</strong> is the standard library for circuit breakers in the Java/Spring Boot ecosystem. It implements circuit breakers, retries, rate limiters, and bulkheads with annotation-based configuration. Worth knowing if you’re in the Spring world.</p><h3>Pattern 4: Bulkheads</h3><p>Named after the compartments in a ship’s hull — if one compartment floods, watertight bulkheads prevent the flood from spreading to the rest of the ship.</p><p>In software, a bulkhead isolates failures to a bounded resource pool so that one failing dependency cannot consume resources needed by healthy parts of the system.</p><p><strong>The problem without bulkheads:</strong></p><p>Imagine Service A has a shared thread pool of 100 threads. It calls Service B and Service C. Service B slows down. Requests to Service B start queuing. Threads pile up waiting for Service B. The thread pool fills up — all 100 threads are waiting on Service B. Now requests to Service C also fail, even though Service C is perfectly healthy, because there are no threads available to process them.</p><p><strong>The solution:</strong></p><p>Give each downstream dependency its own isolated thread pool (or semaphore limit).</p><pre>// Separate thread pools per dependency<br>serviceBThreadPool = ThreadPool(maxThreads=30)<br>serviceCThreadPool = ThreadPool(maxThreads=30)<br>sharedPool = ThreadPool(maxThreads=40)<br>function callServiceB(request):<br>    return serviceBThreadPool.execute(() -&gt; httpClient.get(serviceBUrl))<br>function callServiceC(request):<br>    return serviceCThreadPool.execute(() -&gt; httpClient.get(serviceCUrl))</pre><p>Now if Service B’s pool fills up, Service C’s pool is unaffected. The failure is contained.</p><p><strong>Bulkheads are about limiting blast radius.</strong> They don’t prevent failure — they prevent one failure from becoming total failure.</p><h3>How These Patterns Work Together</h3><p>These patterns are not mutually exclusive. In production systems, they layer:</p><pre>Incoming request<br>    │<br>    ▼<br>[Bulkhead] — limits concurrent calls to this dependency<br>    │<br>    ▼<br>[Circuit Breaker] — fails fast if dependency is known to be down<br>    │<br>    ▼<br>[Retry with backoff] — handles transient failures<br>    │<br>    ▼<br>[Timeout] — prevents indefinite waiting<br>    │<br>    ▼<br>Downstream service</pre><p>Each layer handles a different failure mode. Timeout catches hangs. Retry catches transient blips. Circuit breaker catches sustained outages. Bulkhead contains blast radius.</p><p>A real-world configuration might look like:</p><ul><li>Timeout: 2 seconds read, 500ms connect</li><li>Retry: 3 attempts, exponential backoff starting at 200ms, jitter ±100ms, retry on 5xx only</li><li>Circuit breaker: open after 5 failures in 10 seconds, half-open after 30 seconds, close after 2 successes</li><li>Bulkhead: max 20 concurrent calls to this dependency</li></ul><h3>What Most Teams Get Wrong</h3><p><strong>Setting the same timeout for everything.</strong><br> A user profile lookup and a PDF generation endpoint should not have the same timeout. Profile lookup: 500ms. PDF generation: 10 seconds. Blanket timeouts either cut off legitimate slow operations or don’t protect you from fast-failing ones.</p><p><strong>Retrying non-idempotent operations blindly.</strong><br> Adding retries to a payment endpoint without idempotency keys is how you double-charge users. Retries without idempotency are dangerous on write operations.</p><p><strong>No fallback for open circuit breakers.</strong><br> A circuit breaker without a fallback just converts a slow failure into a fast failure. Better, but still a failure. Define what “degraded but functional” means for each dependency and implement it.</p><p><strong>Treating resilience as an afterthought.</strong><br> Resilience patterns are easiest to add when you’re building the integration, not six months later when you’re debugging a production incident at 2am. Design for failure from the start.</p><h3>The One-Line Summary</h3><p>Timeouts prevent hangs. Retries handle transience. Circuit breakers handle sustained outages. Bulkheads contain blast radius. Layer all four — they solve different problems.</p><p><em>If you found this useful, I write about backend architecture, Java, and System Design. Follow for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2861b323c5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis in Production: Caching Patterns, TTL Strategy, and When Not to Cache]]></title>
            <link>https://medium.com/@acabhisikta/redis-in-production-caching-patterns-ttl-strategy-and-when-not-to-cache-4f99349c8435?source=rss-82187ccb8f58------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f99349c8435</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Abhisikta]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 10:08:08 GMT</pubDate>
            <atom:updated>2026-07-03T10:08:08.740Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide for backend developers moving beyond “just add Redis”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3p769eDriTieIUEBgkYFxA.jpeg" /></figure><p>Redis gets added to systems the same way salt gets added to food — a little at first, then more, then someone asks why everything is salty and nobody remembers making that decision.</p><p>Caching is one of the highest-leverage tools in backend engineering. It’s also one of the most commonly misapplied. This article is about using Redis deliberately: the right patterns, how to think about TTL, how to handle invalidation without losing your mind, and when caching is actually the wrong answer.</p><h3>What Redis Actually Is (And Isn’t)</h3><p>Redis is an in-memory data store. It is extremely fast because it reads and writes to RAM, not disk. It supports rich data structures — strings, hashes, lists, sets, sorted sets — not just key-value pairs.</p><p>What it isn’t: a database replacement, a source of truth, or a silver bullet for slow APIs.</p><p>If your application cannot function correctly when Redis is unavailable, you’ve built a dependency, not a cache. A cache should be an optimisation layer. The system should degrade gracefully without it, not collapse.</p><h3>The Core Caching Patterns</h3><h3>1. Cache-Aside (Lazy Loading)</h3><p>The most common pattern. The application manages the cache explicitly.</p><pre>function getUser(userId):<br>    user = cache.get(&quot;user:&quot; + userId)<br>if user is null:<br>        user = database.findById(userId)<br>        cache.set(&quot;user:&quot; + userId, user, TTL=300)<br>    return user</pre><p><strong>Flow:</strong></p><ul><li>Check cache first</li><li>On miss, fetch from database</li><li>Populate cache for future requests</li><li>Return result</li></ul><p><strong>Pros:</strong> Only caches what’s actually requested. No wasted memory on data nobody reads.</p><p><strong>Cons:</strong> The first request after a cache miss (or expiry) always hits the database. Under high traffic, a cache miss on a popular key can cause a <strong>thundering herd</strong> — hundreds of requests hitting the database simultaneously before the cache is repopulated. Solve this with a short distributed lock on cache population.</p><p><strong>Best for:</strong> Read-heavy workloads with unpredictable access patterns. User profiles, product details, configuration data.</p><h3>2. Write-Through</h3><p>Every write goes to the cache and the database simultaneously.</p><pre>function updateUser(userId, data):<br>    database.update(userId, data)<br>    cache.set(&quot;user:&quot; + userId, data, TTL=300)</pre><p><strong>Pros:</strong> Cache is always consistent with the database. No stale reads immediately after a write.</p><p><strong>Cons:</strong> Every write pays the cost of a cache update, even for data that may never be read again. Cache can fill with data that’s written once and never read.</p><p><strong>Best for:</strong> Systems where read consistency after a write is critical. Financial balances, inventory counts.</p><h3>3. Write-Behind (Write-Back)</h3><p>Writes go to the cache first. The cache asynchronously flushes to the database.</p><pre>function updateUser(userId, data):<br>    cache.set(&quot;user:&quot; + userId, data)<br>    queue.publish(&quot;db-write&quot;, {userId, data})  // async flush</pre><p><strong>Pros:</strong> Extremely fast writes. Batching multiple updates before hitting the database reduces write load significantly.</p><p><strong>Cons:</strong> Risk of data loss if Redis goes down before the flush completes. Complex to implement correctly. Harder to debug.</p><p><strong>Best for:</strong> High-write workloads where some data loss is acceptable (analytics counters, view counts, activity logs). Not for anything financial or transactional.</p><h3>4. Read-Through</h3><p>The cache sits in front of the database and handles the miss logic itself, rather than the application managing it.</p><pre>// Application just calls the cache<br>function getUser(userId):<br>    return cache.get(&quot;user:&quot; + userId)<br>    // Cache internally fetches from DB on miss and populates itself</pre><p><strong>Pros:</strong> Simpler application code — the cache handles its own population logic.</p><p><strong>Cons:</strong> Requires a cache layer that supports this pattern natively (not plain Redis — you need a library or abstraction on top). Less control over what gets cached.</p><p><strong>Best for:</strong> When using a caching framework that abstracts the miss logic (Spring Cache with @Cacheable annotation, for example).</p><h3>Thinking About TTL</h3><p>TTL (Time To Live) is how long a cached value is considered valid before it expires. Getting TTL wrong is one of the most common production caching mistakes.</p><p><strong>Too short:</strong> Cache hit rate drops. You’re paying the overhead of caching with none of the benefit. Every request still ends up at the database.</p><p><strong>Too long:</strong> Stale data. Users see outdated information. Worse, you forget the data can be stale and build business logic on top of cached values as if they were fresh.</p><p><strong>The right question isn’t “what TTL should I set?” — it’s “how stale can this data be before it causes a real problem?”</strong></p><p>Some guidance by data type:</p><p>Data Type Staleness Tolerance Suggested TTL User profile (name, email) Minutes to hours 5–30 minutes Product catalogue Minutes 5–15 minutes Inventory count Seconds 10–30 seconds Auth tokens / sessions Until expiry Match token expiry Configuration / feature flags Minutes 1–5 minutes Exchange rates / pricing Seconds 5–30 seconds Static reference data Hours to days 1–24 hours</p><p><strong>Avoid infinite TTL (no expiry) unless you have explicit invalidation logic.</strong> Without expiry, stale data accumulates indefinitely and you rely entirely on manual cache busting — which someone will forget.</p><p><strong>Stagger your TTLs.</strong> If all your cache keys expire at the same time (e.g. everything set at midnight expires at 1am), you get a cache stampede — sudden massive load on your database when the entire cache goes cold simultaneously. Add a small random jitter to TTLs: TTL = baseTTL + random(0, 60 seconds).</p><h3>Cache Invalidation</h3><p>Phil Karlton famously said there are only two hard problems in computer science: cache invalidation and naming things.</p><p>He was right about both.</p><p><strong>Strategy 1: TTL-based expiry (passive invalidation)</strong><br> Let the cache expire naturally. Simple. Works well when staleness is acceptable. No invalidation logic to maintain.</p><p><strong>Strategy 2: Event-driven invalidation (active invalidation)</strong><br> When data changes, explicitly delete or update the cache entry.</p><pre>function updateProduct(productId, data):<br>    database.update(productId, data)<br>    cache.delete(&quot;product:&quot; + productId)</pre><p>Simple and effective. The next read repopulates the cache with fresh data. The downside: a brief window between the delete and the next read where every request hits the database.</p><p><strong>Strategy 3: Versioned cache keys</strong><br> Instead of invalidating a key, change the key itself.</p><pre>// v1<br>cache.set(&quot;product:v1:123&quot;, data)<br>// After update, write to v2<br>cache.set(&quot;product:v2:123&quot;, updatedData)<br>// Application reads from v2; v1 naturally expires</pre><p>Useful when you want zero downtime cache transitions or when you’re deploying changes that affect how data is structured in the cache.</p><p><strong>The write-then-delete pattern:</strong><br> When updating data, always write to the database first, then invalidate the cache — never the reverse. If you invalidate first and the database write fails, you’ve deleted the cached value and now serve stale data from the database (or no data at all). Database write first, cache invalidation second.</p><h3>Atomic Operations and Distributed Locks</h3><p>Redis is single-threaded for command execution, which makes it useful for coordination across distributed services. Two patterns worth knowing:</p><p><strong>Atomic increment (counters, rate limiting):</strong></p><pre>// Atomic — no race condition possible<br>cache.increment(&quot;rate_limit:user:123&quot;)<br>cache.expire(&quot;rate_limit:user:123&quot;, 60)</pre><p><strong>Distributed lock (prevent duplicate processing):</strong></p><pre>acquired = cache.setIfNotExists(&quot;lock:job:456&quot;, &quot;locked&quot;, TTL=30)<br>if acquired:<br>    process(job)<br>    cache.delete(&quot;lock:job:456&quot;)<br>else:<br>    // Another instance is already processing this job<br>    skip()</pre><p>This is the foundation of preventing duplicate operations in distributed systems — the same pattern used for idempotent job processing, preventing double payments, and ensuring exactly-one execution of scheduled tasks.</p><h3>When NOT to Cache</h3><p>This is the section most caching articles skip.</p><p><strong>Don’t cache highly personalised data at the object level.</strong><br> If every user gets a different version of the response, your cache hit rate approaches zero. You’re paying the overhead of cache reads with none of the benefit. Cache at a lower level (raw database results, computed fragments) rather than the full personalised response.</p><p><strong>Don’t cache data that changes faster than your TTL.</strong><br> If stock prices update every second and your TTL is 60 seconds, you’re not serving fresh data — you’re serving lies confidently. Either shorten the TTL to the point where caching has no benefit, or rethink the architecture (WebSocket push, not pull).</p><p><strong>Don’t cache data where consistency is non-negotiable.</strong><br> Account balances in the middle of a transaction. Seat availability at the moment of booking. Anything where two users making decisions simultaneously on cached data would cause a conflict. Cache the lookup, not the decision-critical state.</p><p><strong>Don’t cache to fix a slow query you haven’t tried to fix.</strong><br> Caching a query that takes 4 seconds is treating the symptom, not the cause. Add an index first. Restructure the query. Denormalise if necessary. Cache should be a layer of optimisation on an already-reasonable system, not a band-aid on a broken one.</p><p><strong>Don’t cache error responses.</strong><br> If a downstream service returns a 500 and you cache that, every subsequent request gets the cached error until TTL expires. Always check the response before caching. Only cache successful, valid responses.</p><h3>Cache Warming</h3><p>Cold caches cause pain. After a deployment or a Redis restart, every request is a cache miss until the cache warms up organically. Under high traffic, this can cause a sudden spike in database load — sometimes enough to cause an outage right after a deployment.</p><p><strong>Proactive warming:</strong> Before routing traffic to a new instance, pre-populate the cache with the most frequently accessed keys. Run a background job that fetches the top N records from the database and loads them into Redis.</p><p><strong>Gradual traffic shifting:</strong> Don’t cut over all traffic at once. Shift 10%, let the cache warm, then increase. Useful during deployments.</p><h3>The One-Line Summary</h3><p>Cache what’s read frequently and changes infrequently. Set TTLs based on how much staleness your business can tolerate. Invalidate explicitly when correctness matters. And before adding Redis, ask whether the real problem is a slow query that should just be fixed.</p><p><em>If you found this useful, I write about backend architecture, Java, and System Design. Follow for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f99349c8435" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro-services Communication: When to Use REST, When to Use Messaging, and Why It Matters]]></title>
            <link>https://medium.com/@acabhisikta/micro-services-communication-when-to-use-rest-when-to-use-messaging-and-why-it-matters-e0b8c3da27f9?source=rss-82187ccb8f58------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0b8c3da27f9</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Abhisikta]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 05:59:25 GMT</pubDate>
            <atom:updated>2026-06-27T05:59:25.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uihQ11ARuk-m_NKcYNPxg.jpeg" /></figure><p><em>An architecture design guide for mid-level backend developers.</em></p><p>You are building your micro-service project. You have split your monolith. You have separate service. But now they need to talk to each other?</p><p>How would you approach this problem?</p><p>Most developers default to REST because it is familiar. Call a service, get a response, move on. And often that is exactly right. But sometimes it isn’t. And choosing wrong doesn’t blow up immediately. It blows up at 3AM six months later when your order service is down and it has taken your payment service with it.</p><p>This article is about making that choice deliberately.</p><h3>The Core Question : Does the Caller Need to Wait?</h3><p>Before you think about REST vs Kafka, queues vs streams, sync vs async — you should ask one simple question :</p><p><strong>Does the caller need the result of this operation before it can continue?</strong></p><p>If yes → synchronous communication is the obvious choice.</p><p>If no → you are probably forcing a dependency that does not need to exit.</p><p>The implementation then becomes quite easy.</p><h3><strong>Synchronous Communication (REST/gRPC)</strong></h3><p>In synchronous communication, Service A calls Service B and waits. The thread is blocked, the connection is held open, and Service A cannot proceed until Service B responds.</p><p>This is the right choice when —</p><ul><li>You need the result immediately to complete the current operation.</li></ul><p>For example, a payment service calling a fraud detection service before authorising transaction — you cannot proceed without that answer.</p><ul><li>The operation is inherently request-response in nature.</li></ul><p>For example, A user logs in, you validate credentials, you return a token. There is no async version of this that makes sense.</p><ul><li>You need strong consistency.</li></ul><p>For example, If service B’s answer changes what Service A does next, you need it synchronously.</p><ul><li>Simplicity matters more than resilience. Sync is easier to reason about, easier to debug and easier to trace.</li></ul><h4>Where it breaks down :</h4><p>The problem with synchronous communication in microservices is <strong>temporal coupling</strong>. Service A can only succeed if Service B is available <em>right now</em>. If Service B is slow, service A is slow. If Service B is down, Service A fails. In a chain of synchronous calls — A calls B, B calls C, C calls D — the reliability of the entire chain is the product of each service’s reliability.</p><p>If each service is 99.99% available, a chain of 5 synchronous calls is only ~99.5% available. At scale, this compounds fast.</p><p>This is also where <strong>cascading failures</strong> come from.</p><p>Service D slows down under load → Service C threads pile up waiting → Service B starts timing out waiting for C -&gt; Service A starts failing.</p><p>One slow service poisons the whole flow.</p><h3>Asynchronous Communication ( Message Queues / Event Streaming )</h3><p>In asynchronous communication, Service A publishes a message to a broker and moves on. It does not wait. Service B picks up that message when it is ready and processes it independently.</p><p>This is the right choice when :</p><ul><li>The caller doesn’t need an immediate result.</li></ul><p>For example, An order is placed — you need to send a confirmation email, update inventory, notify the warehouse, and generate an invoice. None of these need to happen before the use sees “Order Confirmed”. They just need to happen eventually.</p><ul><li>You want services to be independent of each other’s availability.</li></ul><p>For example, If the email service is down, the order still completes. The message sits in the queue and gets processed when the email service recovers.</p><ul><li>You have fan-out patterns.</li></ul><p>For example, One event needs to trigger multiple downstream actions. Publishing a single “OrderPlaced” event and having 5 different consumers react to it is far cleaner than Service A making 5 synchronous calls.</p><ul><li>You need to handle traffic spikes.</li></ul><p>For example, A message broker acts as a buffer. If 10,000 orders come in simultaneously, the queue absorbs the spike and downstream services process at their own pace rather than getting hammered all at once.</p><ul><li>You want natural retry and durability.</li></ul><p>Messages persist in the broker. If a consumer crashes mid-processing, the message isn’t lost — it gets redelivered.</p><p><strong>Where it breaks down :</strong></p><p>Async is not simpler — it is a different kind of complex. You trade temporal coupling for eventual consistency, which means :</p><ul><li>You cannot gurantee the order of operations without careful design.</li><li>Debugging is harder. There’s no single stack trace that shows you what happened. You need distributed tracing and correlation IDs across services.</li><li>Error handling requires explicit design. What happens if a message processing fails repeatedly? You need dead letter queues, alerting and a strategy for replaying failed messages.</li><li>Testing is harder. You can’t just call a function and assert a return value — you need to verify that the right message was published and that consumers reacted correctly.</li></ul><h3>The Decision Framework</h3><p>Here’s how to think through it for any given service interaction :</p><p><strong>Use synchronous (REST/gRPC) when :</strong></p><ul><li>The caller needs the result to proceed.</li><li>You need immediate consistency.</li><li>The interaction is naturally request-response.</li><li>The downstream service is under your control and reliably fast.</li></ul><p><strong>Use asynchronous (messaging) when :</strong></p><ul><li>The caller doesn’t need the result immediately.</li><li>Multiple services need to react to the same event.</li><li>You need the system to remain functional even if a downstream service is temporarily unavailable.</li><li>You’re dealing with long-running operations or heavy processing.</li></ul><p><strong>The grey zone — async with a callback :</strong></p><p>Sometimes you need the result eventually but not immediately. A user triggers a report generation — it will take 30 seconds. You don’t want to hold an HTTP connection open for 30 seconds.</p><p>Solution ? Accept the request synchronously (return a job ID immediately), process it asynchronously, and notify the caller via webhook or polling when it’s done. This is a common pattern for anything that requires more than a few seconds.</p><h3>Choosing a Messaging Technology</h3><p>Once you’ve decided to go async, the next question is what to use ?</p><h4>Message Queues (RabbitMQ, SQS) :</h4><p>Point-to-point or pub/sub. A message is consumed once and removed. Good for task distribution — you want exactly one consumer to process each job. Natural fit for things like sending emails, processing payments, running background jobs.</p><h4>Event Streaming (Kafka) :</h4><p>Messages are persisted as an ordered log. Multiple consumers can read the same message independently, at their own pace. Messages are retained for a configurable period, so consumers can replay history. Good for event-driven architectures, audit logs, real-time analytics, and fan-out patterns where multiple services need the same event.</p><p>The key difference : Kafka is a log, not a queue. Messages aren’t deleted after consumption.</p><p>A rough guide : If you’re distributing tasks to workers — use a queue. If you’re broadcasting events that multiple services need to react to — or that you might want to replay — use Kafka.</p><h3>What Most Developers Get Wrong</h3><ol><li><strong>Making everything async because it sounds scalable.</strong></li></ol><p>Async adds complexity. If your service handles 100 requests a day and latency doesn’t matter, synchronous REST is completely fine. Don’t introduce a message broker because it feels more “microservice-y”.</p><p><strong>2. Ignoring idempotency in async systems.</strong></p><p>Messages can be delivered more than once. If your consumer is not idempotent — if processing the same message twice causes duplicate emails, double charges, or double inventory updates — you have a bug waiting to happen. Design consumers to handle duplicates safely.</p><p><strong>3. No dead letter queue strategy.</strong></p><p>Messages will fail. A consumer will throw an exception, a downstream database will be unavailable, a payload will be malformed. Without a dead letter queue and an altering strategy, failed messages silently disappear and you find ouy weeks later that 300 orders never got confirmation emails.</p><p><strong>4. Synchronous chains masquerading as microservices.</strong></p><p>If Service A calls Service B which calls Service C which calls Service D — all synchronously — you don’t have microservices. You have a distributed monolith with all the operational complexity of microservices and none of the resilience benefits. Look for these chains and ask whether each call genuinely needs to be synchronous.</p><h3>The One-Line Summary</h3><p>Use synchronous communication when the caller needs the answer to continue. Use asynchronous messaging when it doesn’t — and design your system so that as few things as possible need to wait.</p><p>The goal isn’t to use one or the other. It is to be intentional about which dependency needs to exist in real time and which doesn’t.</p><p><em>If you found this useful, I write about backend architecture, Java, and System Design. Follow for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b8c3da27f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>