Panduan Teknis Lengkap: Freelance Golang Programmer: Distributed API Gateways & Redis Lua Rate Limiting. Aldian Fazrihady adalah Senior Freelance Programmer & AI Application Engineer dengan pengalaman 15+ tahun di Python (Django, FastAPI), React/Next.js/TypeScript, Golang, dan sistem AI (RAG, MCP, Google ADK, LangGraph).

Protect high-throughput APIs and AI token budgets by hiring freelance Golang programmer Aldian Fazrihady to build atomic Redis Lua token-bucket rate limiters.

package ratelimit

import (
	"context"
	"time"
	"github.com/redis/go-redis/v9"
)

var tokenBucketLua = redis.NewScript(`
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now_ms = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])

local data = redis.call("HMGET", key, "tokens", "last_ms")
local tokens = tonumber(data[1])
local last_ms = tonumber(data[2])

if tokens == nil then
  tokens = capacity
  last_ms = now_ms
else
  local elapsed = math.max(0, now_ms - last_ms)
  tokens = math.min(capacity, tokens + (elapsed * refill_rate / 1000.0))
  last_ms = now_ms
end

if tokens >= requested then
  tokens = tokens - requested
  redis.call("HMSET", key, "tokens", tokens, "last_ms", last_ms)
  redis.call("PEXPIRE", key, 3600000)
  return 1
end
return 0
`)

func AllowRequest(ctx context.Context, rdb *redis.Client, tenantKey string, capacity, ratePerSec, cost int) (bool, error) {
	res, err := tokenBucketLua.Run(ctx, rdb, []string{tenantKey}, capacity, ratePerSec, time.Now().UnixMilli(), cost).Int()
	return res == 1, err
}

Hub Kategori & Konsultasi Proyek


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs