DEV Community

Harsh Kadyan
Harsh Kadyan

Posted on

Adding Redis caching to the THEDEVS backend. 200ms to 5ms.

been optimizing the THEDEVS backend today and finally added a Redis caching layer on top of MongoDB

some API routes were taking like 200ms because they were doing heavy aggregation queries on every request. just cached the results in Redis with a 5 minute TTL

same routes now respond in under 5ms. thats a 40x improvement from just a few lines of code

the tricky part was cache invalidation. had to be careful about when to bust the cache. ended up using a pattern where any write operation clears the related cache keys before returning

learned the hard way that caching everything is a bad idea. you gotta cache only the read heavy data that doesnt change often. cached some user specific data by mistake and people were seeing other peoples info lol

moral of the story. add caching early but be thoughtful about what you cache

harshkadyan #thedevs #brutalharsh

Top comments (0)