Feature flagging đã thay đổi paradigm cách backend developers test và modify những gì họ build. Với feature flags, chúng ta có thể enable/disable feature hoặc thay đổi functionality on the fly bằng single click (không cần redeploy).
Trong tutorial này, chúng ta sẽ thấy feature flags giúp enable/disable feature/một phần code khi muốn từ UI, không cần redeploy toàn bộ code.
Để hiểu sâu hơn, chúng ta sẽ build app từ đầu, xem feature flagging capabilities, và dùng tool tên Flagsmith quản lý created feature flags từ single dashboard.
Nội dung bao gồm:
Yêu cầu trước
Feature Flag là gì?
Feature Flags cho Backend Development
Tại sao dùng Open Source Tools?
Let's Code!
Khởi tạo tools
Tạo endpoints cho API
Cách thêm Feature Flagging
Hiểu logic code Feature Flag
Cách tạo Feature Flags trong Flagsmith Dashboard
Rate Limiting Feature Flag
Beta Feature Flag
Lấy Access Key
Chạy API
Cập nhật rate_limit Flag
Cách tích hợp Feature Flags với GitHub App
Test Flagsmith GitHub App
Kết luận
Yêu cầu trước
Golang installed và medium-level understanding.
Running Redis instance (Remote hoặc local)
Flagsmith Account (Free. Sẽ cover sau.)
Feature Flag là gì?
Feature Flag là kỹ thuật development cho phép teams bật/tắt features không modify source code hoặc redeploy.
Để đơn giản hơn, nghĩ chúng giống conditional statements (ví dụ if-else): dựa trên true/false, quyết định code path sẽ execute.
Feature Flags cho Backend Development
Bạn có thể thấy feature flags dùng trong frontends và websites, nhưng còn nhiều hơn thế. Bạn dùng server-side để modify functionality của API, như modify/set rate limit, thay đổi API endpoint functionality hoặc tắt hoàn toàn. Là backend developers, chúng ta có thể level up testing với feature flags.
Để demo, chúng ta sẽ build demo app. App được curated show feature flagging capabilities từ modify functionality (rate limit) on the fly đến thêm endpoint mới cho API cho beta testing hoặc initial rolling. Chúng ta dùng toàn bộ open-source tools!
Chúng ta dùng open source tools build app này (Golang, Redis, Flagsmith). Open source mang lại transparency, trust và encourage collaboration với global community backend developers.
Bằng cách integrate open source tools, chúng ta có full visibility khi build và test. Ví dụ, integrate feature flags với GitHub, cho phép track lifecycle của feature bằng cách link Flagsmith feature flag với GitHub Pull Request hoặc Issue. Điều này giúp stay updated với changes features không cần manually track mỗi modification. Chúng ta dễ dàng track status features across different environments.
Let's Code!
Trong tutorial, bạn sẽ thấy functionality app thay đổi trước và sau test với feature flagging mechanisms. Tools và frameworks: Golang, Docker, Redis, Flagsmith, GitHub. Tất cả open source và free tạo account test.
Để bắt đầu, mở IDE yêu thích, init Golang project, copy code dưới vào file main.go. Sau đó chạy go mod tidy cài dependencies.
Hiểu gì đang xảy ra trong code snippet:
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis_rate/v10"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
)
var (
redisClient *redis.Client
limiter *redis_rate.Limiter
)
func initClients() {
redisClient = redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS_URL"),
})
limiter = redis_rate.NewLimiter(redisClient)
}
func main() {
err := godotenv.Load()
if err != nil {
log.Printf("Loading environment variable from the host system")
} else {
log.Printf("Loading environment from .env file")
}
initClients()
defer redisClient.Close()
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
err, remainingLimit := rateLimitCall(c.ClientIP())
if err != nil {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Rate Limit Hit"})
} else {
c.JSON(http.StatusOK, gin.H{"Your left over API request is": remainingLimit})
}
})
r.GET("/beta", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "This is beta endpoint"})
})
r.Run(":" + os.Getenv("PORT"))
}
func rateLimitCall(ClientIP string) (error, int) {
ctx := context.Background()
rateLimitString := os.Getenv("RATE_LIMIT")
RATE_LIMIT, _ := strconv.Atoi(rateLimitString)
res, err := limiter.Allow(ctx, ClientIP, redis_rate.PerHour(RATE_LIMIT))
if err != nil {
panic(err)
}
if res.Remaining == 0 {
return errors.New("You have hit the Rate Limit for the API. Try again later"), 0
}
fmt.Println("remaining request for", ClientIP, "is", res.Remaining)
return nil, res.Remaining
}
Khởi tạo Tools
func initClients() {
redisClient = redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS_URL"),
})
limiter = redis_rate.NewLimiter(redisClient)
}
func main() {
err := godotenv.Load()
if err != nil {
log.Printf("Loading environment variable from the host system")
} else {
log.Printf("Loading environment from .env file")
}
initClients()
defer redisClient.Close()
r := gin.Default()
... })
Ở top, khai báo variables lưu Redis và Rate limiter clients để reuse và init một lần. Khởi tạo trong initClients().
Trong main(), load env variables từ system hoặc .env file. Gọi initClients(). Tạo clients lưu vào variables.
Tiếp theo, tạo Gin router handle incoming requests. Environment variables cần trong file .env. Demo này cần Redis instance running lưu data cho rate-limiting. Dùng Docker hoặc remote machine – nhớ update REDIS_URL accordingly. Tôi dùng Docker.
Cũng có thể lấy tất cả env variables từ feature flags, nhưng không làm ở đây.
REDIS_URL=localhost:6379
PORT=8080
RATE_LIMIT=10
Tạo Endpoints cho API
r.GET("/ping", func(c *gin.Context) {
err, remainingLimit := rateLimitCall(c.ClientIP())
if err != nil {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Rate Limit Hit"})
} else {
c.JSON(http.StatusOK, gin.H{"Your left over API request is": remainingLimit})
}
})
r.GET("/beta", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "This is beta endpoint"})
})
r.Run(":" + os.Getenv("PORT"))
Tạo hai GET endpoints, /ping và /beta. Mỗi lần hit /ping gọi rateLimitCall(). Nó check và set rate limit incoming requests từ IP address. Tất cả lưu trong Redis instance.
Vì vậy, user tương tác /ping lần đầu sẽ tạo entry với limit 10 per hour. Số limit 10 từ RATE_LIMIT set, hourly refresh từ function redis_rate.PerHour(RATE_LIMIT).
Check remaining limit. Nếu còn, trả message với số request còn lại. Nếu hit cap, trả message báo limit.
Ngoài /ping, có endpoint /beta. Trả message đơn giản, sau sẽ thấy dùng feature flags bật/tắt hoàn toàn endpoint này.
Cách thêm Feature Flagging
Giờ thêm feature flagging capabilities vào app. Dùng Flagsmith. Flagsmith là open source software cho phép dễ dàng tạo và manage feature flags across web, mobile, server-side apps.
Dùng Flagsmith, wrap features trong flag và toggle on/off cho different environments, users, hoặc user segments. Manage tất cả từ Flagsmith dashboard không cần redeploy.
Cài Flagsmith package:
go get github.com/Flagsmith/flagsmith-go-client/v3
Import package với alias flagsmith. Dưới là updated functionality sau apply feature flagging vào code hiện có.
Hiểu changes chúng ta làm (giải thích dưới code):
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
flagsmith "github.com/Flagsmith/flagsmith-go-client/v3"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis_rate/v10"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
)
var (
redisClient *redis.Client
limiter *redis_rate.Limiter
flagsmithClient *flagsmith.Client
)
func initClients() {
redisClient = redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS_URL"),
})
limiter = redis_rate.NewLimiter(redisClient)
flagsmithClient = flagsmith.NewClient(os.Getenv("FLAGSMITH_ENVIRONMENT_KEY"))
}
func main() {
err := godotenv.Load()
if err != nil {
log.Printf("Loading environment variable from the host system")
} else {
log.Printf("Loading environment from .env file")
}
initClients()
defer redisClient.Close()
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
err, remainingLimit := rateLimitCall(c.ClientIP())
if err != nil {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Rate Limit Hit"})
} else {
c.JSON(http.StatusOK, gin.H{"Your left over API request is": remainingLimit})
}
})
r.GET("/beta", func(c *gin.Context) {
flags := getFeatureFlags()
isEnabled, _ := flags.IsFeatureEnabled("beta")
if isEnabled {
c.JSON(http.StatusOK, gin.H{"message": "This is beta endpoint"})
} else {
c.String(http.StatusNotFound, "404 page not found")
}
})
r.Run(":" + os.Getenv("PORT"))
}
func rateLimitCall(ClientIP string) (error, int) {
ctx := context.Background()
flags := getFeatureFlags()
rateLimitInterface, _ := flags.GetFeatureValue("rate_limit")
RATE_LIMIT := int(rateLimitInterface.(float64))
fmt.Println("Current Rate Limit is", RATE_LIMIT)
res, err := limiter.Allow(ctx, ClientIP, redis_rate.PerHour(RATE_LIMIT))
if err != nil {
panic(err)
}
if res.Remaining == 0 {
return errors.New("You have hit the Rate Limit for the API. Try again later"), 0
}
fmt.Println("remaining request for", ClientIP, "is", res.Remaining)
return nil, res.Remaining
}
func getFeatureFlags() flagsmith.Flags {
ctx := context.Background()
flags, _ := flagsmithClient.GetEnvironmentFlags(ctx)
return flags
}
Hiểu Feature Flag Code Logic
func getFeatureFlags() flagsmith.Flags {
ctx := context.Background()
flags, _ := flagsmithClient.GetEnvironmentFlags(ctx)
return flags
}
Trước, jump vào function getFeatureFlags() mới tạo ở bottom. Function này return tất cả flags tạo trên Flagsmith dashboard, bằng cách gọi method GetEnvironmentFlags() trên flagsmithClient.
Chúng ta initiated flagsmithClient trong initClients(). Flagsmith Client cần access key (function NewClient()) lấy từ Flagsmith dashboard. Giống Redis và Limter clients, lưu client trong global variable để reuse. Dashboard, tạo flags, lấy key sẽ hiểu ở các bước sau.
func rateLimitCall(ClientIP string) (error, int) {
ctx := context.Background()
flags := getFeatureFlags()
rateLimitInterface, _ := flags.GetFeatureValue("rate_limit")
RATE_LIMIT := int(rateLimitInterface.(float64))
fmt.Println("Current Rate Limit is", RATE_LIMIT)
res, err := limiter.Allow(ctx, ClientIP, redis_rate.PerHour(RATE_LIMIT))
if err != nil {
panic(err)
}
if res.Remaining == 0 {
return errors.New("You have hit the Rate Limit for the API. Try again later"), 0
}
fmt.Println("remaining request for", ClientIP, "is", res.Remaining)
return nil, res.Remaining
}
Giờ rateLimitCall(), thay vì lấy RATE_LIMIT từ env, lấy value từ flag rate_limit (sẽ tạo sau). Gọi getFeatureFlags() lấy flag rate_limit value từ tất cả flags.
Bằng cách set as feature flags, chúng ta dynamic change limit bất kỳ lúc nào từ dashboard. Không cần đổi code functionality hoặc cách truyền thống đổi RATE_LIMIT value và re-run server catch updated values.
r.GET("/beta", func(c *gin.Context) {
flags := getFeatureFlags()
isEnabled, _ := flags.IsFeatureEnabled("beta")
if isEnabled {
c.JSON(http.StatusOK, gin.H{"message": "This is beta endpoint"})
} else {
c.String(http.StatusNotFound, "404 page not found")
}
})
Giờ /beta endpoint, based trên beta flag enabled/disabled, endpoint sẽ serve query. Ngược lại, act như non-reachable endpoint trả 404 error.
Trong ví dụ, thêm placeholder message basic show cách hoạt động, nhưng mở possibilities mới trong testing và initial releases (beta). Nếu API có endpoint mới, wrap functionality trong feature flag và make available/unavailable với single click. Cũng làm được nhiều hơn như scheduling và canary releases.
File .env sẽ trông như sau. Đã xóa RATE_LIMIT thêm FLAGSMITH_ENVIRONMENT_KEY.
REDIS_URL=localhost:6379
PORT=8080
FLAGSMITH_ENVIRONMENT_KEY=ser.ZRd***********469
Cách tạo Feature Flags trong Flagsmith Dashboard
Đến Flagsmith dashboard tạo flags dùng ở trên và lấy access key. Nếu chưa có account Flagsmith, sign up free here.
Sau sign up, prompted tạo organisation và project. Project separation tốt, giúp isolate logic cho different projects. Xong, thấy dashboard như screenshot.
Nhiều functionalities từ integrations đến scheduling flags để compare changes. Ngoài Go, Flagsmith cung cấp nhiều SDKs. Click chỗ viết language name sẽ cho boilerplate code cho language đó.

