Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Xây dựng URL Shortener High-Performance với Node.js và Redis Distributed Caching

Xây dựng URL Shortener High-Performance với Node.js và Redis Distributed Caching

Trong tutorial này, chúng ta sẽ build một scalable URL shortening service dùng Node.js và Redis. Service sẽ tận dụng distributed caching để handle high traffic efficiently, giảm latency, và scale seamless. Chúng ta sẽ explore key concepts như consistent hashing, cache invalidation strategies, và sharding để đảm bảo system vẫn fast và reliable.

Cuối guide, bạn sẽ có fully functional URL shortener service dùng distributed caching optimize performance. Chúng ta cũng tạo interactive demo nơi user input URLs và xem real-time metrics như cache hits và misses.

What You Will Learn

  • Cách build URL shortener service dùng Node.js và Redis.

  • Cách implement distributed caching optimize performance.

  • Hiểu consistent hashing và cache invalidation strategies.

  • Dùng Docker simulate multiple Redis instances cho sharding và scaling.

Prerequisites

Trước khi bắt đầu, đảm bảo bạn có installed:

  • Node.js (v14 hoặc cao hơn)

  • Redis

  • Docker

  • Kiến thức cơ bản JavaScript, Node.js, và Redis.

Mục lục

  • Project Overview

  • Step 1: Setting Up the Project

  • Step 2: Setting Up Redis Instances

  • Step 3: Implementing the URL Shortener Service

  • Step 4: Implementing Cache Invalidation

  • Step 5: Monitoring Cache Metrics

  • Step 6: Testing the Application

  • Conclusion: What You've Learned

Project Overview

Chúng ta build URL shortener service nơi:

  1. Users có thể shorten long URLs và retrieve original URLs.

  2. Service dùng Redis caching lưu mappings giữa shortened URLs và original URLs.

  3. Cache distributed across multiple Redis instances handle high traffic.

  4. System demo cache hits và misses real-time.

System Architecture

Đảm bảo scalability và performance, chia service thành components:

  1. API Server: Handle requests shortening và retrieving URLs.

  2. Redis Caching Layer: Dùng multiple Redis instances cho distributed caching.

  3. Docker: Simulate distributed environment với multiple Redis containers.

Step 1: Setting Up the Project

Setup project bằng cách init Node.js application:

mkdir scalable-url-shortener
cd scalable-url-shortener
npm init -y

Cài necessary dependencies:

npm install express redis shortid dotenv
  • express: Lightweight web server framework.

  • redis: Handle caching.

  • shortid: Generate short, unique IDs.

  • dotenv: Manage environment variables.

Tạo .env file ở root project:

PORT=3000
REDIS_HOST_1=localhost
REDIS_PORT_1=6379
REDIS_HOST_2=localhost
REDIS_PORT_2=6380
REDIS_HOST_3=localhost
REDIS_PORT_3=6381

Variables này define Redis hosts và ports chúng ta dùng.

Step 2: Setting Up Redis Instances

Dùng Docker simulate distributed environment với multiple Redis instances.

Chạy commands sau start ba Redis containers:

docker run -p 6379:6379 --name redis1 -d redis
docker run -p 6380:6379 --name redis2 -d redis
docker run -p 6381:6379 --name redis3 -d redis

Điều này setup ba Redis instances chạy different ports. Chúng ta dùng implement consistent hashing và sharding.

Step 3: Implementing the URL Shortener Service

Tạo main application file, index.js:

require('dotenv').config();
const express = require('express');
const redis = require('redis');
const shortid = require('shortid');
const app = express();
app.use(express.json());
const redisClients = [
    redis.createClient({ host: process.env.REDIS_HOST_1, port: process.env.REDIS_PORT_1 }),
    redis.createClient({ host: process.env.REDIS_HOST_2, port: process.env.REDIS_PORT_2 }),
    redis.createClient({ host: process.env.REDIS_HOST_3, port: process.env.REDIS_PORT_3 })
];
// Hash function distribute keys among Redis clients
function getRedisClient(key) {
    const hash = key.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
    return redisClients[hash % redisClients.length];
}
// Endpoint shorten a URL
app.post('/shorten', async (req, res) => {
    const { url } = req.body;
    if (!url) return res.status(400).send('URL is required');
    const shortId = shortid.generate();
    const redisClient = getRedisClient(shortId);
    await redisClient.set(shortId, url);
    res.json({ shortUrl: `https://localhost:${process.env.PORT}/${shortId}` });
});
// Endpoint retrieve original URL
app.get('/:shortId', async (req, res) => {
    const { shortId } = req.params;
    const redisClient = getRedisClient(shortId);
    redisClient.get(shortId, (err, url) => {
        if (err || !url) {
            return res.status(404).send('URL not found');
        }
        res.redirect(url);
    });
});
app.listen(process.env.PORT, () => {
    console.log(`Server running on port ${process.env.PORT}`);
});

