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

Kiến trúc Serverless: AWS Lambda, Upstash Redis & Go cho Ứng dụng Có thể Mở rộng, Hiệu quả Chi phí

Giới thiệu

Nền tảng tính toán serverless rất tuyệt vời, nhưng nếu không có cơ sở dữ liệu serverless thì chúng quá bị giới hạn.

Khi tôi đang xây dựng nền tảng cho khóa học sắp tới "The Elements of CI/CD", tôi muốn một cơ sở dữ liệu serverless vì đã quyết định sử dụng AWS Lambda làm máy chủ cho một số tác vụ. Các yêu cầu của tôi là:

  1. Định giá theo sử dụng (Pay as you go). Tôi không muốn trả tiền theo giờ hoặc theo nút, mà theo mức sử dụng (số request, dung lượng lưu trữ, v.v.). Chi phí phải rất rẻ khi bắt đầu và tăng dần tỷ lệ thuận khi sử dụng tăng.
  2. Độ trễ thấp. Không ai thích phản hồi chậm, nên truy vấn cơ sở dữ liệu phải nhanh từ bên trong các region AWS (ví dụ eu-west-1).
  3. Trải nghiệm nhà phát triển tuyệt vời (DevX). Có giao diện đẹp cho cơ sở dữ liệu mà không phải học thêm một DSL nhỏ lẻ nào, hoặc lãng phí hàng giờ điền form trên web là điều ưu tiên.

Upstash Redis đáp ứng tất cả các yêu cầu trên và làm rất tốt.

  • Định giá theo sử dụng?
    • ✅ Rất rẻ khi bắt đầu, và cũng rẻ khi mở rộng!
  • Độ trễ thấp?
    • ✅ Dưới 1ms độ trễ khi truy vấn từ bên trong AWS Lambda!
  • DevX tuyệt vời?
    • ✅ Là Redis chuẩn. Vậy là xong.

Trong bài viết này, chúng ta sẽ xem cách sử dụng Upstash Redis từ bên trong AWS Lambda, đảm bảo nó đủ nhanh cho nhu cầu của chúng ta, đồng thời giữ cho code có thể bảo trì để test local hoặc triển khai lên nền tảng khác nếu cần.

Chúng ta sẽ triển khai gì?

Để đơn giản, chúng ta sẽ triển khai chỉ 3 API endpoint:

  1. Endpoint GET|POST /login chấp nhận userId làm tham số query trong GET, hoặc bên trong form value gửi với request POST. Endpoint này sẽ tạo session ID, lưu vào Redis, và đặt cookie cho các lần truy cập sau. GET chỉ để dễ test hơn. 🙃
  2. Endpoint GET /lessons/completed yêu cầu người dùng đã đăng nhập (có cookie với session ID) và trả về JSON với tất cả bài học người dùng đã hoàn thành và thời gian.
  3. Endpoint POST /lessons/{lessonSlug}/mark-complete yêu cầu người dùng đã đăng nhập và đánh dấu bài học theo lessonSlug là đã hoàn thành với thời gian hiện tại.

Lưu ý: Code dưới đây thiếu một vài thứ, nên chưa sẵn sàng cho production copy-paste. Ví dụ, nên kiểm tra lessonSlug tồn tại trước khi cập nhật. Endpoint login cũng nên chấp nhận mật khẩu và xác thực salt/hash đúng cách trước khi tạo session ID, v.v.

1. Thiết lập

  • Code hoàn chỉnh bên dưới cũng tồn tại trong repository aws-playground của tôi nếu bạn muốn xem cách mọi thứ kết nối với nhau.

Như bạn sẽ thấy, chúng ta tạo hai entrypoint, tức là hai lệnh thực thi. Một cho server local thông thường, một cho AWS Lambda. Cách này cho phép test toàn bộ logic local, và dùng unit/integration test chuẩn nếu muốn.

Sự khác biệt duy nhất giữa chúng được trình bày ở mục 1.2 và 1.3 bên dưới.

1.1 Workspace