Rate Limiting Feature Flag
Tạo feature flag đầu cho rate limit. Click nút Create Feature top right. Sidebar window mở. Set name, để flag turn on đúng cách khi tạo, chọn Enabled by default.
Phần value, set flag value. Chấp nhận formats như Txt, JSON, XML... Vì feature value simple text như 20, 30, chọn Txt (default) set random limit – chọn 20.
Cũng có thể give tags và descriptions. Tags helpful khi filter Feature Flags. Ví dụ, tạo tag backend filter all feature flags related to Backend. Description là giải thích ngắn gọn feature flag làm gì khi enabled (giúp hiểu sau này).
Screenshot dưới cho thấy sau khi fill details. Click nút Create Feature tạo flag.

Beta Feature Flag
Tạo flag thứ hai beta. Process giống flag đầu, nhưng không cần set flag value, để trống column đó. Sau khi tạo cả hai, dashboard trông như này. Hiển thị flag name, value, current state (view), v.v.

Lấy Access Key
Để lấy Access Key, click SDK Keys từ sidebar, click nút Create Server-side Environment Key generate key. Vì app server-side, tốt dùng key đó. Copy paste key vào value trong .env cho key FLAGSMITH_ENVIRONMENT_KEY.

Chạy API
Mọi thứ set, quay lại IDE chạy server execute go run main.go trong terminal. Sẽ thấy message này trong terminal. Nếu encounter errors, check packages installed correctly, variables set correctly, app access Redis instance.

