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

Upstash Thúc Đẩy Tăng Trưởng Nhanh Cho PlanTripAI: Chiến Lược & Câu Chuyện Thành Công

Giới Thiệu

Trong bài viết này, tôi khám phá vai trò then chốt của Upstash trong phát triển PlanTripAI — startup lên kế hoạch chuyến đi dựa trên AI. Việc sử dụng Upstash Redis đã quan trọng trong việc quản lý các khía cạnh cốt lõi: lưu trữ license key cho truy cập user, và lưu/cache nội dung chuyến đi hiệu quả. Hơn nữa, tính năng Rate Limit của Upstash đóng vai trò sống còn bảo vệ hệ thống. Nó quản lý tần suất request hiệu quả, bảo vệ mạnh mẽ chống lại các mối đe dọa bảo mật tiềm ẩn và đảm bảo dịch vụ mượt mà, không gián đoạn cho user.

plantripai.com là AI-based trip planner tạo itinerary cá nhân hóa nhanh chóng dựa trên sở thích user: destination, duration, travel style, budget. Cung cấp tạo itinerary không giới hạn và nhiều format download.

  • @upstash/redis
  • @upstash/ratelimit
  • next.js

Cách Hoạt Động

AI companies thường cung cấp nhiều cách để user thử sản phẩm. Tại PlanTripAI, cung cấp cả freemium và paid plan.

Trong freemium (popular nhất): Mỗi lần user tạo trip không có license hợp lệ, random key mới được generate và lưu trong Redis hash (redis.hset(trip:${key}, data)) kèm nội dung trip. Key này cấp truy cập tạm thời đến trang chi tiết trip. Khi truy cập hết hạn, user quyết định có muốn giữ truy cập vĩnh viễn không.

Freemium users chịu rate limit (fixedWindow) 3 requests / 10 giây, ngăn chặn tấn công tiềm ẩn lên ứng dụng.

Upstash Thúc Đẩy Tăng Trưởng Nhanh Cho PlanTripAI: Chiến Lược & Câu Chuyện Thành Công

Với paid plan: User mua qua payment gateway. Khi transaction thành công, webhook emit success event, key lưu trong Redis làm valid key (redis.set(${licenseKey}, true)).

Khi user có valid license tạo trip: random key vẫn generate và lưu Redis. Thêm vào đó, trip mới lưu trong user object và link với license key của họ.

Paid users hưởng rate limit hào phóng hơn freemium. Tính năng nâng cấp này cung cấp động bằng cách check valid key trong Redis.

Upstash Thúc Đẩy Tăng Trưởng Nhanh Cho PlanTripAI: Chiến Lược & Câu Chuyện Thành Công

Lưu Trữ Dữ Liệu Trip

PlanTripAI dùng Redis lưu trip user tạo. Redis lựa chọn ideal nhờ hiệu quả key-value store nhanh. Vì trip sau khi tạo immutable, dùng hash cho phép lưu metadata cùng key data.

Cấu trúc trip data trong Redis hash:

{
  "itinerary": [
    { "day": "Day 1", "data": [...] }
  ],
  "info": "This itinerary is designed for a city explorer visiting Paris, France for 2 days.",
  "inputs": {
    "city": "Paris, France",
    "days": 2,
    "accommodation": "Paris France Hotel",
    "kind": "city explorer",
    "currency": "USD",
    "budget": 3000,
    "transportation": "bus"
  },
  "createdAt": ...,
  "shareable": false
}

Dùng Upstash Redis API qua HTTP, data lưu trong free Redis database (10,000 requests/ngày free — đủ dùng).

import { Redis } from "@upstash/redis";
const redis = new Redis({
  url: "..." // UPSTASH_REDIS_REST_URL
  token: "..." // UPSTASH_REDIS_REST_TOKEN
});
redis.hset(`trip:${id}`, data);

Lưu Trữ Valid License Keys

Như đã nói, một cách truy cập full features PlanTripAI là paid subscription — mỗi paid user có valid license key lưu Redis. Setup ideal cho validation check nhanh, nhờ Redis efficient key-value DB.

Đánh dấu user valid:

import { Redis } from "@upstash/redis";
const redis = new Redis({
  url: "..." // UPSTASH_REDIS_REST_URL
  token: "..." // UPSTASH_REDIS_REST_TOKEN
});
await redis.set(licenseKey, true);

Verify user valid:

import { Redis } from "@upstash/redis";
const redis = new Redis({
  url: "..." // UPSTASH_REDIS_REST_URL
  token: "..." // UPSTASH_REDIS_REST_TOKEN
});
const redisLicenseKey = await redis.get(licenseKey);
const valid = Boolean(redisLicenseKey);
if (!valid) {
  return new Response(
    JSON.stringify({ message: "The license key is invalid!" }),
    { status: 401 }
  );
}
// successful code here... 

Triển Khai Rate Limits

Tính năng then chốt bảo vệ app là rate limit logic, supported by Upstash Rate Limit. Chi tiết tại đây. Service quan trọng duy trì trải nghiệm mượt mà cho free và paid users, đã thwart tấn công từ malicious users mà không ảnh hưởng app tổng thể.

Code snippet dùng next.js middleware. Quản lý check user IP, quyết định proceed request tiếp theo:

import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const cache = new Map();
const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.fixedWindow(3, "10s"),
  ephemeralCache: cache,
  analytics: true,
});

export default async function middleware(
  request: NextRequest,
  event: NextFetchEvent
): Promise<Response | undefined> {
  const id = request.ip ?? "anonymous";
  const blockeds = [];
  if (blockeds.includes(id.trim())) {
    return new NextResponse(
      JSON.stringify({ message: "Blocked :)" }),
      { status: 429, headers: { "Content-Type": "application/json" } }
    );
  }
  const { success, pending, limit, reset, remaining } = await ratelimit.limit(id);
  event.waitUntil(pending);
  request.headers.set("X-RateLimit-Limit", limit.toString());
  request.headers.set("X-RateLimit-Remaining", remaining.toString());
  request.headers.set("X-RateLimit-Reset", reset.toString());
  return success ? NextResponse.next() : new NextResponse(
    JSON.stringify({ message: "Request cannot be processed! You sent too many requests in a given amount of time." }),
    { status: 429, headers: { "Content-Type": "application/json" } }
  );
}
export const config = {
  matcher: ["/api/generate-trip", "/api/get-license/(.*)"],
};

Lời Kết

Cảm ơn bạn đã đọc! PlanTripAI bắt đầu như side project, từ curiosity tích hợp Upstash Redis với Next.js trong SaaS framework.

Hy vọng bài viết hữu ích và insightful. Câu hỏi/feedback rất welcome. Kết nối Twitter cho queries/comments.