Why Your Cache Breaks The Moment You Scale Beyond One Python Process
From the publisher’s feed, collected in the ZeroLabs newsroom.
Python Caching Explained Through A Production Disaster ☠️Photo by Growtika on UnsplashIn the last blog, we learned something painful:Async wasn’t about making your app faster. It was about helping your app survive waiting.Because modern applications spend half their lives waiting for APIs, waiting for databases, waiting for LLMs, waiting for somebody else’s server in another country having a difficult day & async solved that beautifully.Python Async Isn't About Speed - It's About Surviving Waiting 😴Our AI app stopped freezing. Users stopped staring at loading spinners like they were contemplating life choices. Everything was great.For about 11 minutes. Because the moment traffic increased… a completely different monster appeared. Not slowness. Not waiting.Memory.More specifically, the horrifying realization that your cache is basically a goldfish with identity issues once multiple Python processes enter the chat.See, after optimizing our async AI application, we did what every engineer eventually does, We added caching.And ohhhhhh…for a brief shining moment…we felt unstoppable.API calls dropped. Responses became instant. The OpenAI bill stopped looking like medical debt. We wrote this masterpiece:cache = {}def get_summary(text): if text in cache: print("Cache hit") return cache[text] print("Calling expensive API...") result = expensive_llm_call(text) cache[text] = result return resultWe tested it locally. First request ➡️ slow. Second request ➡️ instant. At this point every developer experiences the same dangerous thought:Wait… distributed systems are actually easy?Python watches this confidence silently. Like a horror movie villain watching teenagers enter the basement. Because everything works beautifully…Until you add:multiple usersmultiple workersmultiple podsmultiple containersAnd suddenly:cache misses appear randomlyduplicate API calls explodememory becomes inconsistentusers start hitting different realitiesToday we’re going to recreate that disaster locally. Not theoretically.Not with a Kubernetes diagram containing seventeen hexagons and three arrows labeled service mesh.We’ll build a cache, scale it beyond a single Python process, watch it fail, understand exactly why it fails, and then fix it using Redis, TTLs, and request deduplication.By the end, you’ll understand why in-memory caching works perfectly on your laptop, why it breaks the moment you scale, and why Redis became one of the most important pieces of infrastructure on the modern internet.https://medium.com/media/ad524f8b2308e2412b6607ec702ddd26/hrefThe Day Our Cache Started Living Multiple LivesSo far, everything looks fantastic. We have a FastAPI application, an expensive AI call, and a simple in-memory cache:cache = {}Every time a request arrives, we first check the cache. If the value exists, we return it instantly. If not, we call the expensive API, store the result, and cache future requests.To make the behavior easier to observe, I added two small pieces of instrumentation:a worker ID using os.getpid()a counter tracking real API callsThis lets us see exactly which process handled each request and whether the response came from the cache or the underlying API.Our application now looks like this:import timeimport randomimport asyncioimport osfrom fastapi import FastAPIapp = FastAPI()cache = {}API_CALL_COUNT = 0async def expensive_llm_call(text: str): global API_CALL_COUNT API_CALL_COUNT += 1 print(f"\n🔥 REAL API CALL for: {text}") print(f"📞 Total API Calls: {API_CALL_COUNT}") await asyncio.sleep(3) return f"Summary of {text}"@app.get("/summary")async def summarize(text: str): worker_id = os.getpid() if text in cache: return { "worker": worker_id, "source": "CACHE", "result": cache[text] } result = await expensive_llm_call(text) cache[text] = result return { "worker": worker_id, "source": "API", "result": result }If we run a single FastAPI worker:uvicorn app:appeverything behaves exactly as expected.## Request 1:{"worker":87717,"source":"API","result":"Summary of batman"}## Request 2:{"worker":87717,"source":"CACHE","result":"Summary of batman"}Same worker 🤝 Same memory 🤝 Same cache 👉 Life is good. At this point many developers accidentally learn the wrong lesson:Caching is solved 😎What they have actually learned is:Caching works when there is only one Python process.Those are very different statements. Let’s change one thing. Instead of running a single worker, we’ll run two:uvicorn app:app --workers 2This looks innocent. It is not. FastAPI doesn’t create two threads. It creates two completely separate Python processes.Each process has:its own memoryits own variablesits own cache dictionaryConceptually, our architecture now looks like this:Request | ------------------ | | Worker A Worker B cache={} cache={}Notice something important ? Worker A cannot see Worker B’s memory. Worker B cannot see Worker A’s memory. Each worker believes its cache is the only cache that exists. Let’s prove it.Hit the endpoint a few times and look at the worker IDs:## Request 1:{"worker":91335,"source":"API","result":"Summary of batman"}## Request 2:{"worker":91335,"source":"CACHE","result":"Summary of batman"}## Request 3:{"worker":91334,"source":"API","result":"Summary of batman"}The same request is now bouncing between different workers. When a request lands on Worker A, it can use Worker A’s cache. When a request lands on Worker B, it only sees Worker B’s cache.Our dictionary never stopped working. The cache wasn’t broken. Our assumption was. We assumed memory was shared. Python never made that promise.https://medium.com/media/46a1cdf10624ae19c36168d6fc722403/hrefAnd this is the exact moment where caching stops being a Python feature and starts becoming a distributed systems problem.Fixing The Split-Brain Cache With RedisWe finally found the real problem. Our cache wasn’t failing. Our workers simply couldn’t see each other’s memory. Every FastAPI worker had its own private universe:Worker Acache={}Worker Bcache={}When Worker A cached a value, Worker B had absolutely no idea it existed.Kubernetes Makes This Worse Now imagine this in production. Instead of 2 workers:Load Balancer ↓ Pod A Pod B Pod C Pod DEvery pod has:separate RAMseparate Python processseparate cache, etc.Your global cache was never global. It was just emotionally global. This is one of the most important backend engineering lessons you’ll ever learn. Stateless services became popular because local memory becomes unreliable the moment you scale horizontally.So where should shared data live? The answer is surprisingly simple: Not inside your application.Instead, we move the cache into a separate service that every worker can access.Enter Redis — The Shared Brain 🧠Redis is an in-memory datastore that lives outside your Python process.https://medium.com/media/e0b9f7bc3cb9393b47a38a46638aba15/hrefInstead of storing cached values inside a local dictionary, all workers talk to the same Redis instance. Our architecture now looks like this: Redis ▲ │ ┌─────────┴─────────┐ │ │ Worker A Worker BNow when Worker A stores a value:batman → Summary of batmanWorker B can immediately read it. The cache becomes shared. The workers remain independent. Everybody wins.Here’s how we can implement it in the existing code:import redisredis_client = redis.Redis( host="localhost", port=6379, decode_responses=True)cached = redis_client.get(text)if cached: return { "worker": worker_id, "source": "CACHE", "result": cached }result = await expensive_llm_call(text)redis_client.set(text, result)return { "worker": worker_id, "source": "API", "result": result}Then run the same experiment again. Same two workers. Same endpoint.Success 🤔Worker A can now create a cache entry and Worker B can immediately use it.Our cache is finally shared, the duplicate API calls caused by isolated worker memory are gone, and for a brief moment everything looks wonderfully production-ready.Naturally, this is the exact moment an engineer becomes dangerous. We look at Redis, look at our cache hit rate, and start thinking:Nice. We solved caching.Unfortunately, production systems have a long history of humbling people immediately after they say things like that.Because while Redis solved our shared state problem, it did not solve our concurrency problem.And the moment a traffic spike arrives, we’re about to discover that fifty users can still trigger the same expensive API call at exactly the same time.To see why, let’s stop making requests one at a time and simulate what real traffic actually looks like.Redis Fixed The Cache. It Didn’t Fix The Crowd.So far we’ve been testing our application the way developers usually test things:One request.Wait.Another request.Observe success.Repeat.Real traffic doesn’t behave like that. Users don’t politely stand in a queue waiting for each other to finish.They arrive together. Sometimes hundreds of them.Sometimes thousands. And they all want the same thing at exactly the same moment.To simulate this behavior, I wrote a small traffic generator that launches multiple concurrent requests against our API.Instead of manually calling the endpoint with curl, the simulator creates 50 users that all request the exact same Batman summary simultaneously.import asyncioimport randomimport timeimport httpxfrom rich import printfrom rich.live import Livefrom rich.table import Tablefrom rich.console import Consoleconsole = Console()stats = { "total_requests": 0, "api_hits": 0, "cache_hits": 0,}recent_events = []URL = "http://127.0.0.1:8000/summary"# heroes = [# "batman",# "superman",# "batman",# "batman",# "superman",# "batman",# "flash",# "flash",# ]heroes = ["batman"]async def make_request(client, hero, request_id): start = time.time() response = await client.get( URL, params={"text": hero} ) data = response.json() duration = round(time.time() - start, 2) stats["total_requests"] += 1 if data["source"] == "API": stats["api_hits"] += 1 else: stats["cache_hits"] += 1 recent_events.append( f"Req {request_id} | {hero: f"{data['source']: f"Worker {data['worker']} | " f"{duration}s" ) recent_events[:] = recent_events[-15:]async def traffic_burst(): async with httpx.AsyncClient() as client: tasks = [] for i in range(50): hero = random.choice(heroes) task = asyncio.create_task( make_request(client, hero, i) ) tasks.append(task) await asyncio.gather(*tasks)def build_table(): table = Table(title="Cache Simulation Dashboard") table.add_column("Metric") table.add_column("Value") table.add_row( "Total Requests", str(stats["total_requests"]) ) table.add_row( "API Hits", str(stats["api_hits"]) ) table.add_row( "Cache Hits", str(stats["cache_hits"]) ) return tablefrom rich.console import Groupfrom rich.panel import Panelasync def dashboard(): with Live(refresh_per_second=4) as live: traffic_task = asyncio.create_task( traffic_burst() ) while not traffic_task.done(): table = build_table() events_text = "\n".join( recent_events[-10:] ) layout = Group( table, Panel( events_text, title="Recent Activity" ) ) live.update(layout) await asyncio.sleep(0.3) table = build_table() events_text = "\n".join( recent_events[-10:] ) layout = Group( table, Panel( events_text, title="Recent Activity" ) ) live.update(layout)asyncio.run(dashboard())For this experiment, we’re still using Redis as our cache. Nothing else changes.Same application 🤝 Same Redis instance 🤝 Same cache key.The only difference is that requests now arrive concurrently instead of one at a time. We start our application with multiple workers & then we run the simulator, What happened next was… unexpected.Run 1: The Empty Cache DisasterThe first time we run the simulator, Redis is empty. No Batman summary exists yet. The cache has never been populated. This was the result:Notice the numbers:Total Requests : 50API Hits : 50Cache Hits : 0Wait. What? We have Redis now. We have a shared cache. Why did we still make fifty expensive API calls? The answer lies in timing.Imagine all 50 requests arriving within a few milliseconds of each other. A simplified timeline looks like this:## t = 0.00050 requests arrive## t = 0.001All 50 check Redis## t = 0.002Redis is empty## t = 0.003All 50 start expensive work## t = 3.000All 50 store the same valueThe key observation is that none of the requests waited long enough for another request to populate the cache.Every request checked Redis before the first request finished generating the result. From the perspective of every request:Cache?Nope.Guess I'll do the work myself.Fifty requests. Fifty cache misses. Fifty identical API calls. Fifty workers all solving the same problem independently.Your backend: 🔥🔥🔥🔥🔥Your API bill: 📈📈📈📈📈Your manager: Can we optimize this?Redis wasn’t broken. The cache wasn’t broken. The timing was.This phenomenon is known as a cache stampede (sometimes called the thundering herd problem).https://medium.com/media/ec043c0f6c5d48b773cb372c0f8380a0/hrefIt occurs when many requests encounter a cache miss simultaneously and all rush to perform the same expensive computation.Instead of reducing load, the cache accidentally amplifies it. And in production systems, this can be devastating.Imagine replacing our fake AI call with:an LLM APIa database querya recommendation enginea machine learning modelA single traffic spike can suddenly generate hundreds or thousands of duplicate expensive operations.The very system designed to protect your infrastructure can become the reason it gets overwhelmed.Run 2: The Warm CacheNow let’s run the exact same simulator again. Just run it one more time.This time, however, the Batman summary already exists in Redis because the previous burst populated the cache.Here’s what happened:Notice the difference:Total Requests : 50API Hits : 0Cache Hits : 50Same workload. Same application. Same Redis instance. Completely different outcome.Every request immediately found the value in Redis and returned without performing any expensive work.The response times dropped dramatically. The API remained untouched. The cache behaved exactly as we originally imagined it would.And this reveals something extremely important: The cache itself was never the problem. The problem exists during the tiny window between:Cache entry does not exist ↓Expensive work begins ↓Cache entry gets storedIf hundreds of requests arrive during that tiny window, they all duplicate the same expensive work.Once the cache is populated, everything becomes fast again. Unfortunately, production systems spend a surprising amount of time living inside that tiny window.Especially when:cache entries expireapplications restarttraffic spikes suddenly occurpopular content gets requested after being inactiveAnd that leads us to an important realization. Redis solved our shared-state problem. Workers can now see the same cache.But Redis did not solve our concurrency problem ❗️We still have fifty requests independently performing the same expensive work before the cache gets populated.Caching and request deduplication are not the same thing.To solve this problem, we need a way for one request to do the work while everybody else waits for the answer. That’s exactly what we’ll build next.One Request Works. Everyone Else Waits 🤓We finally understand the problem. Redis solved our shared-memory issue. Every worker can now see the same cache.But Redis alone did not stop fifty concurrent requests from performing the exact same expensive work before the cache was populated.In our previous experiment, we saw this:Total Requests : 50API Hits : 50Cache Hits : 0Fifty users requested the same Batman summary. Fifty requests checked Redis. Fifty requests saw a cache miss.Fifty requests independently called the expensive API.The cache wasn’t helping because it didn’t exist yet.So the obvious question becomes:Why are we letting fifty requests solve the same problem?What we actually want is something like this:Request #1 ↓Compute Result ↓Save To RedisRequest #2Request #3Request #4...Request #50 ↓Wait ↓Reuse ResultOnly one request should perform the expensive work. Everyone else should simply wait for the answer.This technique is commonly known as:Request DeduplicationRequest CoalescingSingle Flight PatternDifferent names 🤝 Same idea.One request works. Everyone else benefits.Building A Simple Distributed LockTo achieve this, we need a way for requests to coordinate with each other.Since all workers can already communicate through Redis, we can use Redis as a lightweight locking mechanism.When a request encounters a cache miss, it attempts to create a lock:lock_acquired = redis_client.set( lock_key, "processing", nx=True, ex=10)A few important things are happening here: nx=True means:Only create the key if it doesn’t already exist.The first request succeeds. Every other request fails.And: ex=10adds a 10-second expiration.This prevents deadlocks if a worker crashes while holding the lock.Without a timeout, a crashed worker could leave the lock behind forever and block future requests indefinitely.The First Request Becomes The WorkerThe request that successfully acquires the lock becomes responsible for generating the result.Conceptually:Cache Miss ↓Acquire Lock ↓Call Expensive API ↓Save To Redis ↓Release LockIn code:if lock_acquired: result = await expensive_llm_call(text) redis_client.set( text, result, ex=60 ) redis_client.delete(lock_key) return resultOnly one request reaches this path. No matter how many users arrive simultaneously.Everybody Else WaitsWhat happens to the remaining requests? They simply wait until the first request finishes.Their flow now looks like:Cache Miss ↓Lock Already Exists ↓Wait ↓Check Redis Again ↓Receive Shared ResultIn code:while True: await asyncio.sleep(0.2) cached = redis_client.get(text) if cached: return cachedInstead of calling the expensive API themselves, these requests patiently wait for the first request to finish its work.The moment the result appears in Redis, everyone immediately reuses it.Running The Experiment AgainNow let’s rerun the exact same simulator. Same application. Same Redis instance. Same workload. Same 50 concurrent users.The only difference is our new request deduplication logic.This time the dashboard looks very different.Notice something interesting. We didn’t get 49 cache hits. We got 49 WAITED responses. That’s because the cache didn’t exist yet.The first request was still generating the Batman summary. Every other request patiently waited for that result instead of generating its own copy.This is fundamentally different from a cache hit. A cache hit means the value already existed.A WAITED response means another request was actively creating the value and we reused its work.Notice what happened:Total Requests : 50API Hits : 1WAITED : 49This is the result we were hoping for all along. Only one request performed the expensive computation.The remaining 49 requests simply reused the result generated by the first request. Instead of generating fifty identical summaries, we generated exactly one. Now again run the script again & lets see what happens in warm start:The Batman summary already exists in Redis. Nobody needs to acquire a lock. Nobody needs to wait. Nobody needs to call the API. Every request immediately returns from cache.https://medium.com/media/5cadcb5bc1e8fadcea061956bdb7c28a/hrefLet’s Visualize The Difference## Stage 1: Redis Without Request Deduplication50 Requests ↓50 Cache Misses ↓50 API Calls ↓50 Identical Results---## Stage 2: Redis + Request Deduplication (Cold Cache)50 Requests ↓50 Cache Misses ↓1 Request Acquires Lock ↓1 API Call ↓49 Requests Wait ↓Result Stored In Redis ↓50 Shared Results---## Stage 3: Warm Cache50 Requests ↓50 Cache Hits ↓0 API Calls ↓50 Results Returned InstantlyThe interesting part is that all three scenarios used the same application, the same Redis instance, and the same cache key. The only difference was how requests arrived and whether the result already existed. This is why production caching is not just about storing data. It’s about coordinating access to that data when thousands of users show up at the same time.The amount of useful work hasn’t changed. Users still receive exactly the same response.But the amount of duplicated work has collapsed from fifty expensive operations to one. That’s an enormous reduction in load.Especially when the expensive operation is:an LLM calla database querya recommendation enginea machine learning modelan external APIAt production scale, this difference can be the difference between a healthy system and an outage.The Bigger Lesson Hidden Underneath All ThisThis article was never really about Redis.It was about understanding:memory ownership,process isolation,distributed state,coordination between services.The moment your application scales beyond one Python process, local memory stops behaving the way most developers intuitively expect.What felt shared on localhost suddenly becomes isolated. What felt fast suddenly becomes duplicated. And what looked like a simple cache slowly turns into a distributed systems problem.This is exactly why modern production systems became:statelessdistributedcache-drivencoordination-heavyAnd honestly, this is one of the biggest mindset shifts in backend engineering:Scaling is rarely about making code faster.It’s mostly about making multiple independent systems agree on what is currently happening.https://medium.com/media/31c19e0e59a45a55a158f43a8eb7a1da/hrefGreat job for making it to the end of this blog! I hope you learned something new and enjoyed this article !!! I will try to bring up more Machine learning/Data science concepts and will try to break down fancy-sounding terms and concepts into simpler ones.You can follow me Afaque Umer for more such articles. Thanks for reading 🙏Keep learning 🧠 Keep Sharing 🤝 Stay Awesome 🤘Why Your Cache Breaks The Moment You Scale Beyond One Python Process was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.