Như thấy code, chúng ta có:

  1. Consistent Hashing:

    • Distribute keys (shortened URLs) across multiple Redis clients dùng simple hash function.
    • Hash function đảm bảo URLs distributed evenly across Redis instances.
  2. URL Shortening:

    • /shorten endpoint chấp nhận long URL và generate short ID dùng shortid library.
    • Shortened URL lưu trong một Redis instances dùng hash function.
  3. URL Redirection:

    • /:shortId endpoint retrieve original URL từ cache và redirect user.
    • Nếu URL không tìm thấy trong cache, trả 404 response.

Step 4: Implementing Cache Invalidation

Trong real-world application, URLs có thể expire hoặc thay đổi theo thời gian. Handle này, cần implement cache invalidation.

Adding Expiry to Cached URLs

Modify index.js set expiration time cho mỗi cached entry:

// Endpoint shorten a URL with expiration
app.post('/shorten', async (req, res) => {
    const { url, ttl } = req.body; // ttl (time-to-live) is optional
    if (!url) return res.status(400).send('URL is required');
    const shortId = shortid.generate();
    const redisClient = getRedisClient(shortId);
    await redisClient.set(shortId, url, 'EX', ttl || 3600); // Default TTL 1 hour
    res.json({ shortUrl: `https://localhost:${process.env.PORT}/${shortId}` });
});
  • TTL (Time-To-Live): Set default expiration time 1 hour cho mỗi shortened URL. Bạn customize TTL cho mỗi URL nếu cần.

  • Cache Invalidation: Khi TTL expires, entry tự động removed từ cache.

Step 5: Monitoring Cache Metrics

Monitor cache hits và misses, thêm logging vào endpoints trong index.js:

app.get('/:shortId', async (req, res) => {
    const { shortId } = req.params;
    const redisClient = getRedisClient(shortId);
    redisClient.get(shortId, (err, url) => {
        if (err || !url) {
            console.log(`Cache miss for key: ${shortId}`);
            return res.status(404).send('URL not found');
        }
        console.log(`Cache hit for key: ${shortId}`);
        res.redirect(url);
    });
});

Đang xảy ra trong code:

  • Cache Hits: Nếu URL tìm thấy trong cache, là cache hit.

  • Cache Misses: Nếu URL không tìm thấy, là cache miss.

  • Logging này giúp monitor performance của distributed cache.

Step 6: Testing the Application

  1. Start Redis instances:
docker start redis1 redis2 redis3
  1. Run Node.js server:
node index.js
  1. Test endpoints dùng curl hoặc Postman:

    • Shorten a URL:

      POST https://localhost:3000/shorten
      Body: { "url": "https://example.com" }
    • Access shortened URL:

      GET https://localhost:3000/{shortId}

Conclusion: What You've Learned

Chúc mừng! Bạn đã successfully built scalable URL shortener service với distributed caching dùng Node.js và Redis. Throughout tutorial, bạn học cách:

  1. Implement consistent hashing distribute cache entries across multiple Redis instances.

  2. Optimize application với cache invalidation strategies giữ data up-to-date.

  3. Dùng Docker simulate distributed environment với multiple Redis nodes.

  4. Monitor cache hits and misses optimize performance.

Next Steps:

  • Add a Database: Store URLs trong database cho persistence beyond cache.

  • Implement Analytics: Track click counts và analytics cho shortened URLs.

  • Deploy to the Cloud: Deploy application dùng Kubernetes cho auto-scaling và resilience.

Happy coding!

Học code miễn phí. Chương trình open source freeCodeCamp đã giúp hơn 40.000 người có việc developer. Bắt đầu ngay