Bài này gộp 4 chủ đề: AWS SDK for Go v2 (config, client, paginator, lỗi, retry, test), Lambda bằng Go trên runtime
provided.al2023, Build container nhỏ (multi-stage, distroless/scratch) và cross-compile, Profiling vớipprofvà tinh chỉnh runtime trong container.
Mục tiêu học tập
- Khởi tạo AWS SDK for Go v2 đúng cách: một lần, dùng lại client, truyền
ctxcho từng lời gọi - Dùng paginator, xử lý lỗi bằng
smithy.APIErrorvà lỗi có kiểu của từng service, cấu hình retry và timeout - Viết code dùng SDK mà vẫn unit test được bằng interface nhỏ ở phía dùng
- Viết, build và deploy Lambda bằng Go trên
provided.al2023(arm64,bootstrap,-tags lambda.norpc); hiểu vì sao không còngo1.x - Viết Dockerfile multi-stage ra image vài MB, chọn giữa
scratchvà distroless, chạy non-root - Cross-compile cho
linux/arm64(Graviton), nhúng phiên bản vào binary - Thu và đọc profile CPU, heap, goroutine bằng
pprofmà không mở lỗ hổng ra internet - Biết
GOMAXPROCS,GOMEMLIMITvà PGO ảnh hưởng gì khi chạy trong container
Phần 1: AWS SDK for Go v2
1. Cài đặt và khởi tạo
SDK v1 (github.com/aws/aws-sdk-go) đã hết hỗ trợ từ 31/07/2025. Dùng v2: mỗi service là một module riêng, chỉ kéo về những gì bạn dùng.
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/dynamodb
go get github.com/aws/aws-sdk-go-v2/service/s3
go get github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue
func newClients(ctx context.Context) (*dynamodb.Client, *s3.Client, error) {
cfg, err := config.LoadDefaultConfig(ctx,
config.WithRegion("ap-southeast-1"), // bỏ qua để lấy từ AWS_REGION / ~/.aws/config
)
if err != nil {
return nil, nil, fmt.Errorf("load aws config: %w", err)
}
return dynamodb.NewFromConfig(cfg), s3.NewFromConfig(cfg), nil
}
LoadDefaultConfigdò credential theo chuỗi mặc định của AWS SDK: biến môi trường, file~/.aws/configvà~/.aws/credentials(kể cả profile SSO, assume role), web identity token (IRSA trên EKS), credential của ECS task role, và IMDS trên EC2. Code giống nhau ở máy dev, ECS, Lambda; chỉ môi trường khác nhau.- Tạo client một lần lúc khởi động và dùng lại: client an toàn khi dùng đồng thời từ nhiều goroutine và giữ connection pool. Tạo client mới cho mỗi request làm mất keep-alive và tốn thời gian.
- Field trong input là con trỏ để phân biệt "không đặt" với zero value. Dùng helper
aws.String("x"),aws.Int32(25),aws.ToString(p)(trả""nếu nil). - Tuỳ chọn theo từng lời gọi qua functional option:
client.GetObject(ctx, in, func(o *s3.Options) { o.Region = "us-east-1" }). - Chạy với DynamoDB Local hoặc LocalStack:
dynamodb.NewFromConfig(cfg, func(o *dynamodb.Options) { o.BaseEndpoint = aws.String("http://localhost:8000") }).
2. Đọc, ghi DynamoDB và paginator
type OrderItem struct {
PK string `dynamodbav:"pk"`
SK string `dynamodbav:"sk"`
Customer string `dynamodbav:"customer"`
Total int64 `dynamodbav:"total"`
CreatedAt string `dynamodbav:"created_at"`
}
func (s *Store) Create(ctx context.Context, it OrderItem) error {
av, err := attributevalue.MarshalMap(it)
if err != nil {
return fmt.Errorf("marshal order %s: %w", it.PK, err)
}
_, err = s.db.PutItem(ctx, &dynamodb.PutItemInput{
TableName: aws.String(s.table),
Item: av,
ConditionExpression: aws.String("attribute_not_exists(pk)"), // không ghi đè đơn đã có
})
if err != nil {
var ccf *types.ConditionalCheckFailedException
if errors.As(err, &ccf) {
return order.ErrAlreadyExists
}
return fmt.Errorf("put order %s: %w", it.PK, err)
}
return nil
}
API trả kết quả theo trang (ListObjectsV2, Query, Scan) có paginator sẵn. Kết hợp với iterator (Ngày 2) để người gọi duyệt từng phần tử mà không cần biết về trang:
func (s *Store) ObjectKeys(ctx context.Context, bucket, prefix string) iter.Seq2[string, error] {
return func(yield func(string, error) bool) {
p := s3.NewListObjectsV2Paginator(s.s3, &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
Prefix: aws.String(prefix),
})
for p.HasMorePages() {
page, err := p.NextPage(ctx)
if err != nil {
yield("", err)
return
}
for _, obj := range page.Contents {
if !yield(aws.ToString(obj.Key), nil) {
return
}
}
}
}
}
for key, err := range store.ObjectKeys(ctx, "invoices", "2026/11/") {
if err != nil {
return err
}
fmt.Println(key)
}
3. Lỗi, retry, timeout
Mọi lỗi từ client được bọc trong *smithy.OperationError (tên service, operation). Lỗi do service trả về thoả interface smithy.APIError; lỗi đã được mô hình hoá có kiểu riêng trong package types của service.
import (
"github.com/aws/smithy-go"
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
)
out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{Bucket: &bucket, Key: &key})
if err != nil {
var nsk *s3types.NoSuchKey
if errors.As(err, &nsk) {
return nil, ErrInvoiceNotFound // lỗi có kiểu: rõ ràng nhất
}
var ae smithy.APIError
if errors.As(err, &ae) && ae.ErrorCode() == "AccessDenied" {
return nil, fmt.Errorf("check task role policy: %w", err)
}
var re *awshttp.ResponseError
if errors.As(err, &re) {
s.logger.Error("s3 get failed", "request_id", re.ServiceRequestID(), "err", err)
}
return nil, fmt.Errorf("get invoice %s: %w", key, err)
}
defer out.Body.Close() // Body là stream: luôn đóng
- Retry mặc định:
retry.Standard, tối đa 3 lần thử, backoff tối đa 20 giây, có token bucket hạn chế retry khi lỗi dồn dập. Lỗi throttling và lỗi mạng tạm thời được retry tự động; bạn không cần tự viết vòng retry quanh lời gọi SDK. - Nâng số lần thử:
Cảnh báo:cfg, err := config.LoadDefaultConfig(ctx, config.WithRetryer(func() aws.Retryer { return retry.AddWithMaxAttempts(retry.NewStandard(), 5) }))retry.AddWithMaxAttempts(..., 0)nghĩa là retry không giới hạn, dễ thành vòng lặp tốn tiền. - Timeout đặt bằng context cho từng lời gọi:
ctx, cancel := context.WithTimeout(ctx, 2*time.Second). Khi context bị huỷ, SDK dừng và không retry nữa.
4. Unit test code dùng SDK
Đừng fake cả *dynamodb.Client (hàng chục method). Khai báo interface ở phía dùng, đúng chữ ký method của client, chỉ gồm những gì bạn gọi:
type dynamoAPI interface {
PutItem(ctx context.Context, in *dynamodb.PutItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)
GetItem(ctx context.Context, in *dynamodb.GetItemInput, optFns ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)
}
type Store struct {
db dynamoAPI // *dynamodb.Client thoả interface này một cách ngầm định
table string
}
type fakeDynamo struct {
putErr error
puts []*dynamodb.PutItemInput
}
func (f *fakeDynamo) PutItem(_ context.Context, in *dynamodb.PutItemInput, _ ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error) {
f.puts = append(f.puts, in)
return &dynamodb.PutItemOutput{}, f.putErr
}
func (f *fakeDynamo) GetItem(context.Context, *dynamodb.GetItemInput, ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error) {
return &dynamodb.GetItemOutput{}, nil
}
func TestCreate_Duplicate(t *testing.T) {
f := &fakeDynamo{putErr: &types.ConditionalCheckFailedException{}}
s := &Store{db: f, table: "orders"}
err := s.Create(t.Context(), OrderItem{PK: "o-1"})
if !errors.Is(err, order.ErrAlreadyExists) {
t.Fatalf("err = %v, want ErrAlreadyExists", err)
}
}
Kiểm tra thêm các lời gọi thật (điều kiện, index, quyền IAM) bằng integration test với DynamoDB Local hoặc tài khoản test, tách bằng build tag (Ngày 5).
Phần 2: Lambda bằng Go
1. Runtime: chỉ còn provided.al2023
Go biên dịch ra binary nên Lambda chạy Go trên OS-only runtime (họ provided). Theo bảng runtime của Lambda tại thời điểm viết (11/2026):
| Runtime | Hệ điều hành | Trạng thái |
|---|---|---|
provided.al2023 | Amazon Linux 2023 | Được hỗ trợ, dự kiến deprecate 30/06/2029 |
provided.al2 | Amazon Linux 2 | Đã deprecate từ 31/07/2026; chặn tạo mới từ 29/07/2027 |
go1.x | Amazon Linux | Đã deprecate từ 08/01/2024; chặn cập nhật từ 31/08/2027 |
So với go1.x, runtime provided hỗ trợ arm64 (Graviton), binary nhỏ hơn và invoke nhanh hơn một chút. Chuyển từ go1.x không cần sửa code, chỉ đổi cách build và runtime. (Tài liệu AWS hiện gọi loại function này là "Lambda Event Functions"; nội dung bài vẫn dùng "Lambda function".)
2. Handler
package main
import (
"context"
"encoding/json"
"log/slog"
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
)
type app struct {
store *Store
logger *slog.Logger
}
// Xử lý batch SQS; chỉ báo lại message lỗi để SQS không gửi lại cả batch.
func (a *app) handle(ctx context.Context, ev events.SQSEvent) (events.SQSEventResponse, error) {
var resp events.SQSEventResponse
for _, msg := range ev.Records {
var it OrderItem
err := json.Unmarshal([]byte(msg.Body), &it)
if err == nil {
err = a.store.Create(ctx, it)
}
if err != nil {
a.logger.ErrorContext(ctx, "process message", "message_id", msg.MessageId, "err", err)
resp.BatchItemFailures = append(resp.BatchItemFailures,
events.SQSBatchItemFailure{ItemIdentifier: msg.MessageId})
}
}
return resp, nil
}
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// Khởi tạo một lần trong init phase, dùng lại qua nhiều lần invoke.
cfg, err := config.LoadDefaultConfig(context.Background())
if err != nil {
logger.Error("load aws config", "err", err)
os.Exit(1)
}
a := &app{
store: &Store{db: dynamodb.NewFromConfig(cfg), table: os.Getenv("ORDERS_TABLE")},
logger: logger,
}
lambda.Start(a.handle)
}
- Chữ ký handler hợp lệ: 0-2 đối số (nếu 2 thì đầu tiên là
context.Context), 0-2 giá trị trả về (nếu có thì cuối cùng làerror). Kiểu input/output phải dùng được vớiencoding/json. Packageeventscó sẵn kiểu cho SQS, SNS, S3, API Gateway, EventBridge... - Khởi tạo client SDK ngoài handler (trong
maintrướclambda.Start, hoặcinit): execution environment được dùng lại giữa các lần invoke nên client và connection pool được dùng lại. - Không lưu dữ liệu của request trong biến toàn cục: lần invoke sau (có thể của người dùng khác) sẽ thấy.
ctxmang deadline của lần invoke: truyền nó vào mọi lời gọi SDK để dừng trước khi Lambda timeout. Packagelambdacontextlấy request ID của lần invoke.- Partial batch response (
BatchItemFailures) chỉ có tác dụng khi event source mapping bậtReportBatchItemFailures.
3. Build và deploy dạng .zip
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 \
go build -tags lambda.norpc -trimpath -ldflags="-s -w" -o bootstrap ./cmd/order-worker
zip order-worker.zip bootstrap
aws lambda create-function --function-name order-worker \
--runtime provided.al2023 --handler bootstrap \
--architectures arm64 \
--role arn:aws:iam::111122223333:role/order-worker-role \
--zip-file fileb://order-worker.zip
- File thực thi phải tên
bootstrapvà nằm ở gốc file zip. Giá trị--handlerkhông quan trọng với runtimeprovided(quy ước đặtbootstrap). -tags lambda.norpcbỏ phần RPC củaaws-lambda-go, phần chỉ cần cho runtimego1.xđã deprecate; binary nhỏ hơn.--architecturesmặc định làx86_64; với arm64 phải đặt rõ, vàGOARCHphải khớp. Sai kiến trúc thì function lỗi ngay khi khởi động.- Với AWS SAM:
Runtime: provided.al2023,Handler: bootstrap, vàMetadata: BuildMethod: go1.x. Ở đâygo1.xlà tên cách build của SAM, không phải runtime cũ; dễ nhầm khi review template.
4. Lambda dạng container image
Base image public.ecr.aws/lambda/provided:al2023 đã có sẵn Runtime Interface Emulator để test local:
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -tags lambda.norpc -o /out/main ./cmd/order-worker
FROM public.ecr.aws/lambda/provided:al2023
COPY --from=build /out/main ./main
ENTRYPOINT ["./main"]
docker buildx build --platform linux/arm64 --provenance=false -t order-worker:dev .
docker run -d -p 9000:8080 --entrypoint /usr/local/bin/aws-lambda-rie order-worker:dev ./main
curl "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"Records":[]}'
Với container image, binary đặt tên gì cũng được. --provenance=false cần để image tương thích với Lambda khi build bằng buildx.
Phần 3: Container nhỏ và cross-compile
1. Dockerfile multi-stage cho service trên ECS/EKS
# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM golang:1.27 AS build
ARG TARGETOS TARGETARCH VERSION=dev
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" \
-o /out/orders-api ./cmd/orders-api
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/orders-api /orders-api
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/orders-api"]
docker buildx build --platform linux/arm64,linux/amd64 --build-arg VERSION=1.4.2 -t orders-api:1.4.2 .
Giải thích các lựa chọn:
FROM --platform=$BUILDPLATFORM: stage build chạy native trên máy build, Go cross-compile sangTARGETARCH. Nhanh hơn nhiều so với build trong giả lập QEMU.- Copy
go.mod/go.sumvàgo mod downloadtrước khi copy source: layer dependency được cache, sửa code không tải lại module. Cache mount giữ cả build cache của Go giữa các lần build. CGO_ENABLED=0: binary tĩnh, không phụ thuộc libc, chạy được trên image không có libc.-trimpath: bỏ đường dẫn máy build khỏi binary.-ldflags="-s -w": bỏ bảng symbol và DWARF, binary nhỏ hơn; stack trace khi panic vàpprofvẫn có tên hàm vì Go dùng bảng thông tin riêng của runtime.- Image cuối chỉ chứa binary: không shell, không package manager, bề mặt tấn công nhỏ.
| Image cuối | Có gì | Khi nào dùng |
|---|---|---|
scratch | Không có gì | Muốn nhỏ tuyệt đối và tự lo CA certificate, tzdata, user |
gcr.io/distroless/static-debian13 (khoảng 2 MiB) | CA certificates, tzdata, /etc/passwd (có user nonroot), /tmp; không glibc | Mặc định cho binary Go tĩnh |
gcr.io/distroless/base-debian13 | Như trên + glibc, libssl | Binary dùng cgo |
alpine | Shell, apk, musl | Cần shell để debug; chấp nhận bề mặt tấn công lớn hơn |
Bẫy khi dùng scratch:
- Không có CA certificate: mọi lời gọi HTTPS (kể cả tới AWS API) lỗi
x509: certificate signed by unknown authority. Phải copy/etc/ssl/certs/ca-certificates.crttừ stage build. - Không có tzdata:
time.LoadLocation("Asia/Ho_Chi_Minh")lỗi. Sửa bằngimport _ "time/tzdata"hoặc build với-tags timetzdatađể nhúng tzdata vào binary. - Không có shell: health check dạng
CMD-SHELL curl ...trong ECS không chạy được. Dùng health check của ALB/target group, hoặc thêm lệnh conorders-api healthcheckvào chính binary.
2. Cross-compile và nhúng phiên bản
go tool dist list | grep linux # các cặp GOOS/GOARCH hỗ trợ
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o dist/orders-cli-linux-arm64 ./cmd/orders-cli
GOOS=darwin GOARCH=arm64 go build -o dist/orders-cli-darwin-arm64 ./cmd/orders-cli
GOOS=windows GOARCH=amd64 go build -o dist/orders-cli.exe ./cmd/orders-cli
- Cross-compile thuần Go chỉ cần đặt
GOOS/GOARCH; không cần máy đích. Có cgo thì cần toolchain C cho nền tảng đích, phức tạp hơn nhiều: lý do chính để giữCGO_ENABLED=0cho service và CLI. - Graviton (arm64) thường rẻ hơn x86 cùng cấu hình; với Go, chuyển sang arm64 thường chỉ là đổi
GOARCH. - Nhúng phiên bản:
-ldflags "-X main.version=1.4.2"gán vào biếnvar version = "dev"trong packagemain. Khi build trong git repo, Go còn tự nhúng commit (vcs.revision,vcs.time,vcs.modified), đọc bằngdebug.ReadBuildInfo(); build trong Docker mà không copy.gitthì không có thông tin này, nên vẫn cần-X.
Phần 4: pprof và runtime trong container
1. Mở endpoint pprof an toàn
import _ "net/http/pprof" đăng ký handler vào http.DefaultServeMux. Nếu service phục vụ public cũng dùng DefaultServeMux (ví dụ http.ListenAndServe(":8080", nil)), profile và thông tin nội bộ bị lộ ra internet. Cách an toàn là một server admin riêng, chỉ nghe trên localhost:
import "net/http/pprof"
func startAdmin(logger *slog.Logger) {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index) // heap, goroutine, allocs, goroutineleak...
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
srv := &http.Server{Addr: "127.0.0.1:6060", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("admin server", "err", err)
}
}()
}
Truy cập từ máy dev qua ECS Exec hoặc SSM port forwarding, không mở port trong security group.
2. Thu và đọc profile
# CPU 30 giây từ service đang chạy
go tool pprof -http=:8081 'http://localhost:6060/debug/pprof/profile?seconds=30'
# Bộ nhớ đang dùng
go tool pprof -http=:8081 http://localhost:6060/debug/pprof/heap
# Goroutine gom theo stack: tìm hàng nghìn goroutine kẹt cùng một dòng
curl -s 'http://localhost:6060/debug/pprof/goroutine?debug=1' | head -50
# Từ Go 1.27: goroutine bị chặn vĩnh viễn (rò)
curl -s 'http://localhost:6060/debug/pprof/goroutineleak?debug=1'
# Profile từ benchmark
go test -run='^$' -bench=. -cpuprofile=cpu.out -memprofile=mem.out ./money
go tool pprof -top cpu.out
| Profile | Trả lời câu hỏi | Ghi chú |
|---|---|---|
profile (CPU) | Thời gian CPU tiêu vào đâu? | Lấy mẫu trong seconds giây |
heap | Bộ nhớ đang giữ (inuse) và đã cấp phát (alloc) ở đâu? | Chọn sample_index=inuse_space hoặc alloc_space |
goroutine | Goroutine đang làm gì, có bị kẹt không? | debug=1 gom theo stack, debug=2 in từng goroutine |
goroutineleak | Goroutine nào không bao giờ được đánh thức nữa? | Chính thức từ Go 1.27 |
mutex, block | Tranh chấp lock, chờ đồng bộ ở đâu? | Phải bật bằng runtime.SetMutexProfileFraction, runtime.SetBlockProfileRate |
Trong giao diện web (-http), từ Go 1.26 view mặc định là flame graph: chiều ngang là tỷ lệ thời gian/bộ nhớ, đọc từ dưới lên theo stack. Trong chế độ dòng lệnh, top xem hàm tốn nhất, list TênHàm xem từng dòng code.
Quy trình tối ưu: đo (benchmark, profile) → tìm điểm nóng → sửa một chỗ → đo lại bằng benchstat. Đừng tối ưu theo cảm giác.
3. Runtime trong container
| Thiết lập | Ý nghĩa | Khuyến nghị |
|---|---|---|
GOMAXPROCS | Số thread chạy code Go đồng thời | Từ Go 1.25 tự theo CPU limit của cgroup trên Linux; thường không cần đặt |
GOMEMLIMIT (Go 1.19+) | Giới hạn mềm bộ nhớ: GC chạy thường xuyên hơn khi heap tiến gần mức này | Đặt khoảng 80-90% memory limit của container để giảm nguy cơ bị OOM kill; runtime không tự suy ra giá trị này từ cgroup như với GOMAXPROCS (theo release notes tới Go 1.27) |
GOGC | Tần suất GC theo tỷ lệ tăng heap (mặc định 100) | Thường giữ mặc định khi đã đặt GOMEMLIMIT |
| PGO (Go 1.21+) | Tối ưu theo profile CPU thật | Lưu một CPU profile từ production thành default.pgo trong thư mục package main; go build tự dùng |
Từ Go 1.26, Green Tea GC được bật mặc định, giảm chi phí GC cho chương trình cấp phát nhiều; phần lớn service không cần chỉnh gì để hưởng lợi.
Câu hỏi ôn tập
-
Vì sao nên tạo
dynamodb.Clientmột lần lúc khởi động thay vì trong mỗi request?Xem đáp án
Client an toàn khi dùng đồng thời và giữ connection pool; tạo mới mỗi request làm mất keep-alive (thêm TLS handshake), tốn CPU và thời gian dò credential. Trong Lambda, tạo ở init phase còn giúp các lần invoke sau trên cùng execution environment dùng lại client.
-
Viết đoạn code phân biệt
ConditionalCheckFailedExceptionvới các lỗi khác khiPutItem.Xem đáp án
var ccf *types.ConditionalCheckFailedException; if errors.As(err, &ccf) { return order.ErrAlreadyExists }, các lỗi khác wrap thêm ngữ cảnh và trả lên. Lỗi có kiểu của từng service nằm trong packagetypescủa service đó; lỗi chung dùngsmithy.APIErrorvàErrorCode(). -
Đồng nghiệp bọc mỗi lời gọi DynamoDB trong vòng lặp retry 5 lần tự viết. Góp ý gì?
Xem đáp án
SDK đã retry lỗi tạm thời (throttling, lỗi mạng) với backoff và token bucket, mặc định 3 lần thử. Vòng tự viết nhân số lần thử lên (5 × 3), làm tình trạng throttling tệ hơn. Nếu cần nhiều lần thử hơn, cấu hình retryer của SDK (
retry.AddWithMaxAttempts), và đặt timeout bằng context. -
Làm sao unit test
Store.Createmà không gọi AWS và không fake toàn bộ client?Xem đáp án
Khai báo interface ở phía dùng chỉ gồm method cần (ví dụ
PutItem) với đúng chữ ký của client, gồm cảoptFns ...func(*dynamodb.Options).*dynamodb.Clientthoả nó ngầm định; trong test, dùng fake trả lỗi hay kết quả mong muốn. -
Function Go vẫn dùng runtime
go1.x. Cần đổi những gì để chuyển sangprovided.al2023trên arm64?Xem đáp án
Code handler không cần sửa. Build với
GOOS=linux GOARCH=arm64, đặt tên binarybootstrapở gốc zip, nên thêm-tags lambda.norpc; đổi runtime sangprovided.al2023và--architectures arm64.provided.al2không còn là lựa chọn vì đã deprecate từ 31/07/2026. -
Template SAM có
BuildMethod: go1.xvàRuntime: provided.al2023. Có mâu thuẫn không?Xem đáp án
Không.
BuildMethod: go1.xlà tên cách build của SAM CLI (biên dịch Go thànhbootstrap), còn runtime thực tế làprovided.al2023. Chỉ cóRuntime: go1.xmới là runtime đã deprecate. -
Service chạy trên image
scratchgọi DynamoDB lỗix509: certificate signed by unknown authority. Nguyên nhân và hai cách sửa?Xem đáp án
scratchkhông có CA certificate nên không xác thực được chứng chỉ TLS của AWS. Sửa: copy file CA bundle từ stage build vào image, hoặc chuyển sanggcr.io/distroless/static-debian13đã có sẵn CA certificate (và tzdata, user nonroot). -
Vì sao Dockerfile dùng
FROM --platform=$BUILDPLATFORM golang:1.27cho stage build khi build image arm64 trên máy x86?Xem đáp án
Để stage build chạy native trên kiến trúc của máy build và để Go cross-compile sang
TARGETARCH. Không có nó, buildx chạy toàn bộ quá trình biên dịch trong giả lập QEMU, chậm hơn nhiều lần. -
Vì sao không nên
import _ "net/http/pprof"trong service public dùnghttp.ListenAndServe(":8080", nil)?Xem đáp án
Import đó đăng ký
/debug/pprof/vàoDefaultServeMux, chính là handler màListenAndServe(..., nil)phục vụ, nên ai cũng xem được profile, cmdline và có thể chạy profile CPU tốn tài nguyên. Dùng server admin riêng nghe trên127.0.0.1với mux riêng. -
Container giới hạn 1 GiB bộ nhớ bị OOM kill khi tải tăng đột biến dù heap trung bình chỉ 400 MiB. Thiết lập runtime nào giúp, và đặt thế nào?
Xem đáp án
GOMEMLIMIT, ví dụ khoảng900MiB: khi heap tiến gần giới hạn, GC chạy thường xuyên hơn thay vì để heap phình theoGOGCtới mức vượt limit của container. Đây là giới hạn mềm, không thay thế việc tìm nguyên nhân bằng profileheapnếu bộ nhớ thật sự cần vượt mức đó.
Bài tập thực hành
Bài 1: Store DynamoDB có test
Viết Store với Create (có ConditionExpression) và Get, dùng interface dynamoAPI. Unit test bằng fake cho ca tạo trùng; integration test (build tag integration) với DynamoDB Local.
Đầu ra mong đợi: go test ./... không cần mạng; go test -tags=integration ./store pass khi DynamoDB Local đang chạy.
Bài 2: Lambda worker arm64
Đóng gói handler SQS ở Phần 2 thành Lambda provided.al2023 arm64 bằng SAM hoặc AWS CLI, nối với một hàng đợi SQS có bật ReportBatchItemFailures. Gửi 10 message, trong đó 2 message JSON hỏng.
Đầu ra mong đợi: 8 đơn được ghi; 2 message hỏng quay lại hàng đợi (rồi vào DLQ sau số lần nhận tối đa); log JSON có message_id của 2 message lỗi.
Bài 3: Image nhỏ đa kiến trúc
Viết Dockerfile multi-stage cho orders-api, build cho linux/amd64 và linux/arm64, nhúng VERSION. Thêm endpoint /version trả phiên bản và vcs.revision (nếu có).
Đầu ra mong đợi: kích thước image cuối (ghi lại con số); docker run chạy với user nonroot; thử đổi image cuối sang scratch và ghi lại lỗi gặp phải khi gọi HTTPS.
Bài 4: Tìm điểm nóng bằng pprof
Thêm admin server pprof vào orders-api. Tạo tải bằng công cụ như hey hoặc vegeta vào GET /orders/{id}, thu CPU profile 30 giây và heap profile.
Đầu ra mong đợi: ảnh chụp flame graph; 3 hàm tốn CPU nhất; một cải tiến cụ thể được đo lại bằng benchmark và benchstat.
Tài liệu tham khảo
- AWS SDK for Go v2 Developer Guide
- AWS SDK for Go v2: Handling errors
- AWS SDK for Go v2: Retries and timeouts
- Lambda: Building functions with Go
- Lambda: Define handlers in Go
- Lambda: Deploy Go functions with .zip file archives
- Lambda: Deploy Go functions with container images
- Lambda runtimes
- aws-lambda-go
- Distroless container images
- Package net/http/pprof
- Diagnostics
- A Guide to the Go Garbage Collector (
GOGC,GOMEMLIMIT) - Profile-guided optimization