Giờ visit localhost:8080/ping, nhận message {"Your left over API request is":19}. Limit 20, request một lần, remaining 19.

Cập nhật rate_limit Flag
Update rate_limit flag value thành 10 xem sao. Lại visit Flagsmith dashboard click flag name. Side menu bar mở. Update value thành 10, click nút Update Feature Value.
Cũng có thể schedule update. Ví dụ, useful khi expect traffic spike tại certain timeframe và giảm limit per user để giảm server load.

Bây giờ visit localhost:8080/ping, nhận message {"Your left over API request is":8} – vì total limit 10 và đã request hai lần.

Test /beta endpoint. Visit localhost:8080/beta, thấy message {"message":"This is beta endpoint"}.

Quay lại Flagsmith dashboard toggle switch disable flag này. Visit URL. Nhận 404 message như endpoint không tồn tại.

Đã setup functionality và demo feature flagging capabilities, xem cách integrate Flagsmith GitHub App.
Cách tích hợp Feature Flags với GitHub App
Đảm bảo đã push app lên GitHub. Sau đó, install GitHub Flagsmith App trên repo từ GitHub Marketplace.
Bằng cách integrate GitHub và Flagsmith, chúng ta view updates feature flags/features as comments trong GitHub Issues và Pull Requests. Cho phép dễ track features, từ tạo issue đến merge PR và deploy changes.