Trước khi đi vào code, hãy thiết lập thư mục làm việc cho Go.

  1. Tải Go.
  2. Tạo tài khoản và database Upstash Redis ở region bạn chọn. Tốt nhất nên trùng region AWS Lambda bạn sẽ deploy. Tôi dùng eu-west-1 (Europe, Ireland) trong bài này.

Kiến trúc Serverless: AWS Lambda, Upstash Redis & Go cho Ứng dụng Có thể Mở rộng, Hiệu quả Chi phí

Sau khi xong, tạo workspace. Giả sử code ở ~/dev/aws-lambda-upstash-redis.

mkdir -p ~/dev/aws-lambda-upstash-redis
cd ~/dev/aws-lambda-upstash-redis

Tạo Go package:

go mod init com.upstash/example/aws-lambda-upstash-redis

1.2 Entrypoint server local

  • Dán code sau vào ~/dev/aws-lambda-upstash-redis/cmd/server/main.go.
package main
import (
    "log"
    "net/http"
    "os"
    "com.upstash/example/aws-lambda-upstash-redis/core"
)
func main() {
    mux := core.NewMux()
    port := os.Getenv("PORT")
    if len(port) == 0 {
        port = "5000"
    }
    if err := http.ListenAndServe(":"+port, mux); err != nil {
        log.Fatal(err)
    }
}

1.3 Entrypoint AWS Lambda

  • Dán code sau vào ~/dev/aws-lambda-upstash-redis/cmd/lambda/main.go.
package main
import (
    "com.upstash/example/aws-lambda-upstash-redis/core"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/awslabs/aws-lambda-go-api-proxy/httpadapter"
)
func main() {
    mux := core.NewMux()
    lambda.Start(httpadapter.NewV2(mux).ProxyWithContext)
}

1.4 Logic lõi (Core logic)

Logic chính sẽ nằm trong package core để chia sẻ cho cả hai entrypoint trên.

  • Dán code sau vào ~/dev/aws-lambda-upstash-redis/core/lib.go.
package core
import (
    "github.com/go-chi/chi/v5"
)
func NewMux() *chi.Mux {
    r := chi.NewRouter()
    return r
}

1.5 Build / Compile

Tôi thường viết makefile nhỏ để tránh gõ lệnh dài mỗi khi compile. Copy sau vào ~/dev/aws-lambda-upstash-redis/makefile:

default: build
clean: rm -rf build/
build: build-lambda build-server
build-lambda: clean
    GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o build/handler cmd/lambda/main.go
    cd build/ && zip handler.zip ./handler
build-server: clean
    CGO_ENABLED=0 go build -o build/server cmd/server/main.go

Đừng lo chi tiết, makefile cho phép:

  • make build-server: Build binary chạy server local (file ./build/server).
  • make build-lambda: Build binary cho AWS Lambda (file ./build/handler và ./build/handler.zip).
  • make hoặc make build làm cả hai.

Tùy chọn CGO_ENABLED=0 đảm bảo binary tự chứa (static compile). GOOS=linux GOARCH=amd64 cần thiết để cross-compile cho môi trường Linux của AWS Lambda nếu bạn dùng Mac/Windows local.

Chạy go mod tidy để tải dependencies. Nhớ chạy mỗi khi thêm/xóa dependency Go.

Cuối cùng, chạy make một lần để build mọi thứ và kiểm tra workspace trước khi đi sâu vào code.

2. Triển khai API

Phần này luôn làm việc trong file ~/dev/aws-lambda-upstash-redis/core/lib.go.

Dưới đây định nghĩa các API endpoint, dùng thư viện tuyệt vời go-chi.

import (
    //...
    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
)
func NewMux() *chi.Mux {
    r := chi.NewRouter()
    r.Use(middleware.RequestID)
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)
    r.Get("/login", login)
    r.Post("/login", login)
    r.Group(func(r chi.Router) {
        r.Use(UsersWithSessionOnly)
        r.Get("/lessons/completed", listLessonsCompleted)
        r.Post("/lessons/{lessonSlug}/mark-complete", markLessonComplete)
    })
    return r
}

Trong snippet trên, r.Group(...) tạo layer chung để áp dụng middleware chung cho các route bên trong. Ở đây thêm middleware tự viết UsersWithSessionOnly, đảm bảo request chứa cookie với session ID hoạt động.

