{"id":30878410,"url":"https://github.com/creator79/redis-mini","last_synced_at":"2025-09-08T05:08:54.624Z","repository":{"id":304091443,"uuid":"1017565494","full_name":"creator79/redis-mini","owner":"creator79","description":null,"archived":false,"fork":false,"pushed_at":"2025-07-24T19:10:49.000Z","size":135,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-24T22:16:24.500Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/creator79.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-10T18:23:36.000Z","updated_at":"2025-07-24T19:10:52.000Z","dependencies_parsed_at":"2025-07-11T07:43:31.738Z","dependency_job_id":"004cbf0f-ee86-4359-b912-9facc5f6b7ee","html_url":"https://github.com/creator79/redis-mini","commit_stats":null,"previous_names":["creator79/redis-mini"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/creator79/redis-mini","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creator79%2Fredis-mini","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creator79%2Fredis-mini/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creator79%2Fredis-mini/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creator79%2Fredis-mini/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/creator79","download_url":"https://codeload.github.com/creator79/redis-mini/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/creator79%2Fredis-mini/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274135710,"owners_count":25228209,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-08T02:00:09.813Z","response_time":121,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-08T05:08:53.351Z","updated_at":"2025-09-08T05:08:54.615Z","avatar_url":"https://github.com/creator79.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![progress-banner](https://backend.codecrafters.io/progress/redis/be2458d2-b7ff-460a-a1f9-533375a55eb1)]\n\n# Redis Server Implementation\n\nThis is a modular implementation of a Redis server in JavaScript. The codebase has been organized into a clean, maintainable structure based on Redis features and functionality.\n\n## Modular Architecture\n\nThe codebase is organized into the following modules:\n\n```\napp/\n├── config/\n│   ├── constants.js       # Centralized constants and enums\n│   └── config-parser.js   # Command-line argument parsing\n├── protocol/\n│   └── resp.js            # Redis Serialization Protocol implementation\n├── storage/\n│   ├── store.js           # In-memory key-value store\n│   └── rdb-loader.js      # RDB file loading and parsing\n├── replication/\n│   ├── replica-manager.js # Replica management and WAIT command\n│   └── replica-handshake.js # Replica handshake process\n├── commands/\n│   └── command-handler.js # Command dispatching and handling\n├── server.js              # Server setup and connection handling\n└── main.js                # Entry point\n```\n\nFor more details about the architecture, see [ModularArchitecture.md](./Notes/ModularArchitecture.md) in the Notes folder.\n\n## Running the Server\n\n```bash\n# Install dependencies\nnpm install\n\n# Run as master\nnpm start\n\n# Run as replica\nnpm start -- --replicaof \"127.0.0.1 6379\"\n\n# Run with custom port\nnpm start -- --port 6380\n\n# Run with custom RDB file location\nnpm start -- --dir ./data --dbfilename custom.rdb\n```\n\nYou can interact with the server using the Redis CLI:\n\n```bash\nredis-cli -p 6379 PING\nredis-cli -p 6379 SET mykey \"Hello World\"\nredis-cli -p 6379 GET mykey\n```\n\n## Next Steps 📚\n\n**Want to make it better? Try adding these features (in order of difficulty):**\n\n### Beginner Level (Class 6-8):\n1. **DEL command** - Delete a key (like removing a contact from your phone)\n2. **EXISTS command** - Check if a key exists (like checking if a contact exists)\n3. **KEYS command** - List all keys (like seeing all your contacts)\n\n### Intermediate Level (Class 9-10# Redis Clone - Simple Explanation 🚀\n\n## What is Redis? 🤔\n\nImagine Redis as a **super-fast chaiwala** who remembers everything! \n\n**Think of it like this:**\n- You have a **magical tapri** (tea stall) 🍵\n- The chaiwala remembers EXACTLY how you like your chai (2 spoons sugar, extra strong, with elaichi)\n- When you come back, he makes it INSTANTLY without asking\n- He remembers orders for THOUSANDS of customers\n- The tapri is in your computer's memory (RAM) so it's lightning fast\n- Multiple customers can order at the same time\n\n**Real-world examples that every Indian knows:**\n- **Swiggy/Zomato**: Redis remembers your favorite restaurants and recent orders\n- **PhonePe/Paytm**: Redis stores your login session so you don't have to enter PIN again and again\n- **WhatsApp**: Redis stores recent messages and online status\n- **Hotstar/Netflix**: Redis remembers where you stopped watching Sacred Games\n- **BookMyShow**: Redis holds your seat selection while you're paying (so no one else can book it)\n\n## What is RESP? 🗣️\n\nRESP stands for **REdis Serialization Protocol**. It's like a special language that Redis uses to talk to other programs.\n\n**Think of it like this:**\n- You speak Hindi 🇮🇳\n- Your South Indian friend speaks Tamil 🇮🇳\n- You need Google Translate to understand each other\n- RESP is the \"Google Translate\" between your program and Redis\n- Just like how all Indians can communicate in English at airports, all programs communicate with Redis using RESP\n\n### RESP Examples (Don't worry, it looks scary but it's simple!)\n\n**When you want to say \"PING\" (like checking if chaiwala is awake):**\n```\n*1\\r\\n$4\\r\\nPING\\r\\n\n```\n- `*1` means \"Boss, I'm sending 1 order\"\n- `$4` means \"The order is 4 letters long\"\n- `PING` is the actual command\n- `\\r\\n` are just \"line endings\" (like pressing Enter on your keyboard)\n\n**When you want to say \"SET customer_name Rajesh\" (like telling chaiwala to remember a customer):**\n```\n*3\\r\\n$3\\r\\nSET\\r\\n$12\\r\\ncustomer_name\\r\\n$6\\r\\nRajesh\\r\\n\n```\n- `*3` means \"Boss, I'm sending 3 things\"\n- First thing: `SET` (3 letters)\n- Second thing: `customer_name` (12 letters) \n- Third thing: `Rajesh` (6 letters)\n\n## Why Build a Redis Clone? 🛠️\n\n**Bilkul valid sawal hai!** Here's why:\n\n1. **Jugaad Mentality**: Indians love understanding how things work and making them better (like our famous jugaad!)\n2. **Skill Development**: Building your own Redis is like learning to make chai from scratch instead of just buying packets\n3. **Cost Saving**: Free Redis clone for your startup (very important for bootstrapped Indian startups!)\n4. **Learning**: It's like understanding how your Activa engine works - once you know, you can fix anything!\n5. **Customization**: Add features specifically for Indian market (like handling rupee calculations better)\n\n## Why Use Redis CLI Instead of Building Our Own? 🤷‍♂️\n\n**Bahut accha sawal!** Here's the smart reason (typical Indian business strategy):\n\n### Option 1: Build Everything from Scratch 😰 (Like starting your own telecom company)\n```\nMy Program ←→ My Custom Protocol ←→ My Redis Clone\n```\n- You need to build TWO things: the server AND the client\n- It's like Reliance starting from scratch - possible but takes years!\n- Other programs can't talk to your Redis because it speaks a different language\n- More work, less compatibility\n- **Typical Indian parent reaction**: \"Itna mehnat kyun kar rahe ho?\"\n\n### Option 2: Use Existing Redis CLI (What we did!) 😎 (Like using existing infrastructure)\n```\nRedis CLI ←→ RESP Protocol ←→ Our Redis Clone\n```\n- We only build the server (our Redis clone)\n- We use the existing Redis CLI (already built and tested)\n- It's like using existing railway tracks for your new train\n- Anyone who knows Redis can use our clone immediately!\n- Less work, more compatibility\n- **Smart Indian approach**: \"Kaam kam, fayda zyada!\"\n\n**Perfect Indian analogy:**\n- Instead of building a new type of electrical outlet (like having different plugs for every state), we make our device work with existing outlets\n- People can use their existing chargers (Redis CLI) with our device (Redis clone)\n- Just like how all phones in India use the same charging port now!\n\n## How This Makes it a \"Redis Clone\" 🎭\n\nOur server speaks the same language (RESP) as real Redis, so:\n- Redis CLI thinks it's talking to real Redis\n- Our server responds just like real Redis would\n- From the outside, it looks and acts like Redis!\n\n**Perfect Indian example:**\n- **Real Redis**: Customer asks \"Chai hai?\" → \"Haan hai!\"\n- **Our clone**: Customer asks \"Chai hai?\" → \"Haan hai!\"\n- **Customer can't tell the difference** - both serve the same purpose!\n\nIt's like those local Chinese restaurants that taste exactly like the original but are made by Indian chefs. The customer gets the same experience! 🍜\n\n## Commands Explained (Like You're a Class 5 Student!) 👶\n\n### 1. PING Command 🏓\n**What it does:** Checks if the server is alive\n**Like:** Calling your friend and saying \"Sun raha hai?\" and they reply \"Haan bol!\"\n\n**Example:**\n```bash\nredis-cli PING\n```\n**Response:** `PONG`\n\n**Real-world use:**\n- WhatsApp checking if you're online\n- Swiggy checking if restaurant is accepting orders\n- Your mom checking if you're awake for morning classes\n\n**In our code:**\n```javascript\ncase \"PING\": {\n  return serializeSimpleString(\"PONG\");\n}\n```\n\n### 2. ECHO Command 📢\n**What it does:** Repeats whatever you say\n**Like:** Shouting \"Bharat Mata ki\" from a hill and hearing \"Jai!\" back\n\n**Example:**\n```bash\nredis-cli ECHO \"Jai Hind\"\n```\n**Response:** `\"Jai Hind\"`\n\n**Real-world use:**\n- Testing if server is working properly\n- Debugging network connections\n- Like when you test your mic before a presentation\n\n**In our code:**\n```javascript\ncase \"ECHO\": {\n  if (args.length \u003c 2) {\n    return serializeError(\"ERR wrong number of arguments for 'ECHO'\");\n  }\n  return serializeBulkString(args[1]);\n}\n```\n\n### 3. SET Command 📝\n**What it does:** Saves a value with a name (key)\n**Like:** Writing \"Rahul\" on a sticker and putting it in a box labeled \"class_monitor\"\n\n**Example:**\n```bash\nredis-cli SET student_name \"Priya\"\nredis-cli SET marks \"95\"\nredis-cli SET favorite_subject \"Maths\"\nredis-cli SET pocket_money \"500\"\n```\n**Response:** `OK`\n\n**With expiration (PX option) - Very Important!**\n```bash\nredis-cli SET otp_code \"123456\" PX 300000\n```\nThis saves the OTP but it disappears after 5 minutes (300000 milliseconds)!\n**Perfect for:**\n- Bank OTPs that expire in 5 minutes\n- Paytm login sessions\n- BookMyShow seat reservations (expire in 15 minutes)\n\n**In our code:**\n```javascript\ncase \"SET\": {\n  const key = args[1];      // The box label (like \"student_name\")\n  const value = args[2];    // What goes in the box (like \"Priya\")\n  let ttl = null;           // Time to live (expiration)\n  \n  // Check if they want expiration (like OTP timeout)\n  for (let i = 3; i \u003c args.length - 1; i++) {\n    if (args[i].toUpperCase() === \"PX\") {\n      ttl = parseInt(args[i + 1], 10);\n    }\n  }\n  \n  const record = {\n    value,\n    expiresAt: ttl ? Date.now() + ttl : null,\n  };\n  \n  store.set(key, record);\n  return serializeSimpleString(\"OK\");\n}\n```\n\n### 4. GET Command 📖\n**What it does:** Gets a value by its name (key)\n**Like:** Looking for the box labeled \"class_monitor\" and checking what name is inside\n\n**Example:**\n```bash\nredis-cli GET student_name\n```\n**Response:** `\"Priya\"`\n\n**Real-world examples:**\n```bash\nredis-cli GET user_session     # Check if user is logged in\nredis-cli GET cart_items       # Get items in shopping cart\nredis-cli GET last_seen        # When user was last online\nredis-cli GET notification_count # Number of unread notifications\n```\n\n**If the key doesn't exist:**\n```bash\nredis-cli GET nonexistent_student\n```\n**Response:** `(nil)` (which means \"kuch nahi mila\")\n\n**In our code:**\n```javascript\ncase \"GET\": {\n  const record = store.get(args[1]);\n  \n  if (!record) {\n    return serializeNullBulkString();  // Nothing found\n  }\n  \n  // Check if it expired (like OTP timeout)\n  if (record.expiresAt \u0026\u0026 Date.now() \u003e record.expiresAt) {\n    store.delete(args[1]);\n    return serializeNullBulkString();  // Expired, so return nothing\n  }\n  \n  return serializeBulkString(record.value);\n}\n```\n\n### 5. CONFIG Command ⚙️\n**What it does:** Shows server configuration settings\n**Like:** Asking your friend \"Tumhara address kya hai?\" or \"Phone number kya hai?\"\n\n**Example:**\n```bash\nredis-cli CONFIG GET dir\nredis-cli CONFIG GET dbfilename\n```\n**Response:** Shows the directory and filename settings\n\n**Real-world use:**\n- Checking where database files are stored\n- Debugging server configuration\n- Like checking your phone's storage location\n\n**In our code:**\n```javascript\ncase \"CONFIG\": {\n  const param = args[2];\n  let value = null;\n  \n  if (param === \"dir\") {\n    value = config.dir;\n  } else if (param === \"dbfilename\") {\n    value = config.dbfilename;\n  }\n  \n  return `*2\\r\\n${serializeBulkString(param)}${serializeBulkString(value)}`;\n}\n```\n\n## How Our Memory Store Works 🧠\n\nWe use a JavaScript `Map` as our \"magical almirah\" (cupboard):\n\n```javascript\nconst store = new Map();\n```\n\n**It's like a well-organized Indian household almirah:**\n- Each shelf has a label (key) - like \"Mummy ki medicines\", \"Papa ke documents\"\n- Each shelf contains a box (record) with:\n  - The actual items (value) - like \"Crocin tablets\", \"PAN card\"\n  - An expiration date (expiresAt) - like \"Use before Dec 2024\"\n\n**Example storage (very Indian examples):**\n```javascript\nstore.set(\"student_roll_number\", {\n  value: \"12A45\",\n  expiresAt: null  // Never expires (like your roll number)\n});\n\nstore.set(\"online_exam_session\", {\n  value: \"exam_token_xyz\",\n  expiresAt: Date.now() + 7200000  // Expires in 2 hours (like online exam time limit)\n});\n\nstore.set(\"railway_booking_pnr\", {\n  value: \"PNR123456\",\n  expiresAt: Date.now() + 300000  // Expires in 5 minutes (like tatkal booking window)\n});\n```\n\n**Real-world Indian scenarios:**\n- **BookMyShow**: Seat selection expires in 15 minutes\n- **IRCTC**: Payment session expires if you don't pay quickly\n- **Paytm**: Login session expires after some time for security\n- **Swiggy**: Restaurant availability changes every few minutes\n\n## How the Server Works 🖥️\n\n**Perfect Indian Call Center Analogy:**\n\n1. **Server starts:** Opens a customer service center on \"address\" 6379 (Redis's default port)\n2. **Client connects:** Like a customer calling the helpline\n3. **Client sends query:** Customer explains their problem in proper format\n4. **Server understands:** Customer service representative understands the query\n5. **Server processes:** Representative finds the solution in their system\n6. **Server responds:** Representative gives back the answer in proper format\n\n**The complete flow (like a perfect Indian business transaction):**\n```\nCustomer (Redis CLI) \n    ↓ \nCalls helpline (RESP format)\n    ↓ \nCustomer service (Our Server)\n    ↓ \nChecks database (JavaScript Map)\n    ↓ \nFinds answer (Our Server)\n    ↓ \nResponds professionally (RESP format)\n    ↓ \nCustomer satisfied (Redis CLI)\n```\n\n**It's exactly like:**\n- **Calling Airtel customer care**: You speak in Hindi/English, they understand, check your account, and respond\n- **Ordering from Zomato**: You order in the app, restaurant gets it, prepares food, sends back confirmation\n- **Using PhonePe**: You send money, server processes, bank confirms, you get notification\n\n## Running the Server 🚀\n\n**Start the server (basic):**\n```bash\nnode server.js\n```\n\n**Start with configuration (like a professional setup):**\n```bash\nnode server.js --dir /home/username/redis_data --dbfilename indian_app.rdb\n```\n\n**Use Redis CLI to test (try these Indian examples):**\n```bash\n# Basic health check\nredis-cli PING\n\n# Store student information\nredis-cli SET student_name \"Arjun Sharma\"\nredis-cli SET student_class \"12th\"\nredis-cli SET student_city \"Mumbai\"\n\n# Get student information\nredis-cli GET student_name\nredis-cli GET student_class\n\n# Store temporary data (like OTP)\nredis-cli SET login_otp \"123456\" PX 300000  # Expires in 5 minutes\n\n# Store e-commerce data\nredis-cli SET user_cart \"laptop,mouse,keyboard\"\nredis-cli SET payment_session \"razorpay_session_abc123\" PX 900000  # 15 minutes\n\n# Test echo\nredis-cli ECHO \"Jai Hind!\"\nredis-cli ECHO \"Redis Clone working perfectly!\"\n\n# Check configuration\nredis-cli CONFIG GET dir\nredis-cli CONFIG GET dbfilename\n```\n\n**Expected outputs:**\n```\nredis-cli PING\n→ PONG\n\nredis-cli GET student_name\n→ \"Arjun Sharma\"\n\nredis-cli GET login_otp\n→ \"123456\" (if within 5 minutes)\n→ (nil) (if expired)\n\nredis-cli ECHO \"Jai Hind!\"\n→ \"Jai Hind!\"\n```\n\n## Fun Facts! 🎉\n\n1. **Port 6379:** Redis uses this port because it spells \"MERZ\" on old mobile phones (named after an Italian TV actress) - just like how Indians remember mobile numbers using patterns!\n\n2. **In-Memory Storage:** Everything is stored in RAM, so it's super fast but disappears when you restart - like how your phone's RAM clears when you restart it\n\n3. **Real Redis Speed:** Can handle millions of operations per second - faster than counting currency notes in a bank!\n\n4. **Our Clone:** Handles the basic commands just like real Redis - it's like a perfect duplicate key that works in the same lock!\n\n5. **Indian Connection:** Many Indian startups like Paytm, Flipkart, and Zomato use Redis for their high-speed operations\n\n6. **Memory vs Hard Disk:** Redis is like keeping frequently used items on your study table (fast access) vs keeping them in the cupboard (slower access)\n\n**Interesting Indian Tech Facts:**\n- **Flipkart** uses Redis to handle millions of searches during Big Billion Days\n- **Paytm** uses Redis for instant payment processing\n- **Zomato** uses Redis to track delivery boy locations in real-time\n- **Jio** uses Redis-like systems to handle crores of users simultaneously\n\n## What's Missing? 🤷‍♂️\n\nOur clone is simple but missing some Redis features (like a basic smartphone vs iPhone):\n\n**Missing Features:**\n- **Persistence** (saving to disk) - like having a backup of your WhatsApp chats\n- **More data types** (lists, sets, hashes) - like having different types of containers\n- **Pub/Sub** (messaging) - like WhatsApp group notifications\n- **Clustering** (multiple servers) - like having multiple bank branches\n- **Authentication** (passwords) - like having a PIN for your phone\n- **Many more commands** - like having more apps on your phone\n\n**But that's perfectly fine!** \n- We've built the foundation (like building the basic structure of a house)\n- Now you understand how Redis works under the hood\n- You can add more features as you learn\n- Even WhatsApp started with just text messages!\n\n**Indian startup approach:** Start simple, add features gradually, scale when needed! 🚀\n\n## Next Steps 📚\n\nWant to make it better? Try adding:\n1. **DEL command** (delete a key)\n2. **EXISTS command** (check if a key exists)\n3. **KEYS command** (list all keys)\n4. **EXPIRE command** (set expiration on existing keys)\n\nHappy coding! 🚀","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcreator79%2Fredis-mini","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcreator79%2Fredis-mini","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcreator79%2Fredis-mini/lists"}