Back

Blogs

Thoughts and learnings from my journey in tech

Fadil Bafagih

Fadil Bafagih5 Sep 20264 min read

A Practical Guide to Redis Caching in Node.js Applications

What is Redis? Redis (which stands for Remote Dictionary Server) is an open-source, in-memory data structure store. It is primarily used as a fast, highly scalable key-value database, a cache, a message broker, and a streaming engine. Unlike traditional relational databases (like MySQL or PostgreSQL) that store data on hard drives or SSDs, Redis stores all of its data directly in the server's main memory (RAM). This architectural choice allows it to deliver incredibly fast, sub-millisecond response times because it eliminates the need to access slower disk storage. TL;DR: Redis is your database's best friend. It handles the heavy lifting so your primary database can chill. Key Characteristics Common Data Structures Redis isn't just a boring key-value store — it supports a ton of built-in data structures out of the box: Strings — The most basic type. Store text, numbers, or serialized objects. Lists — Collections of string elements sorted by insertion order. Perfect for queues. Sets — Unordered collections of unique strings. Great for tracking unique visitors. Hashes — Maps composed of fields and values (similar to objects or dictionaries in programming languages). Ideal for storing user profiles. Sorted Sets — Like Sets, but every string is associated with a score, allowing elements to be sorted automatically. Perfect for leaderboards. Primary Use Cases Here are the top real-world scenarios where Redis absolutely shines: Caching — Storing the results of frequent database queries or API calls so that subsequent requests can be served instantly without overloading the primary database. Session Management — Holding user login sessions and tokens for fast verification in web applications. Real-Time Analytics — Counting and processing fast-moving data streams, such as tracking website traffic or monitoring system metrics in real-time. Gaming Leaderboards — Using Sorted Sets to instantly calculate and retrieve a player's global rank. Pub/Sub Messaging — Acting as a lightweight message broker where publishers send messages to channels, and subscribers listen for those messages in real-time (useful for chat applications). Before vs. After Redis Let's visualize what happens when you add Redis to your architecture: Before Redis This side illustrates a standard architecture where the web application relies solely on PostgreSQL for all data operations. Direct Disk I/O — Every time a user makes a request, the web application queries PostgreSQL directly. Because PostgreSQL stores its data on a physical disk (Hard Drive or SSD), it has to perform Disk I/O operations, which are significantly slower than reading from memory. High Latency — The delay caused by waiting for the disk to find and return the data results in a high latency response for the user. Database Strain — Processing every single query, especially repetitive reads, consumes CPU and memory resources, eventually causing a bottleneck as traffic increases. After Redis This side shows how adding Redis dramatically improves performance and relieves the PostgreSQL database. In-Memory Speed (RAM) — Redis is placed between the web application and PostgreSQL. When the app needs data, it checks Redis first. Because Redis stores data in RAM, it provides ultra-fast read and write speeds. Low Latency — Retrieving data from RAM eliminates the slow Disk I/O, resulting in a low latency response that feels instantaneous to the user. Cache Miss and Sync — If Redis doesn't have the data (a "Cache Miss"), the system will fetch it from PostgreSQL and then store it in Redis for next time. Data writes or cache updates can be handled via asynchronous persistence in the background without slowing down the user's experience. A Happy Database — By letting Redis handle the bulk of the repetitive read requests, PostgreSQL is protected from being overwhelmed. PostgreSQL now has plenty of resources freed up to handle complex queries and essential data writes efficiently. Implementation in Express.js Application Alright, enough theory. Let's build a Product API that integrates Redis as a caching layer using the Service-Repository Pattern for clean, SOLID architecture. Project Structure Environment Configuration First, let's handle our environment variables. This centralized config makes it super clean to access settings across the entire app. src/config/env.config.ts Key Takeaways Redis is a performance multiplier — From 190ms to 5ms, the numbers speak for themselves. Cache-Aside is your go-to pattern — Check cache first, fallback to DB, then populate cache. Graceful degradation matters — If Redis dies, your app should still work (just slower). Clean architecture pays off — Interfaces + Dependency Injection = testable, swappable, maintainable code. Security is non-negotiable — Parameterized queries, input validation, and sort column whitelisting protect you from nasty attacks. Full Source Code GitHub Repository

38 views
1 likes
Read more
Fadil Bafagih

Fadil Bafagih16 Mei 20262 min read

5 Custom React Hooks yang Gue Pake Terus buat Bikin Coding Lebih Gampang

Waktu ngoding React, gue sering banget nemuin pattern yang sama berulang-ulang di setiap project. Daripada nulis logic yang sama terus-terusan, mending bikin custom hooks aja yang bisa dipake berkali-kali. Nah, ini dia 5 custom hooks favorit gue yang worth it banget buat dicoba! 1. useDebounce - Delay Execution dengan Elegan Masalahnya Apa? Pernah bikin fitur search dengan auto-complete? Setiap kali user ngetik, langsung trigger API call. Boros banget! Bayangin user ngetik "javascript" - itu udah 10 API calls cuma buat 10 huruf doang. Kodenya Nyimpen data ke localStorage itu ribet. Harus JSON.parse(), JSON.stringify(), plus handle error. Capek deh! Pro tip: Delay qwndodnqwdnqwodnqwpiodn Kesimpulan Chunked file upload is not complicated in concept: split, send, reassemble. The complexity lies in handling the edge cases correctly: idempotency, ordering, failure states, and cleanup. This implementation keeps responsibilities separated: the domain defines what a file is and what can go wrong, the application layer coordinates the chunking logic, infrastructure adapts to specific tools (PostgreSQL, local disk), and the HTTP layer translates between the application and HTTP clients. The StorageProvider interface is the most important design decision in the whole project. It is a small surface area that decouples the chunking logic from the storage destination entirely. Wherever you decide to store files — local disk, S3, GCS, Cloudinary, or anywhere else — the chunk upload logic does not change. That is, ultimately, what clean architecture is for. Kenapa Custom Hooks Itu Penting? Reusability - Logic yang sama, cukup tulis sekali Separation of Concerns - Logic terpisah dari UI Readability - Code lebih clean dan maintainable Testing - Lebih gampang di-test secara terpisah Happy coding!

596 views
23 likes
Read more

Showing 1 to 2 of 2 blogs

1
of 1