2.1 Middleware UsersWithSessionOnly

Middleware này thực hiện:

  1. Trích xuất cookie chứa session ID, fail nếu không có.
  2. Truy vấn Redis lấy chi tiết user dựa trên session ID, fail nếu session ID không hoạt động.
  3. Lưu user ID vào context.Context của request để middleware/handler phía sau dùng.

Trước hết, cần boilerplate cho imports và định nghĩa dùng chung.

import (
    //...
    "log"
    "os"
    "strings"
    "github.com/go-redis/redis/v8"
)
type contextKey struct { name string }
const (
    COOKIE_AUTH_NAME = "xxx_session_id"
)
var (
    CTX_USER_ID = &contextKey{"LoggedInUserId"}
    redisDb = NewClient()
)
func NewClient() *redis.Client {
    redisUrl := strings.TrimSpace(os.Getenv("UPSTASH_REDIS_URL"))
    if redisUrl == "" {
        log.Fatalln("Required env UPSTASH_REDIS_URL not set!")
    }
    opt, _ := redis.ParseURL(redisUrl)
    redisDb := redis.NewClient(opt)
    return redisDb
}

Logic chính cho middleware xác thực:

// UsersWithSessionOnly middleware giới hạn truy cập chỉ cho user đã đăng nhập.
// Nếu validation pass, context sẽ chứa user id (CTX_USER_ID).
func UsersWithSessionOnly(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        c, err := r.Cookie(COOKIE_AUTH_NAME)
        if err != nil {
            render.Status(r, http.StatusForbidden)
            render.JSON(w, r, struct{}{})
            return
        }
        ctx := r.Context()
        userId, err := redisDb.Get(ctx, "session:"+c.Value).Result()
        if err == redis.Nil {
            // Session không tìm thấy -> user bị cấm truy cập API!
            render.Status(r, http.StatusForbidden)
            render.JSON(w, r, struct{}{})
            return
        } else if err != nil {
            // Lỗi khi query Redis!
            render.Status(r, http.StatusInternalServerError)
            render.JSON(w, r, struct{ Message string }{Message: "We could not validate the provided session ID"})
            return
        }
        // Set cho middleware và handler phía sau.
        next.ServeHTTP(w, r.WithContext(context.WithValue(ctx, CTX_USER_ID, userId)))
    })
}

2.2 markLessonComplete(...)

Thao tác đơn giản: lưu vào Redis rằng bài học theo lessonSlug path parameter đã hoàn thành lúc request.

Trong Redis, giữ một map cho mỗi user, key-value là lesson và ngày hoàn thành. Dùng lệnh HSET Redis. Cũng có thể lưu key riêng cho mỗi lesson nhưng cách này dễ lấy tất cả bài học của user cùng lúc.

func markLessonComplete(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    lessonSlug := chi.URLParam(r, "lessonSlug")
    userId := r.Context().Value(CTX_USER_ID).(string)
    timeNow := time.Now().Format(time.RFC3339)
    err := redisDb.HSet(ctx, "lessons:"+userId, lessonSlug, timeNow).Err()
    if err != nil {
        render.Status(r, http.StatusInternalServerError)
        render.JSON(w, r, struct{ Message string }{Message: "We could not save your progression..."})
        return
    }
    render.JSON(w, r, struct {
        LessonSlug string
        LastCompleted string
    }{
        lessonSlug, timeNow,
    })
}

2.3 listLessonsCompleted(...)

Tương tự, trả về toàn bộ map hoàn thành bài học dạng JSON. Dùng lệnh HGETALL.

func listLessonsCompleted(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    userId := r.Context().Value(CTX_USER_ID).(string)
    lessons, err := redisDb.HGetAll(ctx, "lessons:"+userId).Result()
    if err == redis.Nil {
        lessons = map[string]string{}
    } else if err != nil {
        render.Status(r, http.StatusInternalServerError)
        render.JSON(w, r, struct{ Message string }{Message: "We could not load your lessons..."})
        return
    }
    render.JSON(w, r, struct {
        Lessons map[string]string
    }{
        lessons,
    })
}

2.4 login(...)