Chọn organisation và repositories muốn install app. Có thể install all repos hoặc select particular one.
Khi install, auto-redirect về Flagsmith dashboard configure và complete integration. Hầu hết data pre-populated, chỉ select và add project, save configuration.

Khi bấm Save Configuration Button, redirect về main Flagsmith dashboard nơi làm việc trước.
Giờ link một existing flag với GitHub issue/pull request (raise dummy PR/issue test), hoặc tạo flag mới test. Tiến hành với beta flag đã tạo cho beta endpoint.
Để link flag với existing issue hoặc pull request, click flag name, side menu pop up từ phải. Chọn tab 'Link'. Chọn Pull Request option, chọn Pull Request muốn link. Tất cả Issues và Pull Requests linked với flag hiển thị dưới:

Verify flag successfully linked, click hyperlink với arrow icon dưới column heading Name. Navigate đến Issue/Pull Request cụ thể trên GitHub. Bạn thấy Flagsmith GitHub App comment dưới với all details, như environment, enabled value, v.v.

Test Flagsmith GitHub App
Sau này, khi bạn thay đổi flag settings, như bật/tắt flag hoặc đổi value, bot sẽ comment với updated details.
Test bằng cách tắt flag. Ngay khi tắt flash từ Dashboard, bot comment flag đã disabled:

Đó là cách simple integrate Flagsmith với GitHub.
Kết luận
Tóm lại, bạn biết cách leverage feature flags as backend developer thay đổi functionality app on the fly.
Để level up, integrate demo app với Flagsmith GitHub app để stay updated với changes feature flags' status trên Pull Requests/Issues không cần manually update.
Check Flagsmith repo here và đừng quên star các projects để support. Bạn cũng join amazing community để get technical support.
Kết nối với tôi - Pradumna Saraf, trên socials here.
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