دليل هندسي متقدم: Freelance Golang Programmer: Distributed API Gateways & Redis Lua Rate Limiting. ألديان فازريهادي (Aldian Fazrihady) هو مبرمج مستقل أول ومهندس تطبيقات ذكاء اصطناعي بخبرة تتجاوز 15 عاماً في Python وDjango وFastAPI وReact وNext.js وTypeScript وGolang وأنظمة الذكاء الاصطناعي (RAG وMCP وGoogle ADK).

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
}

روابط سريعة وتوظيف مباشر


About the Author — Hire Aldian Fazrihady (Cloud, GCP, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Engineer (Google Cloud Certified Professional Cloud Architect & Professional Data Engineer), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

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

Related Engineering Articles

Engineering Specializations & Category Hubs