Endpoint login. Lại nhắc: đừng copy code này vào production vì không làm validation. Chỉ quan tâm cách query Redis và set cookie session ID.

Session ID sinh bởi thư viện ksuid, có ưu điểm so với UUID thường, và chỉ coi active 1 giờ. Dùng TTL của lệnh SET Redis để tự xóa khỏi DB sau 1 giờ.

import (
    // ...
    "github.com/segmentio/ksuid"
)
func login(w http.ResponseWriter, r *http.Request) {
    // Check credentials và update redis session và return Set-Cookie
    // WARNING: Nên làm validation thật trong production cho credentials!
    // ...
    // Tạm thời luôn giả định đúng và tự tạo session token
    // bằng cách lưu vào Redis, và set làm cookie.
    userId := strings.TrimSpace(r.FormValue("userId"))
    if userId == "" {
        render.Status(r, http.StatusBadRequest)
        render.JSON(w, r, struct{ Message string }{Message: "Missing required userId"})
        return
    }
    sessionId := ksuid.New()
    redisDb.Set(r.Context(), "session:"+sessionId.String(), userId, time.Hour*1)
    http.SetCookie(w, &http.Cookie{
        Name: COOKIE_AUTH_NAME,
        Value: sessionId.String(),
        Path: "/",
        MaxAge: int((time.Hour * 1).Seconds()),
        // Nên true khi deploy production (https), nhưng local cần false (http).
        Secure: false,
    })
    http.Redirect(w, r, "/lessons/completed", http.StatusTemporaryRedirect)
}

3. Demo - Local

Phù, nhiều code quá. 😅

Demo nhanh để chắc chắn mọi thứ chạy đúng.

  • Đặt biến môi trường UPSTASH_REDIS_URL thành URL database bạn tạo ở mục 1. Tìm ở tab Details của trang database (xem mục 1.1).
export UPSTASH_REDIS_URL=""
  • Build và chạy server local:
make build-server && ./build/server

Test trên trình duyệt

Truy cập https://localhost:5000/lessons/completed.

Kiến trúc Serverless: AWS Lambda, Upstash Redis & Go cho Ứng dụng Có thể Mở rộng, Hiệu quả Chi phí

Nhận 403 - Forbidden, thử login bằng https://localhost:5000/login?userId=lambros.

Kiến trúc Serverless: AWS Lambda, Upstash Redis & Go cho Ứng dụng Có thể Mở rộng, Hiệu quả Chi phí

Đã login, tự redirect đến /lessons/completed, nhưng rỗng. Đánh dấu bài học hoàn thành. Mở tab console trong devtools trình duyệt chạy:

await ( await fetch("https://localhost:5000/lessons/123/mark-complete", { method: "POST", credentials: "same-origin", }) ).json();
// Output ví dụ:
// {LessonSlug: '123', LastCompleted: '2022-10-12T02:01:14+03:00'}

Truy cập https://localhost:5000/lessons/completed sẽ thấy bài học đã đánh dấu:

{
  "Lessons": {
    "123": "2022-10-12T02:01:14+03:00"
  }
}

Xong. Mọi thứ chạy ngon!

Kiểm tra database Redis qua Data Browser online mới ra mắt cũng chứng minh data đúng chỗ.

Kiến trúc Serverless: AWS Lambda, Upstash Redis & Go cho Ứng dụng Có thể Mở rộng, Hiệu quả Chi phí

4. AWS Lambda

Để test và deploy lên AWS Lambda, dùng sam cli.

  • Cài SAM cli và đảm bảo user/role có quyền đúng.
  • SAM cli cần Cloudformation template, copy sau vào aws-iac/sam-template.yml:
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Defines all the AWS resources we need for our Upstash Redis API.
Resources:
  GoUpstashRedis:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ../build/handler.zip
      Handler: handler
      Runtime: go1.x
      MemorySize: 512
      FunctionUrlConfig:
        AuthType: NONE
        Cors:
          AllowCredentials: false
          AllowMethods: ["*"]
          AllowOrigins: ["*"]
Outputs:
  GoUpstashRedisApi:
    Description: "Endpoint URL"
    Value: !GetAtt GoUpstashRedisUrl.FunctionUrl
  GoUpstashRedis:
    Description: "Lambda Function ARN"
    Value: !GetAtt GoUpstashRedis.Arn
  GoUpstashRedisIamRole:
    Description: "Implicit IAM Role created for GoUpstashRedis"
    Value: !GetAtt GoUpstashRedisRole.Arn
  • Build handler bundle cho AWS Lambda:
make build-lambda
  • Thêm vào makefile để deploy dễ dàng sau khi đổi code:
sam-deploy: build-lambda
    sam deploy -t aws-iac/sam-template.yml --stack-name "UpstashRedisGoArticleStackDemo" --region eu-west-1 --resolve-s3 --no-confirm-changeset --no-fail-on-empty-changeset --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND
  • Deploy lên region chỉ định (xem lệnh trước).
make sam-deploy
  • Output sẽ hiện URL AWS Lambda deployed, ví dụ https://6pmmwqmg5vec3bcsldabckaf5i0nlgje.lambda-url.eu-west-1.on.aws/. Lặp lại các bước demo trên trình duyệt thay localhost bằng domain thực.
  • Hoặc tìm URL trong outputs của CloudFormation stack UpstashRedisGoArticleStackDemo trên console Cloudformation.
  • Lưu ý: Phải set biến môi trường UPSTASH_REDIS_URL trên config AWS Lambda, nếu không sẽ crash. Vào AWS Lambda console, click Lambda mới deploy, tab Configuration, menu trái click Environment variables. Key UPSTASH_REDIS_URL, value là Upstash Redis URL. Click Save, Lambda sẵn sàng.

4.1 Test SAM local

Test Lambda local bằng file sample-event.json với path/cookie/query params đúng. Ví dụ JSON ở aws-lambda-upstash-redis-article/sample-event.json.

  • Chạy lệnh sau để invoke logic server như trên AWS Lambda:
sam local invoke -t aws-iac/sam-template.yml -e sample-event.json

4.2 Bảo mật Upstash Redis URL

Bài này đơn giản hóa bằng cách cung cấp Upstash Redis URL (chứa password) qua biến môi trường. Không muốn hardcode vào SAM Cloudformation template (được version cùng code), nên phải config thủ công qua AWS Lambda console.

Cách tốt hơn: dùng AWS Systems Manager Parameter Store và resource Cloudformation AWS::SSM::Parameter để giữ URL (set một lần, giữ lại khi deploy), và đổi code Lambda để lấy giá trị parameter lúc runtime. Cũng có thể inject tự động làm env variable trong sam-template.yml, tuy vẫn plain text trên console.

Đổi code lấy từ SSM Parameter Store dễ dàng nhờ tách entrypoint, nên có thể fetch parameter chỉ khi chạy trong AWS Lambda (~/dev/aws-lambda-upstash-redis/cmd/lambda/main.go) và truyền vào hàm NewClient() tạo Redis client.

5. Nhanh như nào?

Ngoài lần invoke cold start đầu tiên mất khoảng 100-120 ms, mọi invoke sau đó cực nhanh và luôn dưới 4 ms.

Ví dụ hot invocation cho endpoint /login?userId=lambros như triển khai trên:

Kiến trúc Serverless: AWS Lambda, Upstash Redis & Go cho Ứng dụng Có thể Mở rộng, Hiệu quả Chi phí

Tổng duration request là 2.06 ms. Đúng, hai milliseconds, để sinh session ID, ghi vào Upstash Redis remote, và trả response redirect.

Xem kỹ phần Log output, request kéo dài 789.435μs từ góc nhìn code. Tức logic hoàn thành dưới 1 ms (khoảng 0.790 ms). Sốc nghĩ đến việc dùng database remote. 🤯

Kết luận

Tôi thực sự ngạc nhiên về hiệu năng Upstash Redis, nhất là vì khó tìm database serverless hiệu năng này cho platform như AWS Lambda.

API Redis rất tiện, Upstash Redis có mô hình giá top, DevX tuyệt vời, và nhanh. Tôi yêu combo này!

AWS Lambda + Upstash Redis + Go = 🚀❤️